X86ISelLowering.cpp revision d642baf4be7cfed68fb8e7f326970f5797a2bdd4
1//===-- X86ISelLowering.cpp - X86 DAG Lowering Implementation -------------===//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file defines the interfaces that X86 uses to lower LLVM code into a
11// selection DAG.
12//
13//===----------------------------------------------------------------------===//
14
15#define DEBUG_TYPE "x86-isel"
16#include "X86ISelLowering.h"
17#include "X86.h"
18#include "X86InstrBuilder.h"
19#include "X86TargetMachine.h"
20#include "X86TargetObjectFile.h"
21#include "Utils/X86ShuffleDecode.h"
22#include "llvm/CallingConv.h"
23#include "llvm/Constants.h"
24#include "llvm/DerivedTypes.h"
25#include "llvm/GlobalAlias.h"
26#include "llvm/GlobalVariable.h"
27#include "llvm/Function.h"
28#include "llvm/Instructions.h"
29#include "llvm/Intrinsics.h"
30#include "llvm/LLVMContext.h"
31#include "llvm/CodeGen/IntrinsicLowering.h"
32#include "llvm/CodeGen/MachineFrameInfo.h"
33#include "llvm/CodeGen/MachineFunction.h"
34#include "llvm/CodeGen/MachineInstrBuilder.h"
35#include "llvm/CodeGen/MachineJumpTableInfo.h"
36#include "llvm/CodeGen/MachineModuleInfo.h"
37#include "llvm/CodeGen/MachineRegisterInfo.h"
38#include "llvm/MC/MCAsmInfo.h"
39#include "llvm/MC/MCContext.h"
40#include "llvm/MC/MCExpr.h"
41#include "llvm/MC/MCSymbol.h"
42#include "llvm/ADT/SmallSet.h"
43#include "llvm/ADT/Statistic.h"
44#include "llvm/ADT/StringExtras.h"
45#include "llvm/ADT/VariadicFunction.h"
46#include "llvm/Support/CallSite.h"
47#include "llvm/Support/Debug.h"
48#include "llvm/Support/ErrorHandling.h"
49#include "llvm/Support/MathExtras.h"
50#include "llvm/Target/TargetOptions.h"
51#include <bitset>
52#include <cctype>
53using namespace llvm;
54
55STATISTIC(NumTailCalls, "Number of tail calls");
56
57// Forward declarations.
58static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
59                       SDValue V2);
60
61/// Generate a DAG to grab 128-bits from a vector > 128 bits.  This
62/// sets things up to match to an AVX VEXTRACTF128 instruction or a
63/// simple subregister reference.  Idx is an index in the 128 bits we
64/// want.  It need not be aligned to a 128-bit bounday.  That makes
65/// lowering EXTRACT_VECTOR_ELT operations easier.
66static SDValue Extract128BitVector(SDValue Vec, unsigned IdxVal,
67                                   SelectionDAG &DAG, DebugLoc dl) {
68  EVT VT = Vec.getValueType();
69  assert(VT.is256BitVector() && "Unexpected vector size!");
70  EVT ElVT = VT.getVectorElementType();
71  unsigned Factor = VT.getSizeInBits()/128;
72  EVT ResultVT = EVT::getVectorVT(*DAG.getContext(), ElVT,
73                                  VT.getVectorNumElements()/Factor);
74
75  // Extract from UNDEF is UNDEF.
76  if (Vec.getOpcode() == ISD::UNDEF)
77    return DAG.getUNDEF(ResultVT);
78
79  // Extract the relevant 128 bits.  Generate an EXTRACT_SUBVECTOR
80  // we can match to VEXTRACTF128.
81  unsigned ElemsPerChunk = 128 / ElVT.getSizeInBits();
82
83  // This is the index of the first element of the 128-bit chunk
84  // we want.
85  unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits()) / 128)
86                               * ElemsPerChunk);
87
88  SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal);
89  SDValue Result = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, ResultVT, Vec,
90                               VecIdx);
91
92  return Result;
93}
94
95/// Generate a DAG to put 128-bits into a vector > 128 bits.  This
96/// sets things up to match to an AVX VINSERTF128 instruction or a
97/// simple superregister reference.  Idx is an index in the 128 bits
98/// we want.  It need not be aligned to a 128-bit bounday.  That makes
99/// lowering INSERT_VECTOR_ELT operations easier.
100static SDValue Insert128BitVector(SDValue Result, SDValue Vec,
101                                  unsigned IdxVal, SelectionDAG &DAG,
102                                  DebugLoc dl) {
103  // Inserting UNDEF is Result
104  if (Vec.getOpcode() == ISD::UNDEF)
105    return Result;
106
107  EVT VT = Vec.getValueType();
108  assert(VT.is128BitVector() && "Unexpected vector size!");
109
110  EVT ElVT = VT.getVectorElementType();
111  EVT ResultVT = Result.getValueType();
112
113  // Insert the relevant 128 bits.
114  unsigned ElemsPerChunk = 128/ElVT.getSizeInBits();
115
116  // This is the index of the first element of the 128-bit chunk
117  // we want.
118  unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits())/128)
119                               * ElemsPerChunk);
120
121  SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal);
122  return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Result, Vec,
123                     VecIdx);
124}
125
126/// Concat two 128-bit vectors into a 256 bit vector using VINSERTF128
127/// instructions. This is used because creating CONCAT_VECTOR nodes of
128/// BUILD_VECTORS returns a larger BUILD_VECTOR while we're trying to lower
129/// large BUILD_VECTORS.
130static SDValue Concat128BitVectors(SDValue V1, SDValue V2, EVT VT,
131                                   unsigned NumElems, SelectionDAG &DAG,
132                                   DebugLoc dl) {
133  SDValue V = Insert128BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
134  return Insert128BitVector(V, V2, NumElems/2, DAG, dl);
135}
136
137static TargetLoweringObjectFile *createTLOF(X86TargetMachine &TM) {
138  const X86Subtarget *Subtarget = &TM.getSubtarget<X86Subtarget>();
139  bool is64Bit = Subtarget->is64Bit();
140
141  if (Subtarget->isTargetEnvMacho()) {
142    if (is64Bit)
143      return new X86_64MachoTargetObjectFile();
144    return new TargetLoweringObjectFileMachO();
145  }
146
147  if (Subtarget->isTargetLinux())
148    return new X86LinuxTargetObjectFile();
149  if (Subtarget->isTargetELF())
150    return new TargetLoweringObjectFileELF();
151  if (Subtarget->isTargetCOFF() && !Subtarget->isTargetEnvMacho())
152    return new TargetLoweringObjectFileCOFF();
153  llvm_unreachable("unknown subtarget type");
154}
155
156X86TargetLowering::X86TargetLowering(X86TargetMachine &TM)
157  : TargetLowering(TM, createTLOF(TM)) {
158  Subtarget = &TM.getSubtarget<X86Subtarget>();
159  X86ScalarSSEf64 = Subtarget->hasSSE2();
160  X86ScalarSSEf32 = Subtarget->hasSSE1();
161
162  RegInfo = TM.getRegisterInfo();
163  TD = getDataLayout();
164
165  // Set up the TargetLowering object.
166  static const MVT IntVTs[] = { MVT::i8, MVT::i16, MVT::i32, MVT::i64 };
167
168  // X86 is weird, it always uses i8 for shift amounts and setcc results.
169  setBooleanContents(ZeroOrOneBooleanContent);
170  // X86-SSE is even stranger. It uses -1 or 0 for vector masks.
171  setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
172
173  // For 64-bit since we have so many registers use the ILP scheduler, for
174  // 32-bit code use the register pressure specific scheduling.
175  // For Atom, always use ILP scheduling.
176  if (Subtarget->isAtom())
177    setSchedulingPreference(Sched::ILP);
178  else if (Subtarget->is64Bit())
179    setSchedulingPreference(Sched::ILP);
180  else
181    setSchedulingPreference(Sched::RegPressure);
182  setStackPointerRegisterToSaveRestore(RegInfo->getStackRegister());
183
184  // Bypass i32 with i8 on Atom when compiling with O2
185  if (Subtarget->hasSlowDivide() && TM.getOptLevel() >= CodeGenOpt::Default)
186    addBypassSlowDiv(32, 8);
187
188  if (Subtarget->isTargetWindows() && !Subtarget->isTargetCygMing()) {
189    // Setup Windows compiler runtime calls.
190    setLibcallName(RTLIB::SDIV_I64, "_alldiv");
191    setLibcallName(RTLIB::UDIV_I64, "_aulldiv");
192    setLibcallName(RTLIB::SREM_I64, "_allrem");
193    setLibcallName(RTLIB::UREM_I64, "_aullrem");
194    setLibcallName(RTLIB::MUL_I64, "_allmul");
195    setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::X86_StdCall);
196    setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::X86_StdCall);
197    setLibcallCallingConv(RTLIB::SREM_I64, CallingConv::X86_StdCall);
198    setLibcallCallingConv(RTLIB::UREM_I64, CallingConv::X86_StdCall);
199    setLibcallCallingConv(RTLIB::MUL_I64, CallingConv::X86_StdCall);
200
201    // The _ftol2 runtime function has an unusual calling conv, which
202    // is modeled by a special pseudo-instruction.
203    setLibcallName(RTLIB::FPTOUINT_F64_I64, 0);
204    setLibcallName(RTLIB::FPTOUINT_F32_I64, 0);
205    setLibcallName(RTLIB::FPTOUINT_F64_I32, 0);
206    setLibcallName(RTLIB::FPTOUINT_F32_I32, 0);
207  }
208
209  if (Subtarget->isTargetDarwin()) {
210    // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
211    setUseUnderscoreSetJmp(false);
212    setUseUnderscoreLongJmp(false);
213  } else if (Subtarget->isTargetMingw()) {
214    // MS runtime is weird: it exports _setjmp, but longjmp!
215    setUseUnderscoreSetJmp(true);
216    setUseUnderscoreLongJmp(false);
217  } else {
218    setUseUnderscoreSetJmp(true);
219    setUseUnderscoreLongJmp(true);
220  }
221
222  // Set up the register classes.
223  addRegisterClass(MVT::i8, &X86::GR8RegClass);
224  addRegisterClass(MVT::i16, &X86::GR16RegClass);
225  addRegisterClass(MVT::i32, &X86::GR32RegClass);
226  if (Subtarget->is64Bit())
227    addRegisterClass(MVT::i64, &X86::GR64RegClass);
228
229  setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
230
231  // We don't accept any truncstore of integer registers.
232  setTruncStoreAction(MVT::i64, MVT::i32, Expand);
233  setTruncStoreAction(MVT::i64, MVT::i16, Expand);
234  setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
235  setTruncStoreAction(MVT::i32, MVT::i16, Expand);
236  setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
237  setTruncStoreAction(MVT::i16, MVT::i8,  Expand);
238
239  // SETOEQ and SETUNE require checking two conditions.
240  setCondCodeAction(ISD::SETOEQ, MVT::f32, Expand);
241  setCondCodeAction(ISD::SETOEQ, MVT::f64, Expand);
242  setCondCodeAction(ISD::SETOEQ, MVT::f80, Expand);
243  setCondCodeAction(ISD::SETUNE, MVT::f32, Expand);
244  setCondCodeAction(ISD::SETUNE, MVT::f64, Expand);
245  setCondCodeAction(ISD::SETUNE, MVT::f80, Expand);
246
247  // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
248  // operation.
249  setOperationAction(ISD::UINT_TO_FP       , MVT::i1   , Promote);
250  setOperationAction(ISD::UINT_TO_FP       , MVT::i8   , Promote);
251  setOperationAction(ISD::UINT_TO_FP       , MVT::i16  , Promote);
252
253  if (Subtarget->is64Bit()) {
254    setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Promote);
255    setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Custom);
256  } else if (!TM.Options.UseSoftFloat) {
257    // We have an algorithm for SSE2->double, and we turn this into a
258    // 64-bit FILD followed by conditional FADD for other targets.
259    setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Custom);
260    // We have an algorithm for SSE2, and we turn this into a 64-bit
261    // FILD for other targets.
262    setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Custom);
263  }
264
265  // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
266  // this operation.
267  setOperationAction(ISD::SINT_TO_FP       , MVT::i1   , Promote);
268  setOperationAction(ISD::SINT_TO_FP       , MVT::i8   , Promote);
269
270  if (!TM.Options.UseSoftFloat) {
271    // SSE has no i16 to fp conversion, only i32
272    if (X86ScalarSSEf32) {
273      setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
274      // f32 and f64 cases are Legal, f80 case is not
275      setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
276    } else {
277      setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Custom);
278      setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
279    }
280  } else {
281    setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
282    setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Promote);
283  }
284
285  // In 32-bit mode these are custom lowered.  In 64-bit mode F32 and F64
286  // are Legal, f80 is custom lowered.
287  setOperationAction(ISD::FP_TO_SINT     , MVT::i64  , Custom);
288  setOperationAction(ISD::SINT_TO_FP     , MVT::i64  , Custom);
289
290  // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
291  // this operation.
292  setOperationAction(ISD::FP_TO_SINT       , MVT::i1   , Promote);
293  setOperationAction(ISD::FP_TO_SINT       , MVT::i8   , Promote);
294
295  if (X86ScalarSSEf32) {
296    setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Promote);
297    // f32 and f64 cases are Legal, f80 case is not
298    setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
299  } else {
300    setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Custom);
301    setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
302  }
303
304  // Handle FP_TO_UINT by promoting the destination to a larger signed
305  // conversion.
306  setOperationAction(ISD::FP_TO_UINT       , MVT::i1   , Promote);
307  setOperationAction(ISD::FP_TO_UINT       , MVT::i8   , Promote);
308  setOperationAction(ISD::FP_TO_UINT       , MVT::i16  , Promote);
309
310  if (Subtarget->is64Bit()) {
311    setOperationAction(ISD::FP_TO_UINT     , MVT::i64  , Expand);
312    setOperationAction(ISD::FP_TO_UINT     , MVT::i32  , Promote);
313  } else if (!TM.Options.UseSoftFloat) {
314    // Since AVX is a superset of SSE3, only check for SSE here.
315    if (Subtarget->hasSSE1() && !Subtarget->hasSSE3())
316      // Expand FP_TO_UINT into a select.
317      // FIXME: We would like to use a Custom expander here eventually to do
318      // the optimal thing for SSE vs. the default expansion in the legalizer.
319      setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Expand);
320    else
321      // With SSE3 we can use fisttpll to convert to a signed i64; without
322      // SSE, we're stuck with a fistpll.
323      setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Custom);
324  }
325
326  if (isTargetFTOL()) {
327    // Use the _ftol2 runtime function, which has a pseudo-instruction
328    // to handle its weird calling convention.
329    setOperationAction(ISD::FP_TO_UINT     , MVT::i64  , Custom);
330  }
331
332  // TODO: when we have SSE, these could be more efficient, by using movd/movq.
333  if (!X86ScalarSSEf64) {
334    setOperationAction(ISD::BITCAST        , MVT::f32  , Expand);
335    setOperationAction(ISD::BITCAST        , MVT::i32  , Expand);
336    if (Subtarget->is64Bit()) {
337      setOperationAction(ISD::BITCAST      , MVT::f64  , Expand);
338      // Without SSE, i64->f64 goes through memory.
339      setOperationAction(ISD::BITCAST      , MVT::i64  , Expand);
340    }
341  }
342
343  // Scalar integer divide and remainder are lowered to use operations that
344  // produce two results, to match the available instructions. This exposes
345  // the two-result form to trivial CSE, which is able to combine x/y and x%y
346  // into a single instruction.
347  //
348  // Scalar integer multiply-high is also lowered to use two-result
349  // operations, to match the available instructions. However, plain multiply
350  // (low) operations are left as Legal, as there are single-result
351  // instructions for this in x86. Using the two-result multiply instructions
352  // when both high and low results are needed must be arranged by dagcombine.
353  for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
354    MVT VT = IntVTs[i];
355    setOperationAction(ISD::MULHS, VT, Expand);
356    setOperationAction(ISD::MULHU, VT, Expand);
357    setOperationAction(ISD::SDIV, VT, Expand);
358    setOperationAction(ISD::UDIV, VT, Expand);
359    setOperationAction(ISD::SREM, VT, Expand);
360    setOperationAction(ISD::UREM, VT, Expand);
361
362    // Add/Sub overflow ops with MVT::Glues are lowered to EFLAGS dependences.
363    setOperationAction(ISD::ADDC, VT, Custom);
364    setOperationAction(ISD::ADDE, VT, Custom);
365    setOperationAction(ISD::SUBC, VT, Custom);
366    setOperationAction(ISD::SUBE, VT, Custom);
367  }
368
369  setOperationAction(ISD::BR_JT            , MVT::Other, Expand);
370  setOperationAction(ISD::BRCOND           , MVT::Other, Custom);
371  setOperationAction(ISD::BR_CC            , MVT::Other, Expand);
372  setOperationAction(ISD::SELECT_CC        , MVT::Other, Expand);
373  if (Subtarget->is64Bit())
374    setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
375  setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16  , Legal);
376  setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8   , Legal);
377  setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1   , Expand);
378  setOperationAction(ISD::FP_ROUND_INREG   , MVT::f32  , Expand);
379  setOperationAction(ISD::FREM             , MVT::f32  , Expand);
380  setOperationAction(ISD::FREM             , MVT::f64  , Expand);
381  setOperationAction(ISD::FREM             , MVT::f80  , Expand);
382  setOperationAction(ISD::FLT_ROUNDS_      , MVT::i32  , Custom);
383
384  // Promote the i8 variants and force them on up to i32 which has a shorter
385  // encoding.
386  setOperationAction(ISD::CTTZ             , MVT::i8   , Promote);
387  AddPromotedToType (ISD::CTTZ             , MVT::i8   , MVT::i32);
388  setOperationAction(ISD::CTTZ_ZERO_UNDEF  , MVT::i8   , Promote);
389  AddPromotedToType (ISD::CTTZ_ZERO_UNDEF  , MVT::i8   , MVT::i32);
390  if (Subtarget->hasBMI()) {
391    setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16  , Expand);
392    setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32  , Expand);
393    if (Subtarget->is64Bit())
394      setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
395  } else {
396    setOperationAction(ISD::CTTZ           , MVT::i16  , Custom);
397    setOperationAction(ISD::CTTZ           , MVT::i32  , Custom);
398    if (Subtarget->is64Bit())
399      setOperationAction(ISD::CTTZ         , MVT::i64  , Custom);
400  }
401
402  if (Subtarget->hasLZCNT()) {
403    // When promoting the i8 variants, force them to i32 for a shorter
404    // encoding.
405    setOperationAction(ISD::CTLZ           , MVT::i8   , Promote);
406    AddPromotedToType (ISD::CTLZ           , MVT::i8   , MVT::i32);
407    setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8   , Promote);
408    AddPromotedToType (ISD::CTLZ_ZERO_UNDEF, MVT::i8   , MVT::i32);
409    setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16  , Expand);
410    setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32  , Expand);
411    if (Subtarget->is64Bit())
412      setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
413  } else {
414    setOperationAction(ISD::CTLZ           , MVT::i8   , Custom);
415    setOperationAction(ISD::CTLZ           , MVT::i16  , Custom);
416    setOperationAction(ISD::CTLZ           , MVT::i32  , Custom);
417    setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8   , Custom);
418    setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16  , Custom);
419    setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32  , Custom);
420    if (Subtarget->is64Bit()) {
421      setOperationAction(ISD::CTLZ         , MVT::i64  , Custom);
422      setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Custom);
423    }
424  }
425
426  if (Subtarget->hasPOPCNT()) {
427    setOperationAction(ISD::CTPOP          , MVT::i8   , Promote);
428  } else {
429    setOperationAction(ISD::CTPOP          , MVT::i8   , Expand);
430    setOperationAction(ISD::CTPOP          , MVT::i16  , Expand);
431    setOperationAction(ISD::CTPOP          , MVT::i32  , Expand);
432    if (Subtarget->is64Bit())
433      setOperationAction(ISD::CTPOP        , MVT::i64  , Expand);
434  }
435
436  setOperationAction(ISD::READCYCLECOUNTER , MVT::i64  , Custom);
437  setOperationAction(ISD::BSWAP            , MVT::i16  , Expand);
438
439  // These should be promoted to a larger select which is supported.
440  setOperationAction(ISD::SELECT          , MVT::i1   , Promote);
441  // X86 wants to expand cmov itself.
442  setOperationAction(ISD::SELECT          , MVT::i8   , Custom);
443  setOperationAction(ISD::SELECT          , MVT::i16  , Custom);
444  setOperationAction(ISD::SELECT          , MVT::i32  , Custom);
445  setOperationAction(ISD::SELECT          , MVT::f32  , Custom);
446  setOperationAction(ISD::SELECT          , MVT::f64  , Custom);
447  setOperationAction(ISD::SELECT          , MVT::f80  , Custom);
448  setOperationAction(ISD::SETCC           , MVT::i8   , Custom);
449  setOperationAction(ISD::SETCC           , MVT::i16  , Custom);
450  setOperationAction(ISD::SETCC           , MVT::i32  , Custom);
451  setOperationAction(ISD::SETCC           , MVT::f32  , Custom);
452  setOperationAction(ISD::SETCC           , MVT::f64  , Custom);
453  setOperationAction(ISD::SETCC           , MVT::f80  , Custom);
454  if (Subtarget->is64Bit()) {
455    setOperationAction(ISD::SELECT        , MVT::i64  , Custom);
456    setOperationAction(ISD::SETCC         , MVT::i64  , Custom);
457  }
458  setOperationAction(ISD::EH_RETURN       , MVT::Other, Custom);
459  // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intened to support
460  // SjLj exception handling but a light-weight setjmp/longjmp replacement to
461  // support continuation, user-level threading, and etc.. As a result, no
462  // other SjLj exception interfaces are implemented and please don't build
463  // your own exception handling based on them.
464  // LLVM/Clang supports zero-cost DWARF exception handling.
465  setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
466  setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
467
468  // Darwin ABI issue.
469  setOperationAction(ISD::ConstantPool    , MVT::i32  , Custom);
470  setOperationAction(ISD::JumpTable       , MVT::i32  , Custom);
471  setOperationAction(ISD::GlobalAddress   , MVT::i32  , Custom);
472  setOperationAction(ISD::GlobalTLSAddress, MVT::i32  , Custom);
473  if (Subtarget->is64Bit())
474    setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
475  setOperationAction(ISD::ExternalSymbol  , MVT::i32  , Custom);
476  setOperationAction(ISD::BlockAddress    , MVT::i32  , Custom);
477  if (Subtarget->is64Bit()) {
478    setOperationAction(ISD::ConstantPool  , MVT::i64  , Custom);
479    setOperationAction(ISD::JumpTable     , MVT::i64  , Custom);
480    setOperationAction(ISD::GlobalAddress , MVT::i64  , Custom);
481    setOperationAction(ISD::ExternalSymbol, MVT::i64  , Custom);
482    setOperationAction(ISD::BlockAddress  , MVT::i64  , Custom);
483  }
484  // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
485  setOperationAction(ISD::SHL_PARTS       , MVT::i32  , Custom);
486  setOperationAction(ISD::SRA_PARTS       , MVT::i32  , Custom);
487  setOperationAction(ISD::SRL_PARTS       , MVT::i32  , Custom);
488  if (Subtarget->is64Bit()) {
489    setOperationAction(ISD::SHL_PARTS     , MVT::i64  , Custom);
490    setOperationAction(ISD::SRA_PARTS     , MVT::i64  , Custom);
491    setOperationAction(ISD::SRL_PARTS     , MVT::i64  , Custom);
492  }
493
494  if (Subtarget->hasSSE1())
495    setOperationAction(ISD::PREFETCH      , MVT::Other, Legal);
496
497  setOperationAction(ISD::MEMBARRIER    , MVT::Other, Custom);
498  setOperationAction(ISD::ATOMIC_FENCE  , MVT::Other, Custom);
499
500  // On X86 and X86-64, atomic operations are lowered to locked instructions.
501  // Locked instructions, in turn, have implicit fence semantics (all memory
502  // operations are flushed before issuing the locked instruction, and they
503  // are not buffered), so we can fold away the common pattern of
504  // fence-atomic-fence.
505  setShouldFoldAtomicFences(true);
506
507  // Expand certain atomics
508  for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
509    MVT VT = IntVTs[i];
510    setOperationAction(ISD::ATOMIC_CMP_SWAP, VT, Custom);
511    setOperationAction(ISD::ATOMIC_LOAD_SUB, VT, Custom);
512    setOperationAction(ISD::ATOMIC_STORE, VT, Custom);
513  }
514
515  if (!Subtarget->is64Bit()) {
516    setOperationAction(ISD::ATOMIC_LOAD, MVT::i64, Custom);
517    setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i64, Custom);
518    setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
519    setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i64, Custom);
520    setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i64, Custom);
521    setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i64, Custom);
522    setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i64, Custom);
523    setOperationAction(ISD::ATOMIC_SWAP, MVT::i64, Custom);
524    setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i64, Custom);
525    setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i64, Custom);
526    setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i64, Custom);
527    setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i64, Custom);
528  }
529
530  if (Subtarget->hasCmpxchg16b()) {
531    setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i128, Custom);
532  }
533
534  // FIXME - use subtarget debug flags
535  if (!Subtarget->isTargetDarwin() &&
536      !Subtarget->isTargetELF() &&
537      !Subtarget->isTargetCygMing()) {
538    setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
539  }
540
541  setOperationAction(ISD::EXCEPTIONADDR, MVT::i64, Expand);
542  setOperationAction(ISD::EHSELECTION,   MVT::i64, Expand);
543  setOperationAction(ISD::EXCEPTIONADDR, MVT::i32, Expand);
544  setOperationAction(ISD::EHSELECTION,   MVT::i32, Expand);
545  if (Subtarget->is64Bit()) {
546    setExceptionPointerRegister(X86::RAX);
547    setExceptionSelectorRegister(X86::RDX);
548  } else {
549    setExceptionPointerRegister(X86::EAX);
550    setExceptionSelectorRegister(X86::EDX);
551  }
552  setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
553  setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
554
555  setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
556  setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
557
558  setOperationAction(ISD::TRAP, MVT::Other, Legal);
559  setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal);
560
561  // VASTART needs to be custom lowered to use the VarArgsFrameIndex
562  setOperationAction(ISD::VASTART           , MVT::Other, Custom);
563  setOperationAction(ISD::VAEND             , MVT::Other, Expand);
564  if (Subtarget->is64Bit()) {
565    setOperationAction(ISD::VAARG           , MVT::Other, Custom);
566    setOperationAction(ISD::VACOPY          , MVT::Other, Custom);
567  } else {
568    setOperationAction(ISD::VAARG           , MVT::Other, Expand);
569    setOperationAction(ISD::VACOPY          , MVT::Other, Expand);
570  }
571
572  setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
573  setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
574
575  if (Subtarget->isTargetCOFF() && !Subtarget->isTargetEnvMacho())
576    setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
577                       MVT::i64 : MVT::i32, Custom);
578  else if (TM.Options.EnableSegmentedStacks)
579    setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
580                       MVT::i64 : MVT::i32, Custom);
581  else
582    setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
583                       MVT::i64 : MVT::i32, Expand);
584
585  if (!TM.Options.UseSoftFloat && X86ScalarSSEf64) {
586    // f32 and f64 use SSE.
587    // Set up the FP register classes.
588    addRegisterClass(MVT::f32, &X86::FR32RegClass);
589    addRegisterClass(MVT::f64, &X86::FR64RegClass);
590
591    // Use ANDPD to simulate FABS.
592    setOperationAction(ISD::FABS , MVT::f64, Custom);
593    setOperationAction(ISD::FABS , MVT::f32, Custom);
594
595    // Use XORP to simulate FNEG.
596    setOperationAction(ISD::FNEG , MVT::f64, Custom);
597    setOperationAction(ISD::FNEG , MVT::f32, Custom);
598
599    // Use ANDPD and ORPD to simulate FCOPYSIGN.
600    setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
601    setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
602
603    // Lower this to FGETSIGNx86 plus an AND.
604    setOperationAction(ISD::FGETSIGN, MVT::i64, Custom);
605    setOperationAction(ISD::FGETSIGN, MVT::i32, Custom);
606
607    // We don't support sin/cos/fmod
608    setOperationAction(ISD::FSIN , MVT::f64, Expand);
609    setOperationAction(ISD::FCOS , MVT::f64, Expand);
610    setOperationAction(ISD::FSIN , MVT::f32, Expand);
611    setOperationAction(ISD::FCOS , MVT::f32, Expand);
612
613    // Expand FP immediates into loads from the stack, except for the special
614    // cases we handle.
615    addLegalFPImmediate(APFloat(+0.0)); // xorpd
616    addLegalFPImmediate(APFloat(+0.0f)); // xorps
617  } else if (!TM.Options.UseSoftFloat && X86ScalarSSEf32) {
618    // Use SSE for f32, x87 for f64.
619    // Set up the FP register classes.
620    addRegisterClass(MVT::f32, &X86::FR32RegClass);
621    addRegisterClass(MVT::f64, &X86::RFP64RegClass);
622
623    // Use ANDPS to simulate FABS.
624    setOperationAction(ISD::FABS , MVT::f32, Custom);
625
626    // Use XORP to simulate FNEG.
627    setOperationAction(ISD::FNEG , MVT::f32, Custom);
628
629    setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
630
631    // Use ANDPS and ORPS to simulate FCOPYSIGN.
632    setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
633    setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
634
635    // We don't support sin/cos/fmod
636    setOperationAction(ISD::FSIN , MVT::f32, Expand);
637    setOperationAction(ISD::FCOS , MVT::f32, Expand);
638
639    // Special cases we handle for FP constants.
640    addLegalFPImmediate(APFloat(+0.0f)); // xorps
641    addLegalFPImmediate(APFloat(+0.0)); // FLD0
642    addLegalFPImmediate(APFloat(+1.0)); // FLD1
643    addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
644    addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
645
646    if (!TM.Options.UnsafeFPMath) {
647      setOperationAction(ISD::FSIN           , MVT::f64  , Expand);
648      setOperationAction(ISD::FCOS           , MVT::f64  , Expand);
649    }
650  } else if (!TM.Options.UseSoftFloat) {
651    // f32 and f64 in x87.
652    // Set up the FP register classes.
653    addRegisterClass(MVT::f64, &X86::RFP64RegClass);
654    addRegisterClass(MVT::f32, &X86::RFP32RegClass);
655
656    setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
657    setOperationAction(ISD::UNDEF,     MVT::f32, Expand);
658    setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
659    setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
660
661    if (!TM.Options.UnsafeFPMath) {
662      setOperationAction(ISD::FSIN           , MVT::f32  , Expand);
663      setOperationAction(ISD::FSIN           , MVT::f64  , Expand);
664      setOperationAction(ISD::FCOS           , MVT::f32  , Expand);
665      setOperationAction(ISD::FCOS           , MVT::f64  , Expand);
666    }
667    addLegalFPImmediate(APFloat(+0.0)); // FLD0
668    addLegalFPImmediate(APFloat(+1.0)); // FLD1
669    addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
670    addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
671    addLegalFPImmediate(APFloat(+0.0f)); // FLD0
672    addLegalFPImmediate(APFloat(+1.0f)); // FLD1
673    addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
674    addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
675  }
676
677  // We don't support FMA.
678  setOperationAction(ISD::FMA, MVT::f64, Expand);
679  setOperationAction(ISD::FMA, MVT::f32, Expand);
680
681  // Long double always uses X87.
682  if (!TM.Options.UseSoftFloat) {
683    addRegisterClass(MVT::f80, &X86::RFP80RegClass);
684    setOperationAction(ISD::UNDEF,     MVT::f80, Expand);
685    setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
686    {
687      APFloat TmpFlt = APFloat::getZero(APFloat::x87DoubleExtended);
688      addLegalFPImmediate(TmpFlt);  // FLD0
689      TmpFlt.changeSign();
690      addLegalFPImmediate(TmpFlt);  // FLD0/FCHS
691
692      bool ignored;
693      APFloat TmpFlt2(+1.0);
694      TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
695                      &ignored);
696      addLegalFPImmediate(TmpFlt2);  // FLD1
697      TmpFlt2.changeSign();
698      addLegalFPImmediate(TmpFlt2);  // FLD1/FCHS
699    }
700
701    if (!TM.Options.UnsafeFPMath) {
702      setOperationAction(ISD::FSIN           , MVT::f80  , Expand);
703      setOperationAction(ISD::FCOS           , MVT::f80  , Expand);
704    }
705
706    setOperationAction(ISD::FFLOOR, MVT::f80, Expand);
707    setOperationAction(ISD::FCEIL,  MVT::f80, Expand);
708    setOperationAction(ISD::FTRUNC, MVT::f80, Expand);
709    setOperationAction(ISD::FRINT,  MVT::f80, Expand);
710    setOperationAction(ISD::FNEARBYINT, MVT::f80, Expand);
711    setOperationAction(ISD::FMA, MVT::f80, Expand);
712  }
713
714  // Always use a library call for pow.
715  setOperationAction(ISD::FPOW             , MVT::f32  , Expand);
716  setOperationAction(ISD::FPOW             , MVT::f64  , Expand);
717  setOperationAction(ISD::FPOW             , MVT::f80  , Expand);
718
719  setOperationAction(ISD::FLOG, MVT::f80, Expand);
720  setOperationAction(ISD::FLOG2, MVT::f80, Expand);
721  setOperationAction(ISD::FLOG10, MVT::f80, Expand);
722  setOperationAction(ISD::FEXP, MVT::f80, Expand);
723  setOperationAction(ISD::FEXP2, MVT::f80, Expand);
724
725  // First set operation action for all vector types to either promote
726  // (for widening) or expand (for scalarization). Then we will selectively
727  // turn on ones that can be effectively codegen'd.
728  for (int i = MVT::FIRST_VECTOR_VALUETYPE;
729           i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
730    MVT VT = (MVT::SimpleValueType)i;
731    setOperationAction(ISD::ADD , VT, Expand);
732    setOperationAction(ISD::SUB , VT, Expand);
733    setOperationAction(ISD::FADD, VT, Expand);
734    setOperationAction(ISD::FNEG, VT, Expand);
735    setOperationAction(ISD::FSUB, VT, Expand);
736    setOperationAction(ISD::MUL , VT, Expand);
737    setOperationAction(ISD::FMUL, VT, Expand);
738    setOperationAction(ISD::SDIV, VT, Expand);
739    setOperationAction(ISD::UDIV, VT, Expand);
740    setOperationAction(ISD::FDIV, VT, Expand);
741    setOperationAction(ISD::SREM, VT, Expand);
742    setOperationAction(ISD::UREM, VT, Expand);
743    setOperationAction(ISD::LOAD, VT, Expand);
744    setOperationAction(ISD::VECTOR_SHUFFLE, VT, Expand);
745    setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT,Expand);
746    setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
747    setOperationAction(ISD::EXTRACT_SUBVECTOR, VT,Expand);
748    setOperationAction(ISD::INSERT_SUBVECTOR, VT,Expand);
749    setOperationAction(ISD::FABS, VT, Expand);
750    setOperationAction(ISD::FSIN, VT, Expand);
751    setOperationAction(ISD::FCOS, VT, Expand);
752    setOperationAction(ISD::FREM, VT, Expand);
753    setOperationAction(ISD::FMA,  VT, Expand);
754    setOperationAction(ISD::FPOWI, VT, Expand);
755    setOperationAction(ISD::FSQRT, VT, Expand);
756    setOperationAction(ISD::FCOPYSIGN, VT, Expand);
757    setOperationAction(ISD::FFLOOR, VT, Expand);
758    setOperationAction(ISD::FCEIL, VT, Expand);
759    setOperationAction(ISD::FTRUNC, VT, Expand);
760    setOperationAction(ISD::FRINT, VT, Expand);
761    setOperationAction(ISD::FNEARBYINT, VT, Expand);
762    setOperationAction(ISD::SMUL_LOHI, VT, Expand);
763    setOperationAction(ISD::UMUL_LOHI, VT, Expand);
764    setOperationAction(ISD::SDIVREM, VT, Expand);
765    setOperationAction(ISD::UDIVREM, VT, Expand);
766    setOperationAction(ISD::FPOW, VT, Expand);
767    setOperationAction(ISD::CTPOP, VT, Expand);
768    setOperationAction(ISD::CTTZ, VT, Expand);
769    setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Expand);
770    setOperationAction(ISD::CTLZ, VT, Expand);
771    setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Expand);
772    setOperationAction(ISD::SHL, VT, Expand);
773    setOperationAction(ISD::SRA, VT, Expand);
774    setOperationAction(ISD::SRL, VT, Expand);
775    setOperationAction(ISD::ROTL, VT, Expand);
776    setOperationAction(ISD::ROTR, VT, Expand);
777    setOperationAction(ISD::BSWAP, VT, Expand);
778    setOperationAction(ISD::SETCC, VT, Expand);
779    setOperationAction(ISD::FLOG, VT, Expand);
780    setOperationAction(ISD::FLOG2, VT, Expand);
781    setOperationAction(ISD::FLOG10, VT, Expand);
782    setOperationAction(ISD::FEXP, VT, Expand);
783    setOperationAction(ISD::FEXP2, VT, Expand);
784    setOperationAction(ISD::FP_TO_UINT, VT, Expand);
785    setOperationAction(ISD::FP_TO_SINT, VT, Expand);
786    setOperationAction(ISD::UINT_TO_FP, VT, Expand);
787    setOperationAction(ISD::SINT_TO_FP, VT, Expand);
788    setOperationAction(ISD::SIGN_EXTEND_INREG, VT,Expand);
789    setOperationAction(ISD::TRUNCATE, VT, Expand);
790    setOperationAction(ISD::SIGN_EXTEND, VT, Expand);
791    setOperationAction(ISD::ZERO_EXTEND, VT, Expand);
792    setOperationAction(ISD::ANY_EXTEND, VT, Expand);
793    setOperationAction(ISD::VSELECT, VT, Expand);
794    for (int InnerVT = MVT::FIRST_VECTOR_VALUETYPE;
795             InnerVT <= MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
796      setTruncStoreAction(VT,
797                          (MVT::SimpleValueType)InnerVT, Expand);
798    setLoadExtAction(ISD::SEXTLOAD, VT, Expand);
799    setLoadExtAction(ISD::ZEXTLOAD, VT, Expand);
800    setLoadExtAction(ISD::EXTLOAD, VT, Expand);
801  }
802
803  // FIXME: In order to prevent SSE instructions being expanded to MMX ones
804  // with -msoft-float, disable use of MMX as well.
805  if (!TM.Options.UseSoftFloat && Subtarget->hasMMX()) {
806    addRegisterClass(MVT::x86mmx, &X86::VR64RegClass);
807    // No operations on x86mmx supported, everything uses intrinsics.
808  }
809
810  // MMX-sized vectors (other than x86mmx) are expected to be expanded
811  // into smaller operations.
812  setOperationAction(ISD::MULHS,              MVT::v8i8,  Expand);
813  setOperationAction(ISD::MULHS,              MVT::v4i16, Expand);
814  setOperationAction(ISD::MULHS,              MVT::v2i32, Expand);
815  setOperationAction(ISD::MULHS,              MVT::v1i64, Expand);
816  setOperationAction(ISD::AND,                MVT::v8i8,  Expand);
817  setOperationAction(ISD::AND,                MVT::v4i16, Expand);
818  setOperationAction(ISD::AND,                MVT::v2i32, Expand);
819  setOperationAction(ISD::AND,                MVT::v1i64, Expand);
820  setOperationAction(ISD::OR,                 MVT::v8i8,  Expand);
821  setOperationAction(ISD::OR,                 MVT::v4i16, Expand);
822  setOperationAction(ISD::OR,                 MVT::v2i32, Expand);
823  setOperationAction(ISD::OR,                 MVT::v1i64, Expand);
824  setOperationAction(ISD::XOR,                MVT::v8i8,  Expand);
825  setOperationAction(ISD::XOR,                MVT::v4i16, Expand);
826  setOperationAction(ISD::XOR,                MVT::v2i32, Expand);
827  setOperationAction(ISD::XOR,                MVT::v1i64, Expand);
828  setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i8,  Expand);
829  setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v4i16, Expand);
830  setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v2i32, Expand);
831  setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v1i64, Expand);
832  setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v1i64, Expand);
833  setOperationAction(ISD::SELECT,             MVT::v8i8,  Expand);
834  setOperationAction(ISD::SELECT,             MVT::v4i16, Expand);
835  setOperationAction(ISD::SELECT,             MVT::v2i32, Expand);
836  setOperationAction(ISD::SELECT,             MVT::v1i64, Expand);
837  setOperationAction(ISD::BITCAST,            MVT::v8i8,  Expand);
838  setOperationAction(ISD::BITCAST,            MVT::v4i16, Expand);
839  setOperationAction(ISD::BITCAST,            MVT::v2i32, Expand);
840  setOperationAction(ISD::BITCAST,            MVT::v1i64, Expand);
841
842  if (!TM.Options.UseSoftFloat && Subtarget->hasSSE1()) {
843    addRegisterClass(MVT::v4f32, &X86::VR128RegClass);
844
845    setOperationAction(ISD::FADD,               MVT::v4f32, Legal);
846    setOperationAction(ISD::FSUB,               MVT::v4f32, Legal);
847    setOperationAction(ISD::FMUL,               MVT::v4f32, Legal);
848    setOperationAction(ISD::FDIV,               MVT::v4f32, Legal);
849    setOperationAction(ISD::FSQRT,              MVT::v4f32, Legal);
850    setOperationAction(ISD::FNEG,               MVT::v4f32, Custom);
851    setOperationAction(ISD::FABS,               MVT::v4f32, Custom);
852    setOperationAction(ISD::LOAD,               MVT::v4f32, Legal);
853    setOperationAction(ISD::BUILD_VECTOR,       MVT::v4f32, Custom);
854    setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4f32, Custom);
855    setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
856    setOperationAction(ISD::SELECT,             MVT::v4f32, Custom);
857  }
858
859  if (!TM.Options.UseSoftFloat && Subtarget->hasSSE2()) {
860    addRegisterClass(MVT::v2f64, &X86::VR128RegClass);
861
862    // FIXME: Unfortunately -soft-float and -no-implicit-float means XMM
863    // registers cannot be used even for integer operations.
864    addRegisterClass(MVT::v16i8, &X86::VR128RegClass);
865    addRegisterClass(MVT::v8i16, &X86::VR128RegClass);
866    addRegisterClass(MVT::v4i32, &X86::VR128RegClass);
867    addRegisterClass(MVT::v2i64, &X86::VR128RegClass);
868
869    setOperationAction(ISD::ADD,                MVT::v16i8, Legal);
870    setOperationAction(ISD::ADD,                MVT::v8i16, Legal);
871    setOperationAction(ISD::ADD,                MVT::v4i32, Legal);
872    setOperationAction(ISD::ADD,                MVT::v2i64, Legal);
873    setOperationAction(ISD::MUL,                MVT::v2i64, Custom);
874    setOperationAction(ISD::SUB,                MVT::v16i8, Legal);
875    setOperationAction(ISD::SUB,                MVT::v8i16, Legal);
876    setOperationAction(ISD::SUB,                MVT::v4i32, Legal);
877    setOperationAction(ISD::SUB,                MVT::v2i64, Legal);
878    setOperationAction(ISD::MUL,                MVT::v8i16, Legal);
879    setOperationAction(ISD::FADD,               MVT::v2f64, Legal);
880    setOperationAction(ISD::FSUB,               MVT::v2f64, Legal);
881    setOperationAction(ISD::FMUL,               MVT::v2f64, Legal);
882    setOperationAction(ISD::FDIV,               MVT::v2f64, Legal);
883    setOperationAction(ISD::FSQRT,              MVT::v2f64, Legal);
884    setOperationAction(ISD::FNEG,               MVT::v2f64, Custom);
885    setOperationAction(ISD::FABS,               MVT::v2f64, Custom);
886
887    setOperationAction(ISD::SETCC,              MVT::v2i64, Custom);
888    setOperationAction(ISD::SETCC,              MVT::v16i8, Custom);
889    setOperationAction(ISD::SETCC,              MVT::v8i16, Custom);
890    setOperationAction(ISD::SETCC,              MVT::v4i32, Custom);
891
892    setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v16i8, Custom);
893    setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i16, Custom);
894    setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
895    setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
896    setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
897
898    // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
899    for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
900      MVT VT = (MVT::SimpleValueType)i;
901      // Do not attempt to custom lower non-power-of-2 vectors
902      if (!isPowerOf2_32(VT.getVectorNumElements()))
903        continue;
904      // Do not attempt to custom lower non-128-bit vectors
905      if (!VT.is128BitVector())
906        continue;
907      setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
908      setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
909      setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
910    }
911
912    setOperationAction(ISD::BUILD_VECTOR,       MVT::v2f64, Custom);
913    setOperationAction(ISD::BUILD_VECTOR,       MVT::v2i64, Custom);
914    setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2f64, Custom);
915    setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2i64, Custom);
916    setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2f64, Custom);
917    setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
918
919    if (Subtarget->is64Bit()) {
920      setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
921      setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
922    }
923
924    // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
925    for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
926      MVT VT = (MVT::SimpleValueType)i;
927
928      // Do not attempt to promote non-128-bit vectors
929      if (!VT.is128BitVector())
930        continue;
931
932      setOperationAction(ISD::AND,    VT, Promote);
933      AddPromotedToType (ISD::AND,    VT, MVT::v2i64);
934      setOperationAction(ISD::OR,     VT, Promote);
935      AddPromotedToType (ISD::OR,     VT, MVT::v2i64);
936      setOperationAction(ISD::XOR,    VT, Promote);
937      AddPromotedToType (ISD::XOR,    VT, MVT::v2i64);
938      setOperationAction(ISD::LOAD,   VT, Promote);
939      AddPromotedToType (ISD::LOAD,   VT, MVT::v2i64);
940      setOperationAction(ISD::SELECT, VT, Promote);
941      AddPromotedToType (ISD::SELECT, VT, MVT::v2i64);
942    }
943
944    setTruncStoreAction(MVT::f64, MVT::f32, Expand);
945
946    // Custom lower v2i64 and v2f64 selects.
947    setOperationAction(ISD::LOAD,               MVT::v2f64, Legal);
948    setOperationAction(ISD::LOAD,               MVT::v2i64, Legal);
949    setOperationAction(ISD::SELECT,             MVT::v2f64, Custom);
950    setOperationAction(ISD::SELECT,             MVT::v2i64, Custom);
951
952    setOperationAction(ISD::FP_TO_SINT,         MVT::v4i32, Legal);
953    setOperationAction(ISD::SINT_TO_FP,         MVT::v4i32, Legal);
954
955    setOperationAction(ISD::UINT_TO_FP,         MVT::v4i8,  Custom);
956    setOperationAction(ISD::UINT_TO_FP,         MVT::v4i16, Custom);
957    // As there is no 64-bit GPR available, we need build a special custom
958    // sequence to convert from v2i32 to v2f32.
959    if (!Subtarget->is64Bit())
960      setOperationAction(ISD::UINT_TO_FP,       MVT::v2f32, Custom);
961
962    setOperationAction(ISD::FP_EXTEND,          MVT::v2f32, Custom);
963    setOperationAction(ISD::FP_ROUND,           MVT::v2f32, Custom);
964
965    setLoadExtAction(ISD::EXTLOAD,              MVT::v2f32, Legal);
966  }
967
968  if (Subtarget->hasSSE41()) {
969    setOperationAction(ISD::FFLOOR,             MVT::f32,   Legal);
970    setOperationAction(ISD::FCEIL,              MVT::f32,   Legal);
971    setOperationAction(ISD::FTRUNC,             MVT::f32,   Legal);
972    setOperationAction(ISD::FRINT,              MVT::f32,   Legal);
973    setOperationAction(ISD::FNEARBYINT,         MVT::f32,   Legal);
974    setOperationAction(ISD::FFLOOR,             MVT::f64,   Legal);
975    setOperationAction(ISD::FCEIL,              MVT::f64,   Legal);
976    setOperationAction(ISD::FTRUNC,             MVT::f64,   Legal);
977    setOperationAction(ISD::FRINT,              MVT::f64,   Legal);
978    setOperationAction(ISD::FNEARBYINT,         MVT::f64,   Legal);
979
980    setOperationAction(ISD::FFLOOR,             MVT::v4f32, Legal);
981    setOperationAction(ISD::FCEIL,              MVT::v4f32, Legal);
982    setOperationAction(ISD::FTRUNC,             MVT::v4f32, Legal);
983    setOperationAction(ISD::FRINT,              MVT::v4f32, Legal);
984    setOperationAction(ISD::FNEARBYINT,         MVT::v4f32, Legal);
985    setOperationAction(ISD::FFLOOR,             MVT::v2f64, Legal);
986    setOperationAction(ISD::FCEIL,              MVT::v2f64, Legal);
987    setOperationAction(ISD::FTRUNC,             MVT::v2f64, Legal);
988    setOperationAction(ISD::FRINT,              MVT::v2f64, Legal);
989    setOperationAction(ISD::FNEARBYINT,         MVT::v2f64, Legal);
990
991    // FIXME: Do we need to handle scalar-to-vector here?
992    setOperationAction(ISD::MUL,                MVT::v4i32, Legal);
993
994    setOperationAction(ISD::VSELECT,            MVT::v2f64, Legal);
995    setOperationAction(ISD::VSELECT,            MVT::v2i64, Legal);
996    setOperationAction(ISD::VSELECT,            MVT::v16i8, Legal);
997    setOperationAction(ISD::VSELECT,            MVT::v4i32, Legal);
998    setOperationAction(ISD::VSELECT,            MVT::v4f32, Legal);
999
1000    // i8 and i16 vectors are custom , because the source register and source
1001    // source memory operand types are not the same width.  f32 vectors are
1002    // custom since the immediate controlling the insert encodes additional
1003    // information.
1004    setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i8, Custom);
1005    setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
1006    setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
1007    setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
1008
1009    setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
1010    setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
1011    setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
1012    setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
1013
1014    // FIXME: these should be Legal but thats only for the case where
1015    // the index is constant.  For now custom expand to deal with that.
1016    if (Subtarget->is64Bit()) {
1017      setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
1018      setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
1019    }
1020  }
1021
1022  if (Subtarget->hasSSE2()) {
1023    setOperationAction(ISD::SRL,               MVT::v8i16, Custom);
1024    setOperationAction(ISD::SRL,               MVT::v16i8, Custom);
1025
1026    setOperationAction(ISD::SHL,               MVT::v8i16, Custom);
1027    setOperationAction(ISD::SHL,               MVT::v16i8, Custom);
1028
1029    setOperationAction(ISD::SRA,               MVT::v8i16, Custom);
1030    setOperationAction(ISD::SRA,               MVT::v16i8, Custom);
1031
1032    if (Subtarget->hasAVX2()) {
1033      setOperationAction(ISD::SRL,             MVT::v2i64, Legal);
1034      setOperationAction(ISD::SRL,             MVT::v4i32, Legal);
1035
1036      setOperationAction(ISD::SHL,             MVT::v2i64, Legal);
1037      setOperationAction(ISD::SHL,             MVT::v4i32, Legal);
1038
1039      setOperationAction(ISD::SRA,             MVT::v4i32, Legal);
1040    } else {
1041      setOperationAction(ISD::SRL,             MVT::v2i64, Custom);
1042      setOperationAction(ISD::SRL,             MVT::v4i32, Custom);
1043
1044      setOperationAction(ISD::SHL,             MVT::v2i64, Custom);
1045      setOperationAction(ISD::SHL,             MVT::v4i32, Custom);
1046
1047      setOperationAction(ISD::SRA,             MVT::v4i32, Custom);
1048    }
1049  }
1050
1051  if (!TM.Options.UseSoftFloat && Subtarget->hasAVX()) {
1052    addRegisterClass(MVT::v32i8,  &X86::VR256RegClass);
1053    addRegisterClass(MVT::v16i16, &X86::VR256RegClass);
1054    addRegisterClass(MVT::v8i32,  &X86::VR256RegClass);
1055    addRegisterClass(MVT::v8f32,  &X86::VR256RegClass);
1056    addRegisterClass(MVT::v4i64,  &X86::VR256RegClass);
1057    addRegisterClass(MVT::v4f64,  &X86::VR256RegClass);
1058
1059    setOperationAction(ISD::LOAD,               MVT::v8f32, Legal);
1060    setOperationAction(ISD::LOAD,               MVT::v4f64, Legal);
1061    setOperationAction(ISD::LOAD,               MVT::v4i64, Legal);
1062
1063    setOperationAction(ISD::FADD,               MVT::v8f32, Legal);
1064    setOperationAction(ISD::FSUB,               MVT::v8f32, Legal);
1065    setOperationAction(ISD::FMUL,               MVT::v8f32, Legal);
1066    setOperationAction(ISD::FDIV,               MVT::v8f32, Legal);
1067    setOperationAction(ISD::FSQRT,              MVT::v8f32, Legal);
1068    setOperationAction(ISD::FFLOOR,             MVT::v8f32, Legal);
1069    setOperationAction(ISD::FCEIL,              MVT::v8f32, Legal);
1070    setOperationAction(ISD::FTRUNC,             MVT::v8f32, Legal);
1071    setOperationAction(ISD::FRINT,              MVT::v8f32, Legal);
1072    setOperationAction(ISD::FNEARBYINT,         MVT::v8f32, Legal);
1073    setOperationAction(ISD::FNEG,               MVT::v8f32, Custom);
1074    setOperationAction(ISD::FABS,               MVT::v8f32, Custom);
1075
1076    setOperationAction(ISD::FADD,               MVT::v4f64, Legal);
1077    setOperationAction(ISD::FSUB,               MVT::v4f64, Legal);
1078    setOperationAction(ISD::FMUL,               MVT::v4f64, Legal);
1079    setOperationAction(ISD::FDIV,               MVT::v4f64, Legal);
1080    setOperationAction(ISD::FSQRT,              MVT::v4f64, Legal);
1081    setOperationAction(ISD::FFLOOR,             MVT::v4f64, Legal);
1082    setOperationAction(ISD::FCEIL,              MVT::v4f64, Legal);
1083    setOperationAction(ISD::FTRUNC,             MVT::v4f64, Legal);
1084    setOperationAction(ISD::FRINT,              MVT::v4f64, Legal);
1085    setOperationAction(ISD::FNEARBYINT,         MVT::v4f64, Legal);
1086    setOperationAction(ISD::FNEG,               MVT::v4f64, Custom);
1087    setOperationAction(ISD::FABS,               MVT::v4f64, Custom);
1088
1089    setOperationAction(ISD::TRUNCATE,           MVT::v8i16, Custom);
1090
1091    setOperationAction(ISD::FP_TO_SINT,         MVT::v8i16, Custom);
1092
1093    setOperationAction(ISD::FP_TO_SINT,         MVT::v8i32, Legal);
1094    setOperationAction(ISD::SINT_TO_FP,         MVT::v8i32, Legal);
1095    setOperationAction(ISD::FP_ROUND,           MVT::v4f32, Legal);
1096
1097    setOperationAction(ISD::ZERO_EXTEND,        MVT::v8i32, Custom);
1098    setOperationAction(ISD::UINT_TO_FP,         MVT::v8i8,  Custom);
1099    setOperationAction(ISD::UINT_TO_FP,         MVT::v8i16, Custom);
1100
1101    setLoadExtAction(ISD::EXTLOAD,              MVT::v4f32, Legal);
1102
1103    setOperationAction(ISD::SRL,               MVT::v16i16, Custom);
1104    setOperationAction(ISD::SRL,               MVT::v32i8, Custom);
1105
1106    setOperationAction(ISD::SHL,               MVT::v16i16, Custom);
1107    setOperationAction(ISD::SHL,               MVT::v32i8, Custom);
1108
1109    setOperationAction(ISD::SRA,               MVT::v16i16, Custom);
1110    setOperationAction(ISD::SRA,               MVT::v32i8, Custom);
1111
1112    setOperationAction(ISD::SETCC,             MVT::v32i8, Custom);
1113    setOperationAction(ISD::SETCC,             MVT::v16i16, Custom);
1114    setOperationAction(ISD::SETCC,             MVT::v8i32, Custom);
1115    setOperationAction(ISD::SETCC,             MVT::v4i64, Custom);
1116
1117    setOperationAction(ISD::SELECT,            MVT::v4f64, Custom);
1118    setOperationAction(ISD::SELECT,            MVT::v4i64, Custom);
1119    setOperationAction(ISD::SELECT,            MVT::v8f32, Custom);
1120
1121    setOperationAction(ISD::VSELECT,           MVT::v4f64, Legal);
1122    setOperationAction(ISD::VSELECT,           MVT::v4i64, Legal);
1123    setOperationAction(ISD::VSELECT,           MVT::v8i32, Legal);
1124    setOperationAction(ISD::VSELECT,           MVT::v8f32, Legal);
1125
1126    if (Subtarget->hasFMA() || Subtarget->hasFMA4()) {
1127      setOperationAction(ISD::FMA,             MVT::v8f32, Legal);
1128      setOperationAction(ISD::FMA,             MVT::v4f64, Legal);
1129      setOperationAction(ISD::FMA,             MVT::v4f32, Legal);
1130      setOperationAction(ISD::FMA,             MVT::v2f64, Legal);
1131      setOperationAction(ISD::FMA,             MVT::f32, Legal);
1132      setOperationAction(ISD::FMA,             MVT::f64, Legal);
1133    }
1134
1135    if (Subtarget->hasAVX2()) {
1136      setOperationAction(ISD::ADD,             MVT::v4i64, Legal);
1137      setOperationAction(ISD::ADD,             MVT::v8i32, Legal);
1138      setOperationAction(ISD::ADD,             MVT::v16i16, Legal);
1139      setOperationAction(ISD::ADD,             MVT::v32i8, Legal);
1140
1141      setOperationAction(ISD::SUB,             MVT::v4i64, Legal);
1142      setOperationAction(ISD::SUB,             MVT::v8i32, Legal);
1143      setOperationAction(ISD::SUB,             MVT::v16i16, Legal);
1144      setOperationAction(ISD::SUB,             MVT::v32i8, Legal);
1145
1146      setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1147      setOperationAction(ISD::MUL,             MVT::v8i32, Legal);
1148      setOperationAction(ISD::MUL,             MVT::v16i16, Legal);
1149      // Don't lower v32i8 because there is no 128-bit byte mul
1150
1151      setOperationAction(ISD::VSELECT,         MVT::v32i8, Legal);
1152
1153      setOperationAction(ISD::SRL,             MVT::v4i64, Legal);
1154      setOperationAction(ISD::SRL,             MVT::v8i32, Legal);
1155
1156      setOperationAction(ISD::SHL,             MVT::v4i64, Legal);
1157      setOperationAction(ISD::SHL,             MVT::v8i32, Legal);
1158
1159      setOperationAction(ISD::SRA,             MVT::v8i32, Legal);
1160    } else {
1161      setOperationAction(ISD::ADD,             MVT::v4i64, Custom);
1162      setOperationAction(ISD::ADD,             MVT::v8i32, Custom);
1163      setOperationAction(ISD::ADD,             MVT::v16i16, Custom);
1164      setOperationAction(ISD::ADD,             MVT::v32i8, Custom);
1165
1166      setOperationAction(ISD::SUB,             MVT::v4i64, Custom);
1167      setOperationAction(ISD::SUB,             MVT::v8i32, Custom);
1168      setOperationAction(ISD::SUB,             MVT::v16i16, Custom);
1169      setOperationAction(ISD::SUB,             MVT::v32i8, Custom);
1170
1171      setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1172      setOperationAction(ISD::MUL,             MVT::v8i32, Custom);
1173      setOperationAction(ISD::MUL,             MVT::v16i16, Custom);
1174      // Don't lower v32i8 because there is no 128-bit byte mul
1175
1176      setOperationAction(ISD::SRL,             MVT::v4i64, Custom);
1177      setOperationAction(ISD::SRL,             MVT::v8i32, Custom);
1178
1179      setOperationAction(ISD::SHL,             MVT::v4i64, Custom);
1180      setOperationAction(ISD::SHL,             MVT::v8i32, Custom);
1181
1182      setOperationAction(ISD::SRA,             MVT::v8i32, Custom);
1183    }
1184
1185    // Custom lower several nodes for 256-bit types.
1186    for (int i = MVT::FIRST_VECTOR_VALUETYPE;
1187             i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
1188      MVT VT = (MVT::SimpleValueType)i;
1189
1190      // Extract subvector is special because the value type
1191      // (result) is 128-bit but the source is 256-bit wide.
1192      if (VT.is128BitVector())
1193        setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1194
1195      // Do not attempt to custom lower other non-256-bit vectors
1196      if (!VT.is256BitVector())
1197        continue;
1198
1199      setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
1200      setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
1201      setOperationAction(ISD::INSERT_VECTOR_ELT,  VT, Custom);
1202      setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1203      setOperationAction(ISD::SCALAR_TO_VECTOR,   VT, Custom);
1204      setOperationAction(ISD::INSERT_SUBVECTOR,   VT, Custom);
1205      setOperationAction(ISD::CONCAT_VECTORS,     VT, Custom);
1206    }
1207
1208    // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
1209    for (int i = MVT::v32i8; i != MVT::v4i64; ++i) {
1210      MVT VT = (MVT::SimpleValueType)i;
1211
1212      // Do not attempt to promote non-256-bit vectors
1213      if (!VT.is256BitVector())
1214        continue;
1215
1216      setOperationAction(ISD::AND,    VT, Promote);
1217      AddPromotedToType (ISD::AND,    VT, MVT::v4i64);
1218      setOperationAction(ISD::OR,     VT, Promote);
1219      AddPromotedToType (ISD::OR,     VT, MVT::v4i64);
1220      setOperationAction(ISD::XOR,    VT, Promote);
1221      AddPromotedToType (ISD::XOR,    VT, MVT::v4i64);
1222      setOperationAction(ISD::LOAD,   VT, Promote);
1223      AddPromotedToType (ISD::LOAD,   VT, MVT::v4i64);
1224      setOperationAction(ISD::SELECT, VT, Promote);
1225      AddPromotedToType (ISD::SELECT, VT, MVT::v4i64);
1226    }
1227  }
1228
1229  // SIGN_EXTEND_INREGs are evaluated by the extend type. Handle the expansion
1230  // of this type with custom code.
1231  for (int VT = MVT::FIRST_VECTOR_VALUETYPE;
1232           VT != MVT::LAST_VECTOR_VALUETYPE; VT++) {
1233    setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,
1234                       Custom);
1235  }
1236
1237  // We want to custom lower some of our intrinsics.
1238  setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1239  setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
1240
1241
1242  // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1243  // handle type legalization for these operations here.
1244  //
1245  // FIXME: We really should do custom legalization for addition and
1246  // subtraction on x86-32 once PR3203 is fixed.  We really can't do much better
1247  // than generic legalization for 64-bit multiplication-with-overflow, though.
1248  for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) {
1249    // Add/Sub/Mul with overflow operations are custom lowered.
1250    MVT VT = IntVTs[i];
1251    setOperationAction(ISD::SADDO, VT, Custom);
1252    setOperationAction(ISD::UADDO, VT, Custom);
1253    setOperationAction(ISD::SSUBO, VT, Custom);
1254    setOperationAction(ISD::USUBO, VT, Custom);
1255    setOperationAction(ISD::SMULO, VT, Custom);
1256    setOperationAction(ISD::UMULO, VT, Custom);
1257  }
1258
1259  // There are no 8-bit 3-address imul/mul instructions
1260  setOperationAction(ISD::SMULO, MVT::i8, Expand);
1261  setOperationAction(ISD::UMULO, MVT::i8, Expand);
1262
1263  if (!Subtarget->is64Bit()) {
1264    // These libcalls are not available in 32-bit.
1265    setLibcallName(RTLIB::SHL_I128, 0);
1266    setLibcallName(RTLIB::SRL_I128, 0);
1267    setLibcallName(RTLIB::SRA_I128, 0);
1268  }
1269
1270  // We have target-specific dag combine patterns for the following nodes:
1271  setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1272  setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1273  setTargetDAGCombine(ISD::VSELECT);
1274  setTargetDAGCombine(ISD::SELECT);
1275  setTargetDAGCombine(ISD::SHL);
1276  setTargetDAGCombine(ISD::SRA);
1277  setTargetDAGCombine(ISD::SRL);
1278  setTargetDAGCombine(ISD::OR);
1279  setTargetDAGCombine(ISD::AND);
1280  setTargetDAGCombine(ISD::ADD);
1281  setTargetDAGCombine(ISD::FADD);
1282  setTargetDAGCombine(ISD::FSUB);
1283  setTargetDAGCombine(ISD::FMA);
1284  setTargetDAGCombine(ISD::SUB);
1285  setTargetDAGCombine(ISD::LOAD);
1286  setTargetDAGCombine(ISD::STORE);
1287  setTargetDAGCombine(ISD::ZERO_EXTEND);
1288  setTargetDAGCombine(ISD::ANY_EXTEND);
1289  setTargetDAGCombine(ISD::SIGN_EXTEND);
1290  setTargetDAGCombine(ISD::TRUNCATE);
1291  setTargetDAGCombine(ISD::SINT_TO_FP);
1292  setTargetDAGCombine(ISD::SETCC);
1293  if (Subtarget->is64Bit())
1294    setTargetDAGCombine(ISD::MUL);
1295  setTargetDAGCombine(ISD::XOR);
1296
1297  computeRegisterProperties();
1298
1299  // On Darwin, -Os means optimize for size without hurting performance,
1300  // do not reduce the limit.
1301  maxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1302  maxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 16 : 8;
1303  maxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1304  maxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1305  maxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1306  maxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1307  setPrefLoopAlignment(4); // 2^4 bytes.
1308  benefitFromCodePlacementOpt = true;
1309
1310  // Predictable cmov don't hurt on atom because it's in-order.
1311  predictableSelectIsExpensive = !Subtarget->isAtom();
1312
1313  setPrefFunctionAlignment(4); // 2^4 bytes.
1314}
1315
1316
1317EVT X86TargetLowering::getSetCCResultType(EVT VT) const {
1318  if (!VT.isVector()) return MVT::i8;
1319  return VT.changeVectorElementTypeToInteger();
1320}
1321
1322
1323/// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1324/// the desired ByVal argument alignment.
1325static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
1326  if (MaxAlign == 16)
1327    return;
1328  if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1329    if (VTy->getBitWidth() == 128)
1330      MaxAlign = 16;
1331  } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1332    unsigned EltAlign = 0;
1333    getMaxByValAlign(ATy->getElementType(), EltAlign);
1334    if (EltAlign > MaxAlign)
1335      MaxAlign = EltAlign;
1336  } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1337    for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1338      unsigned EltAlign = 0;
1339      getMaxByValAlign(STy->getElementType(i), EltAlign);
1340      if (EltAlign > MaxAlign)
1341        MaxAlign = EltAlign;
1342      if (MaxAlign == 16)
1343        break;
1344    }
1345  }
1346}
1347
1348/// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1349/// function arguments in the caller parameter area. For X86, aggregates
1350/// that contain SSE vectors are placed at 16-byte boundaries while the rest
1351/// are at 4-byte boundaries.
1352unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty) const {
1353  if (Subtarget->is64Bit()) {
1354    // Max of 8 and alignment of type.
1355    unsigned TyAlign = TD->getABITypeAlignment(Ty);
1356    if (TyAlign > 8)
1357      return TyAlign;
1358    return 8;
1359  }
1360
1361  unsigned Align = 4;
1362  if (Subtarget->hasSSE1())
1363    getMaxByValAlign(Ty, Align);
1364  return Align;
1365}
1366
1367/// getOptimalMemOpType - Returns the target specific optimal type for load
1368/// and store operations as a result of memset, memcpy, and memmove
1369/// lowering. If DstAlign is zero that means it's safe to destination
1370/// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1371/// means there isn't a need to check it against alignment requirement,
1372/// probably because the source does not need to be loaded. If
1373/// 'IsZeroVal' is true, that means it's safe to return a
1374/// non-scalar-integer type, e.g. empty string source, constant, or loaded
1375/// from memory. 'MemcpyStrSrc' indicates whether the memcpy source is
1376/// constant so it does not need to be loaded.
1377/// It returns EVT::Other if the type should be determined using generic
1378/// target-independent logic.
1379EVT
1380X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1381                                       unsigned DstAlign, unsigned SrcAlign,
1382                                       bool IsZeroVal,
1383                                       bool MemcpyStrSrc,
1384                                       MachineFunction &MF) const {
1385  const Function *F = MF.getFunction();
1386  if (IsZeroVal &&
1387      !F->getFnAttributes().hasAttribute(Attributes::NoImplicitFloat)) {
1388    if (Size >= 16 &&
1389        (Subtarget->isUnalignedMemAccessFast() ||
1390         ((DstAlign == 0 || DstAlign >= 16) &&
1391          (SrcAlign == 0 || SrcAlign >= 16)))) {
1392      if (Size >= 32) {
1393        if (Subtarget->hasAVX2())
1394          return MVT::v8i32;
1395        if (Subtarget->hasAVX())
1396          return MVT::v8f32;
1397      }
1398      if (Subtarget->hasSSE2())
1399        return MVT::v4i32;
1400      if (Subtarget->hasSSE1())
1401        return MVT::v4f32;
1402    } else if (!MemcpyStrSrc && Size >= 8 &&
1403               !Subtarget->is64Bit() &&
1404               Subtarget->hasSSE2()) {
1405      // Do not use f64 to lower memcpy if source is string constant. It's
1406      // better to use i32 to avoid the loads.
1407      return MVT::f64;
1408    }
1409  }
1410  if (Subtarget->is64Bit() && Size >= 8)
1411    return MVT::i64;
1412  return MVT::i32;
1413}
1414
1415/// getJumpTableEncoding - Return the entry encoding for a jump table in the
1416/// current function.  The returned value is a member of the
1417/// MachineJumpTableInfo::JTEntryKind enum.
1418unsigned X86TargetLowering::getJumpTableEncoding() const {
1419  // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1420  // symbol.
1421  if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1422      Subtarget->isPICStyleGOT())
1423    return MachineJumpTableInfo::EK_Custom32;
1424
1425  // Otherwise, use the normal jump table encoding heuristics.
1426  return TargetLowering::getJumpTableEncoding();
1427}
1428
1429const MCExpr *
1430X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1431                                             const MachineBasicBlock *MBB,
1432                                             unsigned uid,MCContext &Ctx) const{
1433  assert(getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1434         Subtarget->isPICStyleGOT());
1435  // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1436  // entries.
1437  return MCSymbolRefExpr::Create(MBB->getSymbol(),
1438                                 MCSymbolRefExpr::VK_GOTOFF, Ctx);
1439}
1440
1441/// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
1442/// jumptable.
1443SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1444                                                    SelectionDAG &DAG) const {
1445  if (!Subtarget->is64Bit())
1446    // This doesn't have DebugLoc associated with it, but is not really the
1447    // same as a Register.
1448    return DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), getPointerTy());
1449  return Table;
1450}
1451
1452/// getPICJumpTableRelocBaseExpr - This returns the relocation base for the
1453/// given PIC jumptable, the same as getPICJumpTableRelocBase, but as an
1454/// MCExpr.
1455const MCExpr *X86TargetLowering::
1456getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1457                             MCContext &Ctx) const {
1458  // X86-64 uses RIP relative addressing based on the jump table label.
1459  if (Subtarget->isPICStyleRIPRel())
1460    return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1461
1462  // Otherwise, the reference is relative to the PIC base.
1463  return MCSymbolRefExpr::Create(MF->getPICBaseSymbol(), Ctx);
1464}
1465
1466// FIXME: Why this routine is here? Move to RegInfo!
1467std::pair<const TargetRegisterClass*, uint8_t>
1468X86TargetLowering::findRepresentativeClass(EVT VT) const{
1469  const TargetRegisterClass *RRC = 0;
1470  uint8_t Cost = 1;
1471  switch (VT.getSimpleVT().SimpleTy) {
1472  default:
1473    return TargetLowering::findRepresentativeClass(VT);
1474  case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1475    RRC = Subtarget->is64Bit() ?
1476      (const TargetRegisterClass*)&X86::GR64RegClass :
1477      (const TargetRegisterClass*)&X86::GR32RegClass;
1478    break;
1479  case MVT::x86mmx:
1480    RRC = &X86::VR64RegClass;
1481    break;
1482  case MVT::f32: case MVT::f64:
1483  case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1484  case MVT::v4f32: case MVT::v2f64:
1485  case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
1486  case MVT::v4f64:
1487    RRC = &X86::VR128RegClass;
1488    break;
1489  }
1490  return std::make_pair(RRC, Cost);
1491}
1492
1493bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
1494                                               unsigned &Offset) const {
1495  if (!Subtarget->isTargetLinux())
1496    return false;
1497
1498  if (Subtarget->is64Bit()) {
1499    // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
1500    Offset = 0x28;
1501    if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
1502      AddressSpace = 256;
1503    else
1504      AddressSpace = 257;
1505  } else {
1506    // %gs:0x14 on i386
1507    Offset = 0x14;
1508    AddressSpace = 256;
1509  }
1510  return true;
1511}
1512
1513
1514//===----------------------------------------------------------------------===//
1515//               Return Value Calling Convention Implementation
1516//===----------------------------------------------------------------------===//
1517
1518#include "X86GenCallingConv.inc"
1519
1520bool
1521X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv,
1522                                  MachineFunction &MF, bool isVarArg,
1523                        const SmallVectorImpl<ISD::OutputArg> &Outs,
1524                        LLVMContext &Context) const {
1525  SmallVector<CCValAssign, 16> RVLocs;
1526  CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1527                 RVLocs, Context);
1528  return CCInfo.CheckReturn(Outs, RetCC_X86);
1529}
1530
1531SDValue
1532X86TargetLowering::LowerReturn(SDValue Chain,
1533                               CallingConv::ID CallConv, bool isVarArg,
1534                               const SmallVectorImpl<ISD::OutputArg> &Outs,
1535                               const SmallVectorImpl<SDValue> &OutVals,
1536                               DebugLoc dl, SelectionDAG &DAG) const {
1537  MachineFunction &MF = DAG.getMachineFunction();
1538  X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1539
1540  SmallVector<CCValAssign, 16> RVLocs;
1541  CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1542                 RVLocs, *DAG.getContext());
1543  CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1544
1545  // Add the regs to the liveout set for the function.
1546  MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
1547  for (unsigned i = 0; i != RVLocs.size(); ++i)
1548    if (RVLocs[i].isRegLoc() && !MRI.isLiveOut(RVLocs[i].getLocReg()))
1549      MRI.addLiveOut(RVLocs[i].getLocReg());
1550
1551  SDValue Flag;
1552
1553  SmallVector<SDValue, 6> RetOps;
1554  RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1555  // Operand #1 = Bytes To Pop
1556  RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(),
1557                   MVT::i16));
1558
1559  // Copy the result values into the output registers.
1560  for (unsigned i = 0; i != RVLocs.size(); ++i) {
1561    CCValAssign &VA = RVLocs[i];
1562    assert(VA.isRegLoc() && "Can only return in registers!");
1563    SDValue ValToCopy = OutVals[i];
1564    EVT ValVT = ValToCopy.getValueType();
1565
1566    // Promote values to the appropriate types
1567    if (VA.getLocInfo() == CCValAssign::SExt)
1568      ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
1569    else if (VA.getLocInfo() == CCValAssign::ZExt)
1570      ValToCopy = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), ValToCopy);
1571    else if (VA.getLocInfo() == CCValAssign::AExt)
1572      ValToCopy = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), ValToCopy);
1573    else if (VA.getLocInfo() == CCValAssign::BCvt)
1574      ValToCopy = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), ValToCopy);
1575
1576    // If this is x86-64, and we disabled SSE, we can't return FP values,
1577    // or SSE or MMX vectors.
1578    if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
1579         VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
1580          (Subtarget->is64Bit() && !Subtarget->hasSSE1())) {
1581      report_fatal_error("SSE register return with SSE disabled");
1582    }
1583    // Likewise we can't return F64 values with SSE1 only.  gcc does so, but
1584    // llvm-gcc has never done it right and no one has noticed, so this
1585    // should be OK for now.
1586    if (ValVT == MVT::f64 &&
1587        (Subtarget->is64Bit() && !Subtarget->hasSSE2()))
1588      report_fatal_error("SSE2 register return with SSE2 disabled");
1589
1590    // Returns in ST0/ST1 are handled specially: these are pushed as operands to
1591    // the RET instruction and handled by the FP Stackifier.
1592    if (VA.getLocReg() == X86::ST0 ||
1593        VA.getLocReg() == X86::ST1) {
1594      // If this is a copy from an xmm register to ST(0), use an FPExtend to
1595      // change the value to the FP stack register class.
1596      if (isScalarFPTypeInSSEReg(VA.getValVT()))
1597        ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
1598      RetOps.push_back(ValToCopy);
1599      // Don't emit a copytoreg.
1600      continue;
1601    }
1602
1603    // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
1604    // which is returned in RAX / RDX.
1605    if (Subtarget->is64Bit()) {
1606      if (ValVT == MVT::x86mmx) {
1607        if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1608          ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ValToCopy);
1609          ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
1610                                  ValToCopy);
1611          // If we don't have SSE2 available, convert to v4f32 so the generated
1612          // register is legal.
1613          if (!Subtarget->hasSSE2())
1614            ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32,ValToCopy);
1615        }
1616      }
1617    }
1618
1619    Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
1620    Flag = Chain.getValue(1);
1621  }
1622
1623  // The x86-64 ABI for returning structs by value requires that we copy
1624  // the sret argument into %rax for the return. We saved the argument into
1625  // a virtual register in the entry block, so now we copy the value out
1626  // and into %rax.
1627  if (Subtarget->is64Bit() &&
1628      DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
1629    MachineFunction &MF = DAG.getMachineFunction();
1630    X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1631    unsigned Reg = FuncInfo->getSRetReturnReg();
1632    assert(Reg &&
1633           "SRetReturnReg should have been set in LowerFormalArguments().");
1634    SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
1635
1636    Chain = DAG.getCopyToReg(Chain, dl, X86::RAX, Val, Flag);
1637    Flag = Chain.getValue(1);
1638
1639    // RAX now acts like a return value.
1640    MRI.addLiveOut(X86::RAX);
1641  }
1642
1643  RetOps[0] = Chain;  // Update chain.
1644
1645  // Add the flag if we have it.
1646  if (Flag.getNode())
1647    RetOps.push_back(Flag);
1648
1649  return DAG.getNode(X86ISD::RET_FLAG, dl,
1650                     MVT::Other, &RetOps[0], RetOps.size());
1651}
1652
1653bool X86TargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
1654  if (N->getNumValues() != 1)
1655    return false;
1656  if (!N->hasNUsesOfValue(1, 0))
1657    return false;
1658
1659  SDValue TCChain = Chain;
1660  SDNode *Copy = *N->use_begin();
1661  if (Copy->getOpcode() == ISD::CopyToReg) {
1662    // If the copy has a glue operand, we conservatively assume it isn't safe to
1663    // perform a tail call.
1664    if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
1665      return false;
1666    TCChain = Copy->getOperand(0);
1667  } else if (Copy->getOpcode() != ISD::FP_EXTEND)
1668    return false;
1669
1670  bool HasRet = false;
1671  for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
1672       UI != UE; ++UI) {
1673    if (UI->getOpcode() != X86ISD::RET_FLAG)
1674      return false;
1675    HasRet = true;
1676  }
1677
1678  if (!HasRet)
1679    return false;
1680
1681  Chain = TCChain;
1682  return true;
1683}
1684
1685EVT
1686X86TargetLowering::getTypeForExtArgOrReturn(LLVMContext &Context, EVT VT,
1687                                            ISD::NodeType ExtendKind) const {
1688  MVT ReturnMVT;
1689  // TODO: Is this also valid on 32-bit?
1690  if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
1691    ReturnMVT = MVT::i8;
1692  else
1693    ReturnMVT = MVT::i32;
1694
1695  EVT MinVT = getRegisterType(Context, ReturnMVT);
1696  return VT.bitsLT(MinVT) ? MinVT : VT;
1697}
1698
1699/// LowerCallResult - Lower the result values of a call into the
1700/// appropriate copies out of appropriate physical registers.
1701///
1702SDValue
1703X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1704                                   CallingConv::ID CallConv, bool isVarArg,
1705                                   const SmallVectorImpl<ISD::InputArg> &Ins,
1706                                   DebugLoc dl, SelectionDAG &DAG,
1707                                   SmallVectorImpl<SDValue> &InVals) const {
1708
1709  // Assign locations to each value returned by this call.
1710  SmallVector<CCValAssign, 16> RVLocs;
1711  bool Is64Bit = Subtarget->is64Bit();
1712  CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1713                 getTargetMachine(), RVLocs, *DAG.getContext());
1714  CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
1715
1716  // Copy all of the result registers out of their specified physreg.
1717  for (unsigned i = 0; i != RVLocs.size(); ++i) {
1718    CCValAssign &VA = RVLocs[i];
1719    EVT CopyVT = VA.getValVT();
1720
1721    // If this is x86-64, and we disabled SSE, we can't return FP values
1722    if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
1723        ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
1724      report_fatal_error("SSE register return with SSE disabled");
1725    }
1726
1727    SDValue Val;
1728
1729    // If this is a call to a function that returns an fp value on the floating
1730    // point stack, we must guarantee the value is popped from the stack, so
1731    // a CopyFromReg is not good enough - the copy instruction may be eliminated
1732    // if the return value is not used. We use the FpPOP_RETVAL instruction
1733    // instead.
1734    if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1) {
1735      // If we prefer to use the value in xmm registers, copy it out as f80 and
1736      // use a truncate to move it from fp stack reg to xmm reg.
1737      if (isScalarFPTypeInSSEReg(VA.getValVT())) CopyVT = MVT::f80;
1738      SDValue Ops[] = { Chain, InFlag };
1739      Chain = SDValue(DAG.getMachineNode(X86::FpPOP_RETVAL, dl, CopyVT,
1740                                         MVT::Other, MVT::Glue, Ops, 2), 1);
1741      Val = Chain.getValue(0);
1742
1743      // Round the f80 to the right size, which also moves it to the appropriate
1744      // xmm register.
1745      if (CopyVT != VA.getValVT())
1746        Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
1747                          // This truncation won't change the value.
1748                          DAG.getIntPtrConstant(1));
1749    } else {
1750      Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1751                                 CopyVT, InFlag).getValue(1);
1752      Val = Chain.getValue(0);
1753    }
1754    InFlag = Chain.getValue(2);
1755    InVals.push_back(Val);
1756  }
1757
1758  return Chain;
1759}
1760
1761
1762//===----------------------------------------------------------------------===//
1763//                C & StdCall & Fast Calling Convention implementation
1764//===----------------------------------------------------------------------===//
1765//  StdCall calling convention seems to be standard for many Windows' API
1766//  routines and around. It differs from C calling convention just a little:
1767//  callee should clean up the stack, not caller. Symbols should be also
1768//  decorated in some fancy way :) It doesn't support any vector arguments.
1769//  For info on fast calling convention see Fast Calling Convention (tail call)
1770//  implementation LowerX86_32FastCCCallTo.
1771
1772/// CallIsStructReturn - Determines whether a call uses struct return
1773/// semantics.
1774enum StructReturnType {
1775  NotStructReturn,
1776  RegStructReturn,
1777  StackStructReturn
1778};
1779static StructReturnType
1780callIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
1781  if (Outs.empty())
1782    return NotStructReturn;
1783
1784  const ISD::ArgFlagsTy &Flags = Outs[0].Flags;
1785  if (!Flags.isSRet())
1786    return NotStructReturn;
1787  if (Flags.isInReg())
1788    return RegStructReturn;
1789  return StackStructReturn;
1790}
1791
1792/// ArgsAreStructReturn - Determines whether a function uses struct
1793/// return semantics.
1794static StructReturnType
1795argsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
1796  if (Ins.empty())
1797    return NotStructReturn;
1798
1799  const ISD::ArgFlagsTy &Flags = Ins[0].Flags;
1800  if (!Flags.isSRet())
1801    return NotStructReturn;
1802  if (Flags.isInReg())
1803    return RegStructReturn;
1804  return StackStructReturn;
1805}
1806
1807/// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
1808/// by "Src" to address "Dst" with size and alignment information specified by
1809/// the specific parameter attribute. The copy will be passed as a byval
1810/// function parameter.
1811static SDValue
1812CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
1813                          ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
1814                          DebugLoc dl) {
1815  SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
1816
1817  return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
1818                       /*isVolatile*/false, /*AlwaysInline=*/true,
1819                       MachinePointerInfo(), MachinePointerInfo());
1820}
1821
1822/// IsTailCallConvention - Return true if the calling convention is one that
1823/// supports tail call optimization.
1824static bool IsTailCallConvention(CallingConv::ID CC) {
1825  return (CC == CallingConv::Fast || CC == CallingConv::GHC ||
1826          CC == CallingConv::HiPE);
1827}
1828
1829bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
1830  if (!CI->isTailCall() || getTargetMachine().Options.DisableTailCalls)
1831    return false;
1832
1833  CallSite CS(CI);
1834  CallingConv::ID CalleeCC = CS.getCallingConv();
1835  if (!IsTailCallConvention(CalleeCC) && CalleeCC != CallingConv::C)
1836    return false;
1837
1838  return true;
1839}
1840
1841/// FuncIsMadeTailCallSafe - Return true if the function is being made into
1842/// a tailcall target by changing its ABI.
1843static bool FuncIsMadeTailCallSafe(CallingConv::ID CC,
1844                                   bool GuaranteedTailCallOpt) {
1845  return GuaranteedTailCallOpt && IsTailCallConvention(CC);
1846}
1847
1848SDValue
1849X86TargetLowering::LowerMemArgument(SDValue Chain,
1850                                    CallingConv::ID CallConv,
1851                                    const SmallVectorImpl<ISD::InputArg> &Ins,
1852                                    DebugLoc dl, SelectionDAG &DAG,
1853                                    const CCValAssign &VA,
1854                                    MachineFrameInfo *MFI,
1855                                    unsigned i) const {
1856  // Create the nodes corresponding to a load from this parameter slot.
1857  ISD::ArgFlagsTy Flags = Ins[i].Flags;
1858  bool AlwaysUseMutable = FuncIsMadeTailCallSafe(CallConv,
1859                              getTargetMachine().Options.GuaranteedTailCallOpt);
1860  bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
1861  EVT ValVT;
1862
1863  // If value is passed by pointer we have address passed instead of the value
1864  // itself.
1865  if (VA.getLocInfo() == CCValAssign::Indirect)
1866    ValVT = VA.getLocVT();
1867  else
1868    ValVT = VA.getValVT();
1869
1870  // FIXME: For now, all byval parameter objects are marked mutable. This can be
1871  // changed with more analysis.
1872  // In case of tail call optimization mark all arguments mutable. Since they
1873  // could be overwritten by lowering of arguments in case of a tail call.
1874  if (Flags.isByVal()) {
1875    unsigned Bytes = Flags.getByValSize();
1876    if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
1877    int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
1878    return DAG.getFrameIndex(FI, getPointerTy());
1879  } else {
1880    int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
1881                                    VA.getLocMemOffset(), isImmutable);
1882    SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
1883    return DAG.getLoad(ValVT, dl, Chain, FIN,
1884                       MachinePointerInfo::getFixedStack(FI),
1885                       false, false, false, 0);
1886  }
1887}
1888
1889SDValue
1890X86TargetLowering::LowerFormalArguments(SDValue Chain,
1891                                        CallingConv::ID CallConv,
1892                                        bool isVarArg,
1893                                      const SmallVectorImpl<ISD::InputArg> &Ins,
1894                                        DebugLoc dl,
1895                                        SelectionDAG &DAG,
1896                                        SmallVectorImpl<SDValue> &InVals)
1897                                          const {
1898  MachineFunction &MF = DAG.getMachineFunction();
1899  X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1900
1901  const Function* Fn = MF.getFunction();
1902  if (Fn->hasExternalLinkage() &&
1903      Subtarget->isTargetCygMing() &&
1904      Fn->getName() == "main")
1905    FuncInfo->setForceFramePointer(true);
1906
1907  MachineFrameInfo *MFI = MF.getFrameInfo();
1908  bool Is64Bit = Subtarget->is64Bit();
1909  bool IsWindows = Subtarget->isTargetWindows();
1910  bool IsWin64 = Subtarget->isTargetWin64();
1911
1912  assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
1913         "Var args not supported with calling convention fastcc, ghc or hipe");
1914
1915  // Assign locations to all of the incoming arguments.
1916  SmallVector<CCValAssign, 16> ArgLocs;
1917  CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1918                 ArgLocs, *DAG.getContext());
1919
1920  // Allocate shadow area for Win64
1921  if (IsWin64) {
1922    CCInfo.AllocateStack(32, 8);
1923  }
1924
1925  CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
1926
1927  unsigned LastVal = ~0U;
1928  SDValue ArgValue;
1929  for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1930    CCValAssign &VA = ArgLocs[i];
1931    // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
1932    // places.
1933    assert(VA.getValNo() != LastVal &&
1934           "Don't support value assigned to multiple locs yet");
1935    (void)LastVal;
1936    LastVal = VA.getValNo();
1937
1938    if (VA.isRegLoc()) {
1939      EVT RegVT = VA.getLocVT();
1940      const TargetRegisterClass *RC;
1941      if (RegVT == MVT::i32)
1942        RC = &X86::GR32RegClass;
1943      else if (Is64Bit && RegVT == MVT::i64)
1944        RC = &X86::GR64RegClass;
1945      else if (RegVT == MVT::f32)
1946        RC = &X86::FR32RegClass;
1947      else if (RegVT == MVT::f64)
1948        RC = &X86::FR64RegClass;
1949      else if (RegVT.is256BitVector())
1950        RC = &X86::VR256RegClass;
1951      else if (RegVT.is128BitVector())
1952        RC = &X86::VR128RegClass;
1953      else if (RegVT == MVT::x86mmx)
1954        RC = &X86::VR64RegClass;
1955      else
1956        llvm_unreachable("Unknown argument type!");
1957
1958      unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
1959      ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
1960
1961      // If this is an 8 or 16-bit value, it is really passed promoted to 32
1962      // bits.  Insert an assert[sz]ext to capture this, then truncate to the
1963      // right size.
1964      if (VA.getLocInfo() == CCValAssign::SExt)
1965        ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
1966                               DAG.getValueType(VA.getValVT()));
1967      else if (VA.getLocInfo() == CCValAssign::ZExt)
1968        ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
1969                               DAG.getValueType(VA.getValVT()));
1970      else if (VA.getLocInfo() == CCValAssign::BCvt)
1971        ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
1972
1973      if (VA.isExtInLoc()) {
1974        // Handle MMX values passed in XMM regs.
1975        if (RegVT.isVector()) {
1976          ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(),
1977                                 ArgValue);
1978        } else
1979          ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
1980      }
1981    } else {
1982      assert(VA.isMemLoc());
1983      ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
1984    }
1985
1986    // If value is passed via pointer - do a load.
1987    if (VA.getLocInfo() == CCValAssign::Indirect)
1988      ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
1989                             MachinePointerInfo(), false, false, false, 0);
1990
1991    InVals.push_back(ArgValue);
1992  }
1993
1994  // The x86-64 ABI for returning structs by value requires that we copy
1995  // the sret argument into %rax for the return. Save the argument into
1996  // a virtual register so that we can access it from the return points.
1997  if (Is64Bit && MF.getFunction()->hasStructRetAttr()) {
1998    X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1999    unsigned Reg = FuncInfo->getSRetReturnReg();
2000    if (!Reg) {
2001      Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(MVT::i64));
2002      FuncInfo->setSRetReturnReg(Reg);
2003    }
2004    SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[0]);
2005    Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
2006  }
2007
2008  unsigned StackSize = CCInfo.getNextStackOffset();
2009  // Align stack specially for tail calls.
2010  if (FuncIsMadeTailCallSafe(CallConv,
2011                             MF.getTarget().Options.GuaranteedTailCallOpt))
2012    StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
2013
2014  // If the function takes variable number of arguments, make a frame index for
2015  // the start of the first vararg value... for expansion of llvm.va_start.
2016  if (isVarArg) {
2017    if (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
2018                    CallConv != CallingConv::X86_ThisCall)) {
2019      FuncInfo->setVarArgsFrameIndex(MFI->CreateFixedObject(1, StackSize,true));
2020    }
2021    if (Is64Bit) {
2022      unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
2023
2024      // FIXME: We should really autogenerate these arrays
2025      static const uint16_t GPR64ArgRegsWin64[] = {
2026        X86::RCX, X86::RDX, X86::R8,  X86::R9
2027      };
2028      static const uint16_t GPR64ArgRegs64Bit[] = {
2029        X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
2030      };
2031      static const uint16_t XMMArgRegs64Bit[] = {
2032        X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2033        X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2034      };
2035      const uint16_t *GPR64ArgRegs;
2036      unsigned NumXMMRegs = 0;
2037
2038      if (IsWin64) {
2039        // The XMM registers which might contain var arg parameters are shadowed
2040        // in their paired GPR.  So we only need to save the GPR to their home
2041        // slots.
2042        TotalNumIntRegs = 4;
2043        GPR64ArgRegs = GPR64ArgRegsWin64;
2044      } else {
2045        TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
2046        GPR64ArgRegs = GPR64ArgRegs64Bit;
2047
2048        NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs64Bit,
2049                                                TotalNumXMMRegs);
2050      }
2051      unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
2052                                                       TotalNumIntRegs);
2053
2054      bool NoImplicitFloatOps = Fn->getFnAttributes().
2055        hasAttribute(Attributes::NoImplicitFloat);
2056      assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
2057             "SSE register cannot be used when SSE is disabled!");
2058      assert(!(NumXMMRegs && MF.getTarget().Options.UseSoftFloat &&
2059               NoImplicitFloatOps) &&
2060             "SSE register cannot be used when SSE is disabled!");
2061      if (MF.getTarget().Options.UseSoftFloat || NoImplicitFloatOps ||
2062          !Subtarget->hasSSE1())
2063        // Kernel mode asks for SSE to be disabled, so don't push them
2064        // on the stack.
2065        TotalNumXMMRegs = 0;
2066
2067      if (IsWin64) {
2068        const TargetFrameLowering &TFI = *getTargetMachine().getFrameLowering();
2069        // Get to the caller-allocated home save location.  Add 8 to account
2070        // for the return address.
2071        int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2072        FuncInfo->setRegSaveFrameIndex(
2073          MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
2074        // Fixup to set vararg frame on shadow area (4 x i64).
2075        if (NumIntRegs < 4)
2076          FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
2077      } else {
2078        // For X86-64, if there are vararg parameters that are passed via
2079        // registers, then we must store them to their spots on the stack so
2080        // they may be loaded by deferencing the result of va_next.
2081        FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
2082        FuncInfo->setVarArgsFPOffset(TotalNumIntRegs * 8 + NumXMMRegs * 16);
2083        FuncInfo->setRegSaveFrameIndex(
2084          MFI->CreateStackObject(TotalNumIntRegs * 8 + TotalNumXMMRegs * 16, 16,
2085                               false));
2086      }
2087
2088      // Store the integer parameter registers.
2089      SmallVector<SDValue, 8> MemOps;
2090      SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
2091                                        getPointerTy());
2092      unsigned Offset = FuncInfo->getVarArgsGPOffset();
2093      for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
2094        SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
2095                                  DAG.getIntPtrConstant(Offset));
2096        unsigned VReg = MF.addLiveIn(GPR64ArgRegs[NumIntRegs],
2097                                     &X86::GR64RegClass);
2098        SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
2099        SDValue Store =
2100          DAG.getStore(Val.getValue(1), dl, Val, FIN,
2101                       MachinePointerInfo::getFixedStack(
2102                         FuncInfo->getRegSaveFrameIndex(), Offset),
2103                       false, false, 0);
2104        MemOps.push_back(Store);
2105        Offset += 8;
2106      }
2107
2108      if (TotalNumXMMRegs != 0 && NumXMMRegs != TotalNumXMMRegs) {
2109        // Now store the XMM (fp + vector) parameter registers.
2110        SmallVector<SDValue, 11> SaveXMMOps;
2111        SaveXMMOps.push_back(Chain);
2112
2113        unsigned AL = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2114        SDValue ALVal = DAG.getCopyFromReg(DAG.getEntryNode(), dl, AL, MVT::i8);
2115        SaveXMMOps.push_back(ALVal);
2116
2117        SaveXMMOps.push_back(DAG.getIntPtrConstant(
2118                               FuncInfo->getRegSaveFrameIndex()));
2119        SaveXMMOps.push_back(DAG.getIntPtrConstant(
2120                               FuncInfo->getVarArgsFPOffset()));
2121
2122        for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
2123          unsigned VReg = MF.addLiveIn(XMMArgRegs64Bit[NumXMMRegs],
2124                                       &X86::VR128RegClass);
2125          SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::v4f32);
2126          SaveXMMOps.push_back(Val);
2127        }
2128        MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
2129                                     MVT::Other,
2130                                     &SaveXMMOps[0], SaveXMMOps.size()));
2131      }
2132
2133      if (!MemOps.empty())
2134        Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2135                            &MemOps[0], MemOps.size());
2136    }
2137  }
2138
2139  // Some CCs need callee pop.
2140  if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2141                       MF.getTarget().Options.GuaranteedTailCallOpt)) {
2142    FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
2143  } else {
2144    FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
2145    // If this is an sret function, the return should pop the hidden pointer.
2146    if (!Is64Bit && !IsTailCallConvention(CallConv) && !IsWindows &&
2147        argsAreStructReturn(Ins) == StackStructReturn)
2148      FuncInfo->setBytesToPopOnReturn(4);
2149  }
2150
2151  if (!Is64Bit) {
2152    // RegSaveFrameIndex is X86-64 only.
2153    FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
2154    if (CallConv == CallingConv::X86_FastCall ||
2155        CallConv == CallingConv::X86_ThisCall)
2156      // fastcc functions can't have varargs.
2157      FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
2158  }
2159
2160  FuncInfo->setArgumentStackSize(StackSize);
2161
2162  return Chain;
2163}
2164
2165SDValue
2166X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
2167                                    SDValue StackPtr, SDValue Arg,
2168                                    DebugLoc dl, SelectionDAG &DAG,
2169                                    const CCValAssign &VA,
2170                                    ISD::ArgFlagsTy Flags) const {
2171  unsigned LocMemOffset = VA.getLocMemOffset();
2172  SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
2173  PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
2174  if (Flags.isByVal())
2175    return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
2176
2177  return DAG.getStore(Chain, dl, Arg, PtrOff,
2178                      MachinePointerInfo::getStack(LocMemOffset),
2179                      false, false, 0);
2180}
2181
2182/// EmitTailCallLoadRetAddr - Emit a load of return address if tail call
2183/// optimization is performed and it is required.
2184SDValue
2185X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
2186                                           SDValue &OutRetAddr, SDValue Chain,
2187                                           bool IsTailCall, bool Is64Bit,
2188                                           int FPDiff, DebugLoc dl) const {
2189  // Adjust the Return address stack slot.
2190  EVT VT = getPointerTy();
2191  OutRetAddr = getReturnAddressFrameIndex(DAG);
2192
2193  // Load the "old" Return address.
2194  OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
2195                           false, false, false, 0);
2196  return SDValue(OutRetAddr.getNode(), 1);
2197}
2198
2199/// EmitTailCallStoreRetAddr - Emit a store of the return address if tail call
2200/// optimization is performed and it is required (FPDiff!=0).
2201static SDValue
2202EmitTailCallStoreRetAddr(SelectionDAG & DAG, MachineFunction &MF,
2203                         SDValue Chain, SDValue RetAddrFrIdx, EVT PtrVT,
2204                         unsigned SlotSize, int FPDiff, DebugLoc dl) {
2205  // Store the return address to the appropriate stack slot.
2206  if (!FPDiff) return Chain;
2207  // Calculate the new stack slot for the return address.
2208  int NewReturnAddrFI =
2209    MF.getFrameInfo()->CreateFixedObject(SlotSize, FPDiff-SlotSize, false);
2210  SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, PtrVT);
2211  Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
2212                       MachinePointerInfo::getFixedStack(NewReturnAddrFI),
2213                       false, false, 0);
2214  return Chain;
2215}
2216
2217SDValue
2218X86TargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2219                             SmallVectorImpl<SDValue> &InVals) const {
2220  SelectionDAG &DAG                     = CLI.DAG;
2221  DebugLoc &dl                          = CLI.DL;
2222  SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs;
2223  SmallVector<SDValue, 32> &OutVals     = CLI.OutVals;
2224  SmallVector<ISD::InputArg, 32> &Ins   = CLI.Ins;
2225  SDValue Chain                         = CLI.Chain;
2226  SDValue Callee                        = CLI.Callee;
2227  CallingConv::ID CallConv              = CLI.CallConv;
2228  bool &isTailCall                      = CLI.IsTailCall;
2229  bool isVarArg                         = CLI.IsVarArg;
2230
2231  MachineFunction &MF = DAG.getMachineFunction();
2232  bool Is64Bit        = Subtarget->is64Bit();
2233  bool IsWin64        = Subtarget->isTargetWin64();
2234  bool IsWindows      = Subtarget->isTargetWindows();
2235  StructReturnType SR = callIsStructReturn(Outs);
2236  bool IsSibcall      = false;
2237
2238  if (MF.getTarget().Options.DisableTailCalls)
2239    isTailCall = false;
2240
2241  if (isTailCall) {
2242    // Check if it's really possible to do a tail call.
2243    isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
2244                    isVarArg, SR != NotStructReturn,
2245                    MF.getFunction()->hasStructRetAttr(), CLI.RetTy,
2246                    Outs, OutVals, Ins, DAG);
2247
2248    // Sibcalls are automatically detected tailcalls which do not require
2249    // ABI changes.
2250    if (!MF.getTarget().Options.GuaranteedTailCallOpt && isTailCall)
2251      IsSibcall = true;
2252
2253    if (isTailCall)
2254      ++NumTailCalls;
2255  }
2256
2257  assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2258         "Var args not supported with calling convention fastcc, ghc or hipe");
2259
2260  // Analyze operands of the call, assigning locations to each operand.
2261  SmallVector<CCValAssign, 16> ArgLocs;
2262  CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
2263                 ArgLocs, *DAG.getContext());
2264
2265  // Allocate shadow area for Win64
2266  if (IsWin64) {
2267    CCInfo.AllocateStack(32, 8);
2268  }
2269
2270  CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2271
2272  // Get a count of how many bytes are to be pushed on the stack.
2273  unsigned NumBytes = CCInfo.getNextStackOffset();
2274  if (IsSibcall)
2275    // This is a sibcall. The memory operands are available in caller's
2276    // own caller's stack.
2277    NumBytes = 0;
2278  else if (getTargetMachine().Options.GuaranteedTailCallOpt &&
2279           IsTailCallConvention(CallConv))
2280    NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
2281
2282  int FPDiff = 0;
2283  if (isTailCall && !IsSibcall) {
2284    // Lower arguments at fp - stackoffset + fpdiff.
2285    X86MachineFunctionInfo *X86Info = MF.getInfo<X86MachineFunctionInfo>();
2286    unsigned NumBytesCallerPushed = X86Info->getBytesToPopOnReturn();
2287
2288    FPDiff = NumBytesCallerPushed - NumBytes;
2289
2290    // Set the delta of movement of the returnaddr stackslot.
2291    // But only set if delta is greater than previous delta.
2292    if (FPDiff < X86Info->getTCReturnAddrDelta())
2293      X86Info->setTCReturnAddrDelta(FPDiff);
2294  }
2295
2296  if (!IsSibcall)
2297    Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true));
2298
2299  SDValue RetAddrFrIdx;
2300  // Load return address for tail calls.
2301  if (isTailCall && FPDiff)
2302    Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
2303                                    Is64Bit, FPDiff, dl);
2304
2305  SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2306  SmallVector<SDValue, 8> MemOpChains;
2307  SDValue StackPtr;
2308
2309  // Walk the register/memloc assignments, inserting copies/loads.  In the case
2310  // of tail call optimization arguments are handle later.
2311  for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2312    CCValAssign &VA = ArgLocs[i];
2313    EVT RegVT = VA.getLocVT();
2314    SDValue Arg = OutVals[i];
2315    ISD::ArgFlagsTy Flags = Outs[i].Flags;
2316    bool isByVal = Flags.isByVal();
2317
2318    // Promote the value if needed.
2319    switch (VA.getLocInfo()) {
2320    default: llvm_unreachable("Unknown loc info!");
2321    case CCValAssign::Full: break;
2322    case CCValAssign::SExt:
2323      Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
2324      break;
2325    case CCValAssign::ZExt:
2326      Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
2327      break;
2328    case CCValAssign::AExt:
2329      if (RegVT.is128BitVector()) {
2330        // Special case: passing MMX values in XMM registers.
2331        Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
2332        Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
2333        Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
2334      } else
2335        Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
2336      break;
2337    case CCValAssign::BCvt:
2338      Arg = DAG.getNode(ISD::BITCAST, dl, RegVT, Arg);
2339      break;
2340    case CCValAssign::Indirect: {
2341      // Store the argument.
2342      SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
2343      int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
2344      Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
2345                           MachinePointerInfo::getFixedStack(FI),
2346                           false, false, 0);
2347      Arg = SpillSlot;
2348      break;
2349    }
2350    }
2351
2352    if (VA.isRegLoc()) {
2353      RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2354      if (isVarArg && IsWin64) {
2355        // Win64 ABI requires argument XMM reg to be copied to the corresponding
2356        // shadow reg if callee is a varargs function.
2357        unsigned ShadowReg = 0;
2358        switch (VA.getLocReg()) {
2359        case X86::XMM0: ShadowReg = X86::RCX; break;
2360        case X86::XMM1: ShadowReg = X86::RDX; break;
2361        case X86::XMM2: ShadowReg = X86::R8; break;
2362        case X86::XMM3: ShadowReg = X86::R9; break;
2363        }
2364        if (ShadowReg)
2365          RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
2366      }
2367    } else if (!IsSibcall && (!isTailCall || isByVal)) {
2368      assert(VA.isMemLoc());
2369      if (StackPtr.getNode() == 0)
2370        StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
2371                                      getPointerTy());
2372      MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
2373                                             dl, DAG, VA, Flags));
2374    }
2375  }
2376
2377  if (!MemOpChains.empty())
2378    Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2379                        &MemOpChains[0], MemOpChains.size());
2380
2381  if (Subtarget->isPICStyleGOT()) {
2382    // ELF / PIC requires GOT in the EBX register before function calls via PLT
2383    // GOT pointer.
2384    if (!isTailCall) {
2385      RegsToPass.push_back(std::make_pair(unsigned(X86::EBX),
2386               DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), getPointerTy())));
2387    } else {
2388      // If we are tail calling and generating PIC/GOT style code load the
2389      // address of the callee into ECX. The value in ecx is used as target of
2390      // the tail jump. This is done to circumvent the ebx/callee-saved problem
2391      // for tail calls on PIC/GOT architectures. Normally we would just put the
2392      // address of GOT into ebx and then call target@PLT. But for tail calls
2393      // ebx would be restored (since ebx is callee saved) before jumping to the
2394      // target@PLT.
2395
2396      // Note: The actual moving to ECX is done further down.
2397      GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2398      if (G && !G->getGlobal()->hasHiddenVisibility() &&
2399          !G->getGlobal()->hasProtectedVisibility())
2400        Callee = LowerGlobalAddress(Callee, DAG);
2401      else if (isa<ExternalSymbolSDNode>(Callee))
2402        Callee = LowerExternalSymbol(Callee, DAG);
2403    }
2404  }
2405
2406  if (Is64Bit && isVarArg && !IsWin64) {
2407    // From AMD64 ABI document:
2408    // For calls that may call functions that use varargs or stdargs
2409    // (prototype-less calls or calls to functions containing ellipsis (...) in
2410    // the declaration) %al is used as hidden argument to specify the number
2411    // of SSE registers used. The contents of %al do not need to match exactly
2412    // the number of registers, but must be an ubound on the number of SSE
2413    // registers used and is in the range 0 - 8 inclusive.
2414
2415    // Count the number of XMM registers allocated.
2416    static const uint16_t XMMArgRegs[] = {
2417      X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2418      X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2419    };
2420    unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
2421    assert((Subtarget->hasSSE1() || !NumXMMRegs)
2422           && "SSE registers cannot be used when SSE is disabled");
2423
2424    RegsToPass.push_back(std::make_pair(unsigned(X86::AL),
2425                                        DAG.getConstant(NumXMMRegs, MVT::i8)));
2426  }
2427
2428  // For tail calls lower the arguments to the 'real' stack slot.
2429  if (isTailCall) {
2430    // Force all the incoming stack arguments to be loaded from the stack
2431    // before any new outgoing arguments are stored to the stack, because the
2432    // outgoing stack slots may alias the incoming argument stack slots, and
2433    // the alias isn't otherwise explicit. This is slightly more conservative
2434    // than necessary, because it means that each store effectively depends
2435    // on every argument instead of just those arguments it would clobber.
2436    SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
2437
2438    SmallVector<SDValue, 8> MemOpChains2;
2439    SDValue FIN;
2440    int FI = 0;
2441    if (getTargetMachine().Options.GuaranteedTailCallOpt) {
2442      for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2443        CCValAssign &VA = ArgLocs[i];
2444        if (VA.isRegLoc())
2445          continue;
2446        assert(VA.isMemLoc());
2447        SDValue Arg = OutVals[i];
2448        ISD::ArgFlagsTy Flags = Outs[i].Flags;
2449        // Create frame index.
2450        int32_t Offset = VA.getLocMemOffset()+FPDiff;
2451        uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
2452        FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
2453        FIN = DAG.getFrameIndex(FI, getPointerTy());
2454
2455        if (Flags.isByVal()) {
2456          // Copy relative to framepointer.
2457          SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
2458          if (StackPtr.getNode() == 0)
2459            StackPtr = DAG.getCopyFromReg(Chain, dl,
2460                                          RegInfo->getStackRegister(),
2461                                          getPointerTy());
2462          Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
2463
2464          MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
2465                                                           ArgChain,
2466                                                           Flags, DAG, dl));
2467        } else {
2468          // Store relative to framepointer.
2469          MemOpChains2.push_back(
2470            DAG.getStore(ArgChain, dl, Arg, FIN,
2471                         MachinePointerInfo::getFixedStack(FI),
2472                         false, false, 0));
2473        }
2474      }
2475    }
2476
2477    if (!MemOpChains2.empty())
2478      Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2479                          &MemOpChains2[0], MemOpChains2.size());
2480
2481    // Store the return address to the appropriate stack slot.
2482    Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx,
2483                                     getPointerTy(), RegInfo->getSlotSize(),
2484                                     FPDiff, dl);
2485  }
2486
2487  // Build a sequence of copy-to-reg nodes chained together with token chain
2488  // and flag operands which copy the outgoing args into registers.
2489  SDValue InFlag;
2490  for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2491    Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2492                             RegsToPass[i].second, InFlag);
2493    InFlag = Chain.getValue(1);
2494  }
2495
2496  if (getTargetMachine().getCodeModel() == CodeModel::Large) {
2497    assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
2498    // In the 64-bit large code model, we have to make all calls
2499    // through a register, since the call instruction's 32-bit
2500    // pc-relative offset may not be large enough to hold the whole
2501    // address.
2502  } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2503    // If the callee is a GlobalAddress node (quite common, every direct call
2504    // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
2505    // it.
2506
2507    // We should use extra load for direct calls to dllimported functions in
2508    // non-JIT mode.
2509    const GlobalValue *GV = G->getGlobal();
2510    if (!GV->hasDLLImportLinkage()) {
2511      unsigned char OpFlags = 0;
2512      bool ExtraLoad = false;
2513      unsigned WrapperKind = ISD::DELETED_NODE;
2514
2515      // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
2516      // external symbols most go through the PLT in PIC mode.  If the symbol
2517      // has hidden or protected visibility, or if it is static or local, then
2518      // we don't need to use the PLT - we can directly call it.
2519      if (Subtarget->isTargetELF() &&
2520          getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
2521          GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
2522        OpFlags = X86II::MO_PLT;
2523      } else if (Subtarget->isPICStyleStubAny() &&
2524                 (GV->isDeclaration() || GV->isWeakForLinker()) &&
2525                 (!Subtarget->getTargetTriple().isMacOSX() ||
2526                  Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2527        // PC-relative references to external symbols should go through $stub,
2528        // unless we're building with the leopard linker or later, which
2529        // automatically synthesizes these stubs.
2530        OpFlags = X86II::MO_DARWIN_STUB;
2531      } else if (Subtarget->isPICStyleRIPRel() &&
2532                 isa<Function>(GV) &&
2533                 cast<Function>(GV)->getFnAttributes().
2534                   hasAttribute(Attributes::NonLazyBind)) {
2535        // If the function is marked as non-lazy, generate an indirect call
2536        // which loads from the GOT directly. This avoids runtime overhead
2537        // at the cost of eager binding (and one extra byte of encoding).
2538        OpFlags = X86II::MO_GOTPCREL;
2539        WrapperKind = X86ISD::WrapperRIP;
2540        ExtraLoad = true;
2541      }
2542
2543      Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
2544                                          G->getOffset(), OpFlags);
2545
2546      // Add a wrapper if needed.
2547      if (WrapperKind != ISD::DELETED_NODE)
2548        Callee = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Callee);
2549      // Add extra indirection if needed.
2550      if (ExtraLoad)
2551        Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Callee,
2552                             MachinePointerInfo::getGOT(),
2553                             false, false, false, 0);
2554    }
2555  } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2556    unsigned char OpFlags = 0;
2557
2558    // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
2559    // external symbols should go through the PLT.
2560    if (Subtarget->isTargetELF() &&
2561        getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2562      OpFlags = X86II::MO_PLT;
2563    } else if (Subtarget->isPICStyleStubAny() &&
2564               (!Subtarget->getTargetTriple().isMacOSX() ||
2565                Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2566      // PC-relative references to external symbols should go through $stub,
2567      // unless we're building with the leopard linker or later, which
2568      // automatically synthesizes these stubs.
2569      OpFlags = X86II::MO_DARWIN_STUB;
2570    }
2571
2572    Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
2573                                         OpFlags);
2574  }
2575
2576  // Returns a chain & a flag for retval copy to use.
2577  SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2578  SmallVector<SDValue, 8> Ops;
2579
2580  if (!IsSibcall && isTailCall) {
2581    Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
2582                           DAG.getIntPtrConstant(0, true), InFlag);
2583    InFlag = Chain.getValue(1);
2584  }
2585
2586  Ops.push_back(Chain);
2587  Ops.push_back(Callee);
2588
2589  if (isTailCall)
2590    Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
2591
2592  // Add argument registers to the end of the list so that they are known live
2593  // into the call.
2594  for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2595    Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2596                                  RegsToPass[i].second.getValueType()));
2597
2598  // Add a register mask operand representing the call-preserved registers.
2599  const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
2600  const uint32_t *Mask = TRI->getCallPreservedMask(CallConv);
2601  assert(Mask && "Missing call preserved mask for calling convention");
2602  Ops.push_back(DAG.getRegisterMask(Mask));
2603
2604  if (InFlag.getNode())
2605    Ops.push_back(InFlag);
2606
2607  if (isTailCall) {
2608    // We used to do:
2609    //// If this is the first return lowered for this function, add the regs
2610    //// to the liveout set for the function.
2611    // This isn't right, although it's probably harmless on x86; liveouts
2612    // should be computed from returns not tail calls.  Consider a void
2613    // function making a tail call to a function returning int.
2614    return DAG.getNode(X86ISD::TC_RETURN, dl,
2615                       NodeTys, &Ops[0], Ops.size());
2616  }
2617
2618  Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, &Ops[0], Ops.size());
2619  InFlag = Chain.getValue(1);
2620
2621  // Create the CALLSEQ_END node.
2622  unsigned NumBytesForCalleeToPush;
2623  if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2624                       getTargetMachine().Options.GuaranteedTailCallOpt))
2625    NumBytesForCalleeToPush = NumBytes;    // Callee pops everything
2626  else if (!Is64Bit && !IsTailCallConvention(CallConv) && !IsWindows &&
2627           SR == StackStructReturn)
2628    // If this is a call to a struct-return function, the callee
2629    // pops the hidden struct pointer, so we have to push it back.
2630    // This is common for Darwin/X86, Linux & Mingw32 targets.
2631    // For MSVC Win32 targets, the caller pops the hidden struct pointer.
2632    NumBytesForCalleeToPush = 4;
2633  else
2634    NumBytesForCalleeToPush = 0;  // Callee pops nothing.
2635
2636  // Returns a flag for retval copy to use.
2637  if (!IsSibcall) {
2638    Chain = DAG.getCALLSEQ_END(Chain,
2639                               DAG.getIntPtrConstant(NumBytes, true),
2640                               DAG.getIntPtrConstant(NumBytesForCalleeToPush,
2641                                                     true),
2642                               InFlag);
2643    InFlag = Chain.getValue(1);
2644  }
2645
2646  // Handle result values, copying them out of physregs into vregs that we
2647  // return.
2648  return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
2649                         Ins, dl, DAG, InVals);
2650}
2651
2652
2653//===----------------------------------------------------------------------===//
2654//                Fast Calling Convention (tail call) implementation
2655//===----------------------------------------------------------------------===//
2656
2657//  Like std call, callee cleans arguments, convention except that ECX is
2658//  reserved for storing the tail called function address. Only 2 registers are
2659//  free for argument passing (inreg). Tail call optimization is performed
2660//  provided:
2661//                * tailcallopt is enabled
2662//                * caller/callee are fastcc
2663//  On X86_64 architecture with GOT-style position independent code only local
2664//  (within module) calls are supported at the moment.
2665//  To keep the stack aligned according to platform abi the function
2666//  GetAlignedArgumentStackSize ensures that argument delta is always multiples
2667//  of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
2668//  If a tail called function callee has more arguments than the caller the
2669//  caller needs to make sure that there is room to move the RETADDR to. This is
2670//  achieved by reserving an area the size of the argument delta right after the
2671//  original REtADDR, but before the saved framepointer or the spilled registers
2672//  e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
2673//  stack layout:
2674//    arg1
2675//    arg2
2676//    RETADDR
2677//    [ new RETADDR
2678//      move area ]
2679//    (possible EBP)
2680//    ESI
2681//    EDI
2682//    local1 ..
2683
2684/// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
2685/// for a 16 byte align requirement.
2686unsigned
2687X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
2688                                               SelectionDAG& DAG) const {
2689  MachineFunction &MF = DAG.getMachineFunction();
2690  const TargetMachine &TM = MF.getTarget();
2691  const TargetFrameLowering &TFI = *TM.getFrameLowering();
2692  unsigned StackAlignment = TFI.getStackAlignment();
2693  uint64_t AlignMask = StackAlignment - 1;
2694  int64_t Offset = StackSize;
2695  unsigned SlotSize = RegInfo->getSlotSize();
2696  if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
2697    // Number smaller than 12 so just add the difference.
2698    Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
2699  } else {
2700    // Mask out lower bits, add stackalignment once plus the 12 bytes.
2701    Offset = ((~AlignMask) & Offset) + StackAlignment +
2702      (StackAlignment-SlotSize);
2703  }
2704  return Offset;
2705}
2706
2707/// MatchingStackOffset - Return true if the given stack call argument is
2708/// already available in the same position (relatively) of the caller's
2709/// incoming argument stack.
2710static
2711bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
2712                         MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
2713                         const X86InstrInfo *TII) {
2714  unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
2715  int FI = INT_MAX;
2716  if (Arg.getOpcode() == ISD::CopyFromReg) {
2717    unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
2718    if (!TargetRegisterInfo::isVirtualRegister(VR))
2719      return false;
2720    MachineInstr *Def = MRI->getVRegDef(VR);
2721    if (!Def)
2722      return false;
2723    if (!Flags.isByVal()) {
2724      if (!TII->isLoadFromStackSlot(Def, FI))
2725        return false;
2726    } else {
2727      unsigned Opcode = Def->getOpcode();
2728      if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r) &&
2729          Def->getOperand(1).isFI()) {
2730        FI = Def->getOperand(1).getIndex();
2731        Bytes = Flags.getByValSize();
2732      } else
2733        return false;
2734    }
2735  } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
2736    if (Flags.isByVal())
2737      // ByVal argument is passed in as a pointer but it's now being
2738      // dereferenced. e.g.
2739      // define @foo(%struct.X* %A) {
2740      //   tail call @bar(%struct.X* byval %A)
2741      // }
2742      return false;
2743    SDValue Ptr = Ld->getBasePtr();
2744    FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
2745    if (!FINode)
2746      return false;
2747    FI = FINode->getIndex();
2748  } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
2749    FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
2750    FI = FINode->getIndex();
2751    Bytes = Flags.getByValSize();
2752  } else
2753    return false;
2754
2755  assert(FI != INT_MAX);
2756  if (!MFI->isFixedObjectIndex(FI))
2757    return false;
2758  return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
2759}
2760
2761/// IsEligibleForTailCallOptimization - Check whether the call is eligible
2762/// for tail call optimization. Targets which want to do tail call
2763/// optimization should implement this function.
2764bool
2765X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
2766                                                     CallingConv::ID CalleeCC,
2767                                                     bool isVarArg,
2768                                                     bool isCalleeStructRet,
2769                                                     bool isCallerStructRet,
2770                                                     Type *RetTy,
2771                                    const SmallVectorImpl<ISD::OutputArg> &Outs,
2772                                    const SmallVectorImpl<SDValue> &OutVals,
2773                                    const SmallVectorImpl<ISD::InputArg> &Ins,
2774                                                     SelectionDAG& DAG) const {
2775  if (!IsTailCallConvention(CalleeCC) &&
2776      CalleeCC != CallingConv::C)
2777    return false;
2778
2779  // If -tailcallopt is specified, make fastcc functions tail-callable.
2780  const MachineFunction &MF = DAG.getMachineFunction();
2781  const Function *CallerF = DAG.getMachineFunction().getFunction();
2782
2783  // If the function return type is x86_fp80 and the callee return type is not,
2784  // then the FP_EXTEND of the call result is not a nop. It's not safe to
2785  // perform a tailcall optimization here.
2786  if (CallerF->getReturnType()->isX86_FP80Ty() && !RetTy->isX86_FP80Ty())
2787    return false;
2788
2789  CallingConv::ID CallerCC = CallerF->getCallingConv();
2790  bool CCMatch = CallerCC == CalleeCC;
2791
2792  if (getTargetMachine().Options.GuaranteedTailCallOpt) {
2793    if (IsTailCallConvention(CalleeCC) && CCMatch)
2794      return true;
2795    return false;
2796  }
2797
2798  // Look for obvious safe cases to perform tail call optimization that do not
2799  // require ABI changes. This is what gcc calls sibcall.
2800
2801  // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
2802  // emit a special epilogue.
2803  if (RegInfo->needsStackRealignment(MF))
2804    return false;
2805
2806  // Also avoid sibcall optimization if either caller or callee uses struct
2807  // return semantics.
2808  if (isCalleeStructRet || isCallerStructRet)
2809    return false;
2810
2811  // An stdcall caller is expected to clean up its arguments; the callee
2812  // isn't going to do that.
2813  if (!CCMatch && CallerCC==CallingConv::X86_StdCall)
2814    return false;
2815
2816  // Do not sibcall optimize vararg calls unless all arguments are passed via
2817  // registers.
2818  if (isVarArg && !Outs.empty()) {
2819
2820    // Optimizing for varargs on Win64 is unlikely to be safe without
2821    // additional testing.
2822    if (Subtarget->isTargetWin64())
2823      return false;
2824
2825    SmallVector<CCValAssign, 16> ArgLocs;
2826    CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
2827                   getTargetMachine(), ArgLocs, *DAG.getContext());
2828
2829    CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2830    for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
2831      if (!ArgLocs[i].isRegLoc())
2832        return false;
2833  }
2834
2835  // If the call result is in ST0 / ST1, it needs to be popped off the x87
2836  // stack.  Therefore, if it's not used by the call it is not safe to optimize
2837  // this into a sibcall.
2838  bool Unused = false;
2839  for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
2840    if (!Ins[i].Used) {
2841      Unused = true;
2842      break;
2843    }
2844  }
2845  if (Unused) {
2846    SmallVector<CCValAssign, 16> RVLocs;
2847    CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(),
2848                   getTargetMachine(), RVLocs, *DAG.getContext());
2849    CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2850    for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2851      CCValAssign &VA = RVLocs[i];
2852      if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1)
2853        return false;
2854    }
2855  }
2856
2857  // If the calling conventions do not match, then we'd better make sure the
2858  // results are returned in the same way as what the caller expects.
2859  if (!CCMatch) {
2860    SmallVector<CCValAssign, 16> RVLocs1;
2861    CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(),
2862                    getTargetMachine(), RVLocs1, *DAG.getContext());
2863    CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
2864
2865    SmallVector<CCValAssign, 16> RVLocs2;
2866    CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(),
2867                    getTargetMachine(), RVLocs2, *DAG.getContext());
2868    CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
2869
2870    if (RVLocs1.size() != RVLocs2.size())
2871      return false;
2872    for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
2873      if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
2874        return false;
2875      if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
2876        return false;
2877      if (RVLocs1[i].isRegLoc()) {
2878        if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
2879          return false;
2880      } else {
2881        if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
2882          return false;
2883      }
2884    }
2885  }
2886
2887  // If the callee takes no arguments then go on to check the results of the
2888  // call.
2889  if (!Outs.empty()) {
2890    // Check if stack adjustment is needed. For now, do not do this if any
2891    // argument is passed on the stack.
2892    SmallVector<CCValAssign, 16> ArgLocs;
2893    CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
2894                   getTargetMachine(), ArgLocs, *DAG.getContext());
2895
2896    // Allocate shadow area for Win64
2897    if (Subtarget->isTargetWin64()) {
2898      CCInfo.AllocateStack(32, 8);
2899    }
2900
2901    CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2902    if (CCInfo.getNextStackOffset()) {
2903      MachineFunction &MF = DAG.getMachineFunction();
2904      if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
2905        return false;
2906
2907      // Check if the arguments are already laid out in the right way as
2908      // the caller's fixed stack objects.
2909      MachineFrameInfo *MFI = MF.getFrameInfo();
2910      const MachineRegisterInfo *MRI = &MF.getRegInfo();
2911      const X86InstrInfo *TII =
2912        ((const X86TargetMachine&)getTargetMachine()).getInstrInfo();
2913      for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2914        CCValAssign &VA = ArgLocs[i];
2915        SDValue Arg = OutVals[i];
2916        ISD::ArgFlagsTy Flags = Outs[i].Flags;
2917        if (VA.getLocInfo() == CCValAssign::Indirect)
2918          return false;
2919        if (!VA.isRegLoc()) {
2920          if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2921                                   MFI, MRI, TII))
2922            return false;
2923        }
2924      }
2925    }
2926
2927    // If the tailcall address may be in a register, then make sure it's
2928    // possible to register allocate for it. In 32-bit, the call address can
2929    // only target EAX, EDX, or ECX since the tail call must be scheduled after
2930    // callee-saved registers are restored. These happen to be the same
2931    // registers used to pass 'inreg' arguments so watch out for those.
2932    if (!Subtarget->is64Bit() &&
2933        !isa<GlobalAddressSDNode>(Callee) &&
2934        !isa<ExternalSymbolSDNode>(Callee)) {
2935      unsigned NumInRegs = 0;
2936      for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2937        CCValAssign &VA = ArgLocs[i];
2938        if (!VA.isRegLoc())
2939          continue;
2940        unsigned Reg = VA.getLocReg();
2941        switch (Reg) {
2942        default: break;
2943        case X86::EAX: case X86::EDX: case X86::ECX:
2944          if (++NumInRegs == 3)
2945            return false;
2946          break;
2947        }
2948      }
2949    }
2950  }
2951
2952  return true;
2953}
2954
2955FastISel *
2956X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
2957                                  const TargetLibraryInfo *libInfo) const {
2958  return X86::createFastISel(funcInfo, libInfo);
2959}
2960
2961
2962//===----------------------------------------------------------------------===//
2963//                           Other Lowering Hooks
2964//===----------------------------------------------------------------------===//
2965
2966static bool MayFoldLoad(SDValue Op) {
2967  return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
2968}
2969
2970static bool MayFoldIntoStore(SDValue Op) {
2971  return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
2972}
2973
2974static bool isTargetShuffle(unsigned Opcode) {
2975  switch(Opcode) {
2976  default: return false;
2977  case X86ISD::PSHUFD:
2978  case X86ISD::PSHUFHW:
2979  case X86ISD::PSHUFLW:
2980  case X86ISD::SHUFP:
2981  case X86ISD::PALIGN:
2982  case X86ISD::MOVLHPS:
2983  case X86ISD::MOVLHPD:
2984  case X86ISD::MOVHLPS:
2985  case X86ISD::MOVLPS:
2986  case X86ISD::MOVLPD:
2987  case X86ISD::MOVSHDUP:
2988  case X86ISD::MOVSLDUP:
2989  case X86ISD::MOVDDUP:
2990  case X86ISD::MOVSS:
2991  case X86ISD::MOVSD:
2992  case X86ISD::UNPCKL:
2993  case X86ISD::UNPCKH:
2994  case X86ISD::VPERMILP:
2995  case X86ISD::VPERM2X128:
2996  case X86ISD::VPERMI:
2997    return true;
2998  }
2999}
3000
3001static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
3002                                    SDValue V1, SelectionDAG &DAG) {
3003  switch(Opc) {
3004  default: llvm_unreachable("Unknown x86 shuffle node");
3005  case X86ISD::MOVSHDUP:
3006  case X86ISD::MOVSLDUP:
3007  case X86ISD::MOVDDUP:
3008    return DAG.getNode(Opc, dl, VT, V1);
3009  }
3010}
3011
3012static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
3013                                    SDValue V1, unsigned TargetMask,
3014                                    SelectionDAG &DAG) {
3015  switch(Opc) {
3016  default: llvm_unreachable("Unknown x86 shuffle node");
3017  case X86ISD::PSHUFD:
3018  case X86ISD::PSHUFHW:
3019  case X86ISD::PSHUFLW:
3020  case X86ISD::VPERMILP:
3021  case X86ISD::VPERMI:
3022    return DAG.getNode(Opc, dl, VT, V1, DAG.getConstant(TargetMask, MVT::i8));
3023  }
3024}
3025
3026static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
3027                                    SDValue V1, SDValue V2, unsigned TargetMask,
3028                                    SelectionDAG &DAG) {
3029  switch(Opc) {
3030  default: llvm_unreachable("Unknown x86 shuffle node");
3031  case X86ISD::PALIGN:
3032  case X86ISD::SHUFP:
3033  case X86ISD::VPERM2X128:
3034    return DAG.getNode(Opc, dl, VT, V1, V2,
3035                       DAG.getConstant(TargetMask, MVT::i8));
3036  }
3037}
3038
3039static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
3040                                    SDValue V1, SDValue V2, SelectionDAG &DAG) {
3041  switch(Opc) {
3042  default: llvm_unreachable("Unknown x86 shuffle node");
3043  case X86ISD::MOVLHPS:
3044  case X86ISD::MOVLHPD:
3045  case X86ISD::MOVHLPS:
3046  case X86ISD::MOVLPS:
3047  case X86ISD::MOVLPD:
3048  case X86ISD::MOVSS:
3049  case X86ISD::MOVSD:
3050  case X86ISD::UNPCKL:
3051  case X86ISD::UNPCKH:
3052    return DAG.getNode(Opc, dl, VT, V1, V2);
3053  }
3054}
3055
3056SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
3057  MachineFunction &MF = DAG.getMachineFunction();
3058  X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
3059  int ReturnAddrIndex = FuncInfo->getRAIndex();
3060
3061  if (ReturnAddrIndex == 0) {
3062    // Set up a frame object for the return address.
3063    unsigned SlotSize = RegInfo->getSlotSize();
3064    ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize, -SlotSize,
3065                                                           false);
3066    FuncInfo->setRAIndex(ReturnAddrIndex);
3067  }
3068
3069  return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
3070}
3071
3072
3073bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
3074                                       bool hasSymbolicDisplacement) {
3075  // Offset should fit into 32 bit immediate field.
3076  if (!isInt<32>(Offset))
3077    return false;
3078
3079  // If we don't have a symbolic displacement - we don't have any extra
3080  // restrictions.
3081  if (!hasSymbolicDisplacement)
3082    return true;
3083
3084  // FIXME: Some tweaks might be needed for medium code model.
3085  if (M != CodeModel::Small && M != CodeModel::Kernel)
3086    return false;
3087
3088  // For small code model we assume that latest object is 16MB before end of 31
3089  // bits boundary. We may also accept pretty large negative constants knowing
3090  // that all objects are in the positive half of address space.
3091  if (M == CodeModel::Small && Offset < 16*1024*1024)
3092    return true;
3093
3094  // For kernel code model we know that all object resist in the negative half
3095  // of 32bits address space. We may not accept negative offsets, since they may
3096  // be just off and we may accept pretty large positive ones.
3097  if (M == CodeModel::Kernel && Offset > 0)
3098    return true;
3099
3100  return false;
3101}
3102
3103/// isCalleePop - Determines whether the callee is required to pop its
3104/// own arguments. Callee pop is necessary to support tail calls.
3105bool X86::isCalleePop(CallingConv::ID CallingConv,
3106                      bool is64Bit, bool IsVarArg, bool TailCallOpt) {
3107  if (IsVarArg)
3108    return false;
3109
3110  switch (CallingConv) {
3111  default:
3112    return false;
3113  case CallingConv::X86_StdCall:
3114    return !is64Bit;
3115  case CallingConv::X86_FastCall:
3116    return !is64Bit;
3117  case CallingConv::X86_ThisCall:
3118    return !is64Bit;
3119  case CallingConv::Fast:
3120    return TailCallOpt;
3121  case CallingConv::GHC:
3122    return TailCallOpt;
3123  case CallingConv::HiPE:
3124    return TailCallOpt;
3125  }
3126}
3127
3128/// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
3129/// specific condition code, returning the condition code and the LHS/RHS of the
3130/// comparison to make.
3131static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
3132                               SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
3133  if (!isFP) {
3134    if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
3135      if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
3136        // X > -1   -> X == 0, jump !sign.
3137        RHS = DAG.getConstant(0, RHS.getValueType());
3138        return X86::COND_NS;
3139      }
3140      if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
3141        // X < 0   -> X == 0, jump on sign.
3142        return X86::COND_S;
3143      }
3144      if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
3145        // X < 1   -> X <= 0
3146        RHS = DAG.getConstant(0, RHS.getValueType());
3147        return X86::COND_LE;
3148      }
3149    }
3150
3151    switch (SetCCOpcode) {
3152    default: llvm_unreachable("Invalid integer condition!");
3153    case ISD::SETEQ:  return X86::COND_E;
3154    case ISD::SETGT:  return X86::COND_G;
3155    case ISD::SETGE:  return X86::COND_GE;
3156    case ISD::SETLT:  return X86::COND_L;
3157    case ISD::SETLE:  return X86::COND_LE;
3158    case ISD::SETNE:  return X86::COND_NE;
3159    case ISD::SETULT: return X86::COND_B;
3160    case ISD::SETUGT: return X86::COND_A;
3161    case ISD::SETULE: return X86::COND_BE;
3162    case ISD::SETUGE: return X86::COND_AE;
3163    }
3164  }
3165
3166  // First determine if it is required or is profitable to flip the operands.
3167
3168  // If LHS is a foldable load, but RHS is not, flip the condition.
3169  if (ISD::isNON_EXTLoad(LHS.getNode()) &&
3170      !ISD::isNON_EXTLoad(RHS.getNode())) {
3171    SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
3172    std::swap(LHS, RHS);
3173  }
3174
3175  switch (SetCCOpcode) {
3176  default: break;
3177  case ISD::SETOLT:
3178  case ISD::SETOLE:
3179  case ISD::SETUGT:
3180  case ISD::SETUGE:
3181    std::swap(LHS, RHS);
3182    break;
3183  }
3184
3185  // On a floating point condition, the flags are set as follows:
3186  // ZF  PF  CF   op
3187  //  0 | 0 | 0 | X > Y
3188  //  0 | 0 | 1 | X < Y
3189  //  1 | 0 | 0 | X == Y
3190  //  1 | 1 | 1 | unordered
3191  switch (SetCCOpcode) {
3192  default: llvm_unreachable("Condcode should be pre-legalized away");
3193  case ISD::SETUEQ:
3194  case ISD::SETEQ:   return X86::COND_E;
3195  case ISD::SETOLT:              // flipped
3196  case ISD::SETOGT:
3197  case ISD::SETGT:   return X86::COND_A;
3198  case ISD::SETOLE:              // flipped
3199  case ISD::SETOGE:
3200  case ISD::SETGE:   return X86::COND_AE;
3201  case ISD::SETUGT:              // flipped
3202  case ISD::SETULT:
3203  case ISD::SETLT:   return X86::COND_B;
3204  case ISD::SETUGE:              // flipped
3205  case ISD::SETULE:
3206  case ISD::SETLE:   return X86::COND_BE;
3207  case ISD::SETONE:
3208  case ISD::SETNE:   return X86::COND_NE;
3209  case ISD::SETUO:   return X86::COND_P;
3210  case ISD::SETO:    return X86::COND_NP;
3211  case ISD::SETOEQ:
3212  case ISD::SETUNE:  return X86::COND_INVALID;
3213  }
3214}
3215
3216/// hasFPCMov - is there a floating point cmov for the specific X86 condition
3217/// code. Current x86 isa includes the following FP cmov instructions:
3218/// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
3219static bool hasFPCMov(unsigned X86CC) {
3220  switch (X86CC) {
3221  default:
3222    return false;
3223  case X86::COND_B:
3224  case X86::COND_BE:
3225  case X86::COND_E:
3226  case X86::COND_P:
3227  case X86::COND_A:
3228  case X86::COND_AE:
3229  case X86::COND_NE:
3230  case X86::COND_NP:
3231    return true;
3232  }
3233}
3234
3235/// isFPImmLegal - Returns true if the target can instruction select the
3236/// specified FP immediate natively. If false, the legalizer will
3237/// materialize the FP immediate as a load from a constant pool.
3238bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3239  for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
3240    if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
3241      return true;
3242  }
3243  return false;
3244}
3245
3246/// isUndefOrInRange - Return true if Val is undef or if its value falls within
3247/// the specified range (L, H].
3248static bool isUndefOrInRange(int Val, int Low, int Hi) {
3249  return (Val < 0) || (Val >= Low && Val < Hi);
3250}
3251
3252/// isUndefOrEqual - Val is either less than zero (undef) or equal to the
3253/// specified value.
3254static bool isUndefOrEqual(int Val, int CmpVal) {
3255  if (Val < 0 || Val == CmpVal)
3256    return true;
3257  return false;
3258}
3259
3260/// isSequentialOrUndefInRange - Return true if every element in Mask, beginning
3261/// from position Pos and ending in Pos+Size, falls within the specified
3262/// sequential range (L, L+Pos]. or is undef.
3263static bool isSequentialOrUndefInRange(ArrayRef<int> Mask,
3264                                       unsigned Pos, unsigned Size, int Low) {
3265  for (unsigned i = Pos, e = Pos+Size; i != e; ++i, ++Low)
3266    if (!isUndefOrEqual(Mask[i], Low))
3267      return false;
3268  return true;
3269}
3270
3271/// isPSHUFDMask - Return true if the node specifies a shuffle of elements that
3272/// is suitable for input to PSHUFD or PSHUFW.  That is, it doesn't reference
3273/// the second operand.
3274static bool isPSHUFDMask(ArrayRef<int> Mask, EVT VT) {
3275  if (VT == MVT::v4f32 || VT == MVT::v4i32 )
3276    return (Mask[0] < 4 && Mask[1] < 4 && Mask[2] < 4 && Mask[3] < 4);
3277  if (VT == MVT::v2f64 || VT == MVT::v2i64)
3278    return (Mask[0] < 2 && Mask[1] < 2);
3279  return false;
3280}
3281
3282/// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that
3283/// is suitable for input to PSHUFHW.
3284static bool isPSHUFHWMask(ArrayRef<int> Mask, EVT VT, bool HasAVX2) {
3285  if (VT != MVT::v8i16 && (!HasAVX2 || VT != MVT::v16i16))
3286    return false;
3287
3288  // Lower quadword copied in order or undef.
3289  if (!isSequentialOrUndefInRange(Mask, 0, 4, 0))
3290    return false;
3291
3292  // Upper quadword shuffled.
3293  for (unsigned i = 4; i != 8; ++i)
3294    if (!isUndefOrInRange(Mask[i], 4, 8))
3295      return false;
3296
3297  if (VT == MVT::v16i16) {
3298    // Lower quadword copied in order or undef.
3299    if (!isSequentialOrUndefInRange(Mask, 8, 4, 8))
3300      return false;
3301
3302    // Upper quadword shuffled.
3303    for (unsigned i = 12; i != 16; ++i)
3304      if (!isUndefOrInRange(Mask[i], 12, 16))
3305        return false;
3306  }
3307
3308  return true;
3309}
3310
3311/// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that
3312/// is suitable for input to PSHUFLW.
3313static bool isPSHUFLWMask(ArrayRef<int> Mask, EVT VT, bool HasAVX2) {
3314  if (VT != MVT::v8i16 && (!HasAVX2 || VT != MVT::v16i16))
3315    return false;
3316
3317  // Upper quadword copied in order.
3318  if (!isSequentialOrUndefInRange(Mask, 4, 4, 4))
3319    return false;
3320
3321  // Lower quadword shuffled.
3322  for (unsigned i = 0; i != 4; ++i)
3323    if (!isUndefOrInRange(Mask[i], 0, 4))
3324      return false;
3325
3326  if (VT == MVT::v16i16) {
3327    // Upper quadword copied in order.
3328    if (!isSequentialOrUndefInRange(Mask, 12, 4, 12))
3329      return false;
3330
3331    // Lower quadword shuffled.
3332    for (unsigned i = 8; i != 12; ++i)
3333      if (!isUndefOrInRange(Mask[i], 8, 12))
3334        return false;
3335  }
3336
3337  return true;
3338}
3339
3340/// isPALIGNRMask - Return true if the node specifies a shuffle of elements that
3341/// is suitable for input to PALIGNR.
3342static bool isPALIGNRMask(ArrayRef<int> Mask, EVT VT,
3343                          const X86Subtarget *Subtarget) {
3344  if ((VT.getSizeInBits() == 128 && !Subtarget->hasSSSE3()) ||
3345      (VT.getSizeInBits() == 256 && !Subtarget->hasAVX2()))
3346    return false;
3347
3348  unsigned NumElts = VT.getVectorNumElements();
3349  unsigned NumLanes = VT.getSizeInBits()/128;
3350  unsigned NumLaneElts = NumElts/NumLanes;
3351
3352  // Do not handle 64-bit element shuffles with palignr.
3353  if (NumLaneElts == 2)
3354    return false;
3355
3356  for (unsigned l = 0; l != NumElts; l+=NumLaneElts) {
3357    unsigned i;
3358    for (i = 0; i != NumLaneElts; ++i) {
3359      if (Mask[i+l] >= 0)
3360        break;
3361    }
3362
3363    // Lane is all undef, go to next lane
3364    if (i == NumLaneElts)
3365      continue;
3366
3367    int Start = Mask[i+l];
3368
3369    // Make sure its in this lane in one of the sources
3370    if (!isUndefOrInRange(Start, l, l+NumLaneElts) &&
3371        !isUndefOrInRange(Start, l+NumElts, l+NumElts+NumLaneElts))
3372      return false;
3373
3374    // If not lane 0, then we must match lane 0
3375    if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Start, Mask[i]+l))
3376      return false;
3377
3378    // Correct second source to be contiguous with first source
3379    if (Start >= (int)NumElts)
3380      Start -= NumElts - NumLaneElts;
3381
3382    // Make sure we're shifting in the right direction.
3383    if (Start <= (int)(i+l))
3384      return false;
3385
3386    Start -= i;
3387
3388    // Check the rest of the elements to see if they are consecutive.
3389    for (++i; i != NumLaneElts; ++i) {
3390      int Idx = Mask[i+l];
3391
3392      // Make sure its in this lane
3393      if (!isUndefOrInRange(Idx, l, l+NumLaneElts) &&
3394          !isUndefOrInRange(Idx, l+NumElts, l+NumElts+NumLaneElts))
3395        return false;
3396
3397      // If not lane 0, then we must match lane 0
3398      if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Idx, Mask[i]+l))
3399        return false;
3400
3401      if (Idx >= (int)NumElts)
3402        Idx -= NumElts - NumLaneElts;
3403
3404      if (!isUndefOrEqual(Idx, Start+i))
3405        return false;
3406
3407    }
3408  }
3409
3410  return true;
3411}
3412
3413/// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
3414/// the two vector operands have swapped position.
3415static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask,
3416                                     unsigned NumElems) {
3417  for (unsigned i = 0; i != NumElems; ++i) {
3418    int idx = Mask[i];
3419    if (idx < 0)
3420      continue;
3421    else if (idx < (int)NumElems)
3422      Mask[i] = idx + NumElems;
3423    else
3424      Mask[i] = idx - NumElems;
3425  }
3426}
3427
3428/// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
3429/// specifies a shuffle of elements that is suitable for input to 128/256-bit
3430/// SHUFPS and SHUFPD. If Commuted is true, then it checks for sources to be
3431/// reverse of what x86 shuffles want.
3432static bool isSHUFPMask(ArrayRef<int> Mask, EVT VT, bool HasAVX,
3433                        bool Commuted = false) {
3434  if (!HasAVX && VT.getSizeInBits() == 256)
3435    return false;
3436
3437  unsigned NumElems = VT.getVectorNumElements();
3438  unsigned NumLanes = VT.getSizeInBits()/128;
3439  unsigned NumLaneElems = NumElems/NumLanes;
3440
3441  if (NumLaneElems != 2 && NumLaneElems != 4)
3442    return false;
3443
3444  // VSHUFPSY divides the resulting vector into 4 chunks.
3445  // The sources are also splitted into 4 chunks, and each destination
3446  // chunk must come from a different source chunk.
3447  //
3448  //  SRC1 =>   X7    X6    X5    X4    X3    X2    X1    X0
3449  //  SRC2 =>   Y7    Y6    Y5    Y4    Y3    Y2    Y1    Y9
3450  //
3451  //  DST  =>  Y7..Y4,   Y7..Y4,   X7..X4,   X7..X4,
3452  //           Y3..Y0,   Y3..Y0,   X3..X0,   X3..X0
3453  //
3454  // VSHUFPDY divides the resulting vector into 4 chunks.
3455  // The sources are also splitted into 4 chunks, and each destination
3456  // chunk must come from a different source chunk.
3457  //
3458  //  SRC1 =>      X3       X2       X1       X0
3459  //  SRC2 =>      Y3       Y2       Y1       Y0
3460  //
3461  //  DST  =>  Y3..Y2,  X3..X2,  Y1..Y0,  X1..X0
3462  //
3463  unsigned HalfLaneElems = NumLaneElems/2;
3464  for (unsigned l = 0; l != NumElems; l += NumLaneElems) {
3465    for (unsigned i = 0; i != NumLaneElems; ++i) {
3466      int Idx = Mask[i+l];
3467      unsigned RngStart = l + ((Commuted == (i<HalfLaneElems)) ? NumElems : 0);
3468      if (!isUndefOrInRange(Idx, RngStart, RngStart+NumLaneElems))
3469        return false;
3470      // For VSHUFPSY, the mask of the second half must be the same as the
3471      // first but with the appropriate offsets. This works in the same way as
3472      // VPERMILPS works with masks.
3473      if (NumElems != 8 || l == 0 || Mask[i] < 0)
3474        continue;
3475      if (!isUndefOrEqual(Idx, Mask[i]+l))
3476        return false;
3477    }
3478  }
3479
3480  return true;
3481}
3482
3483/// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
3484/// specifies a shuffle of elements that is suitable for input to MOVHLPS.
3485static bool isMOVHLPSMask(ArrayRef<int> Mask, EVT VT) {
3486  if (!VT.is128BitVector())
3487    return false;
3488
3489  unsigned NumElems = VT.getVectorNumElements();
3490
3491  if (NumElems != 4)
3492    return false;
3493
3494  // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
3495  return isUndefOrEqual(Mask[0], 6) &&
3496         isUndefOrEqual(Mask[1], 7) &&
3497         isUndefOrEqual(Mask[2], 2) &&
3498         isUndefOrEqual(Mask[3], 3);
3499}
3500
3501/// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
3502/// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
3503/// <2, 3, 2, 3>
3504static bool isMOVHLPS_v_undef_Mask(ArrayRef<int> Mask, EVT VT) {
3505  if (!VT.is128BitVector())
3506    return false;
3507
3508  unsigned NumElems = VT.getVectorNumElements();
3509
3510  if (NumElems != 4)
3511    return false;
3512
3513  return isUndefOrEqual(Mask[0], 2) &&
3514         isUndefOrEqual(Mask[1], 3) &&
3515         isUndefOrEqual(Mask[2], 2) &&
3516         isUndefOrEqual(Mask[3], 3);
3517}
3518
3519/// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
3520/// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
3521static bool isMOVLPMask(ArrayRef<int> Mask, EVT VT) {
3522  if (!VT.is128BitVector())
3523    return false;
3524
3525  unsigned NumElems = VT.getVectorNumElements();
3526
3527  if (NumElems != 2 && NumElems != 4)
3528    return false;
3529
3530  for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3531    if (!isUndefOrEqual(Mask[i], i + NumElems))
3532      return false;
3533
3534  for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
3535    if (!isUndefOrEqual(Mask[i], i))
3536      return false;
3537
3538  return true;
3539}
3540
3541/// isMOVLHPSMask - Return true if the specified VECTOR_SHUFFLE operand
3542/// specifies a shuffle of elements that is suitable for input to MOVLHPS.
3543static bool isMOVLHPSMask(ArrayRef<int> Mask, EVT VT) {
3544  if (!VT.is128BitVector())
3545    return false;
3546
3547  unsigned NumElems = VT.getVectorNumElements();
3548
3549  if (NumElems != 2 && NumElems != 4)
3550    return false;
3551
3552  for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3553    if (!isUndefOrEqual(Mask[i], i))
3554      return false;
3555
3556  for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3557    if (!isUndefOrEqual(Mask[i + e], i + NumElems))
3558      return false;
3559
3560  return true;
3561}
3562
3563//
3564// Some special combinations that can be optimized.
3565//
3566static
3567SDValue Compact8x32ShuffleNode(ShuffleVectorSDNode *SVOp,
3568                               SelectionDAG &DAG) {
3569  EVT VT = SVOp->getValueType(0);
3570  DebugLoc dl = SVOp->getDebugLoc();
3571
3572  if (VT != MVT::v8i32 && VT != MVT::v8f32)
3573    return SDValue();
3574
3575  ArrayRef<int> Mask = SVOp->getMask();
3576
3577  // These are the special masks that may be optimized.
3578  static const int MaskToOptimizeEven[] = {0, 8, 2, 10, 4, 12, 6, 14};
3579  static const int MaskToOptimizeOdd[]  = {1, 9, 3, 11, 5, 13, 7, 15};
3580  bool MatchEvenMask = true;
3581  bool MatchOddMask  = true;
3582  for (int i=0; i<8; ++i) {
3583    if (!isUndefOrEqual(Mask[i], MaskToOptimizeEven[i]))
3584      MatchEvenMask = false;
3585    if (!isUndefOrEqual(Mask[i], MaskToOptimizeOdd[i]))
3586      MatchOddMask = false;
3587  }
3588
3589  if (!MatchEvenMask && !MatchOddMask)
3590    return SDValue();
3591
3592  SDValue UndefNode = DAG.getNode(ISD::UNDEF, dl, VT);
3593
3594  SDValue Op0 = SVOp->getOperand(0);
3595  SDValue Op1 = SVOp->getOperand(1);
3596
3597  if (MatchEvenMask) {
3598    // Shift the second operand right to 32 bits.
3599    static const int ShiftRightMask[] = {-1, 0, -1, 2, -1, 4, -1, 6 };
3600    Op1 = DAG.getVectorShuffle(VT, dl, Op1, UndefNode, ShiftRightMask);
3601  } else {
3602    // Shift the first operand left to 32 bits.
3603    static const int ShiftLeftMask[] = {1, -1, 3, -1, 5, -1, 7, -1 };
3604    Op0 = DAG.getVectorShuffle(VT, dl, Op0, UndefNode, ShiftLeftMask);
3605  }
3606  static const int BlendMask[] = {0, 9, 2, 11, 4, 13, 6, 15};
3607  return DAG.getVectorShuffle(VT, dl, Op0, Op1, BlendMask);
3608}
3609
3610/// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
3611/// specifies a shuffle of elements that is suitable for input to UNPCKL.
3612static bool isUNPCKLMask(ArrayRef<int> Mask, EVT VT,
3613                         bool HasAVX2, bool V2IsSplat = false) {
3614  unsigned NumElts = VT.getVectorNumElements();
3615
3616  assert((VT.is128BitVector() || VT.is256BitVector()) &&
3617         "Unsupported vector type for unpckh");
3618
3619  if (VT.getSizeInBits() == 256 && NumElts != 4 && NumElts != 8 &&
3620      (!HasAVX2 || (NumElts != 16 && NumElts != 32)))
3621    return false;
3622
3623  // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3624  // independently on 128-bit lanes.
3625  unsigned NumLanes = VT.getSizeInBits()/128;
3626  unsigned NumLaneElts = NumElts/NumLanes;
3627
3628  for (unsigned l = 0; l != NumLanes; ++l) {
3629    for (unsigned i = l*NumLaneElts, j = l*NumLaneElts;
3630         i != (l+1)*NumLaneElts;
3631         i += 2, ++j) {
3632      int BitI  = Mask[i];
3633      int BitI1 = Mask[i+1];
3634      if (!isUndefOrEqual(BitI, j))
3635        return false;
3636      if (V2IsSplat) {
3637        if (!isUndefOrEqual(BitI1, NumElts))
3638          return false;
3639      } else {
3640        if (!isUndefOrEqual(BitI1, j + NumElts))
3641          return false;
3642      }
3643    }
3644  }
3645
3646  return true;
3647}
3648
3649/// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
3650/// specifies a shuffle of elements that is suitable for input to UNPCKH.
3651static bool isUNPCKHMask(ArrayRef<int> Mask, EVT VT,
3652                         bool HasAVX2, bool V2IsSplat = false) {
3653  unsigned NumElts = VT.getVectorNumElements();
3654
3655  assert((VT.is128BitVector() || VT.is256BitVector()) &&
3656         "Unsupported vector type for unpckh");
3657
3658  if (VT.getSizeInBits() == 256 && NumElts != 4 && NumElts != 8 &&
3659      (!HasAVX2 || (NumElts != 16 && NumElts != 32)))
3660    return false;
3661
3662  // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3663  // independently on 128-bit lanes.
3664  unsigned NumLanes = VT.getSizeInBits()/128;
3665  unsigned NumLaneElts = NumElts/NumLanes;
3666
3667  for (unsigned l = 0; l != NumLanes; ++l) {
3668    for (unsigned i = l*NumLaneElts, j = (l*NumLaneElts)+NumLaneElts/2;
3669         i != (l+1)*NumLaneElts; i += 2, ++j) {
3670      int BitI  = Mask[i];
3671      int BitI1 = Mask[i+1];
3672      if (!isUndefOrEqual(BitI, j))
3673        return false;
3674      if (V2IsSplat) {
3675        if (isUndefOrEqual(BitI1, NumElts))
3676          return false;
3677      } else {
3678        if (!isUndefOrEqual(BitI1, j+NumElts))
3679          return false;
3680      }
3681    }
3682  }
3683  return true;
3684}
3685
3686/// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
3687/// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
3688/// <0, 0, 1, 1>
3689static bool isUNPCKL_v_undef_Mask(ArrayRef<int> Mask, EVT VT,
3690                                  bool HasAVX2) {
3691  unsigned NumElts = VT.getVectorNumElements();
3692
3693  assert((VT.is128BitVector() || VT.is256BitVector()) &&
3694         "Unsupported vector type for unpckh");
3695
3696  if (VT.getSizeInBits() == 256 && NumElts != 4 && NumElts != 8 &&
3697      (!HasAVX2 || (NumElts != 16 && NumElts != 32)))
3698    return false;
3699
3700  // For 256-bit i64/f64, use MOVDDUPY instead, so reject the matching pattern
3701  // FIXME: Need a better way to get rid of this, there's no latency difference
3702  // between UNPCKLPD and MOVDDUP, the later should always be checked first and
3703  // the former later. We should also remove the "_undef" special mask.
3704  if (NumElts == 4 && VT.getSizeInBits() == 256)
3705    return false;
3706
3707  // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3708  // independently on 128-bit lanes.
3709  unsigned NumLanes = VT.getSizeInBits()/128;
3710  unsigned NumLaneElts = NumElts/NumLanes;
3711
3712  for (unsigned l = 0; l != NumLanes; ++l) {
3713    for (unsigned i = l*NumLaneElts, j = l*NumLaneElts;
3714         i != (l+1)*NumLaneElts;
3715         i += 2, ++j) {
3716      int BitI  = Mask[i];
3717      int BitI1 = Mask[i+1];
3718
3719      if (!isUndefOrEqual(BitI, j))
3720        return false;
3721      if (!isUndefOrEqual(BitI1, j))
3722        return false;
3723    }
3724  }
3725
3726  return true;
3727}
3728
3729/// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
3730/// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
3731/// <2, 2, 3, 3>
3732static bool isUNPCKH_v_undef_Mask(ArrayRef<int> Mask, EVT VT, bool HasAVX2) {
3733  unsigned NumElts = VT.getVectorNumElements();
3734
3735  assert((VT.is128BitVector() || VT.is256BitVector()) &&
3736         "Unsupported vector type for unpckh");
3737
3738  if (VT.getSizeInBits() == 256 && NumElts != 4 && NumElts != 8 &&
3739      (!HasAVX2 || (NumElts != 16 && NumElts != 32)))
3740    return false;
3741
3742  // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3743  // independently on 128-bit lanes.
3744  unsigned NumLanes = VT.getSizeInBits()/128;
3745  unsigned NumLaneElts = NumElts/NumLanes;
3746
3747  for (unsigned l = 0; l != NumLanes; ++l) {
3748    for (unsigned i = l*NumLaneElts, j = (l*NumLaneElts)+NumLaneElts/2;
3749         i != (l+1)*NumLaneElts; i += 2, ++j) {
3750      int BitI  = Mask[i];
3751      int BitI1 = Mask[i+1];
3752      if (!isUndefOrEqual(BitI, j))
3753        return false;
3754      if (!isUndefOrEqual(BitI1, j))
3755        return false;
3756    }
3757  }
3758  return true;
3759}
3760
3761/// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
3762/// specifies a shuffle of elements that is suitable for input to MOVSS,
3763/// MOVSD, and MOVD, i.e. setting the lowest element.
3764static bool isMOVLMask(ArrayRef<int> Mask, EVT VT) {
3765  if (VT.getVectorElementType().getSizeInBits() < 32)
3766    return false;
3767  if (!VT.is128BitVector())
3768    return false;
3769
3770  unsigned NumElts = VT.getVectorNumElements();
3771
3772  if (!isUndefOrEqual(Mask[0], NumElts))
3773    return false;
3774
3775  for (unsigned i = 1; i != NumElts; ++i)
3776    if (!isUndefOrEqual(Mask[i], i))
3777      return false;
3778
3779  return true;
3780}
3781
3782/// isVPERM2X128Mask - Match 256-bit shuffles where the elements are considered
3783/// as permutations between 128-bit chunks or halves. As an example: this
3784/// shuffle bellow:
3785///   vector_shuffle <4, 5, 6, 7, 12, 13, 14, 15>
3786/// The first half comes from the second half of V1 and the second half from the
3787/// the second half of V2.
3788static bool isVPERM2X128Mask(ArrayRef<int> Mask, EVT VT, bool HasAVX) {
3789  if (!HasAVX || !VT.is256BitVector())
3790    return false;
3791
3792  // The shuffle result is divided into half A and half B. In total the two
3793  // sources have 4 halves, namely: C, D, E, F. The final values of A and
3794  // B must come from C, D, E or F.
3795  unsigned HalfSize = VT.getVectorNumElements()/2;
3796  bool MatchA = false, MatchB = false;
3797
3798  // Check if A comes from one of C, D, E, F.
3799  for (unsigned Half = 0; Half != 4; ++Half) {
3800    if (isSequentialOrUndefInRange(Mask, 0, HalfSize, Half*HalfSize)) {
3801      MatchA = true;
3802      break;
3803    }
3804  }
3805
3806  // Check if B comes from one of C, D, E, F.
3807  for (unsigned Half = 0; Half != 4; ++Half) {
3808    if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, Half*HalfSize)) {
3809      MatchB = true;
3810      break;
3811    }
3812  }
3813
3814  return MatchA && MatchB;
3815}
3816
3817/// getShuffleVPERM2X128Immediate - Return the appropriate immediate to shuffle
3818/// the specified VECTOR_MASK mask with VPERM2F128/VPERM2I128 instructions.
3819static unsigned getShuffleVPERM2X128Immediate(ShuffleVectorSDNode *SVOp) {
3820  EVT VT = SVOp->getValueType(0);
3821
3822  unsigned HalfSize = VT.getVectorNumElements()/2;
3823
3824  unsigned FstHalf = 0, SndHalf = 0;
3825  for (unsigned i = 0; i < HalfSize; ++i) {
3826    if (SVOp->getMaskElt(i) > 0) {
3827      FstHalf = SVOp->getMaskElt(i)/HalfSize;
3828      break;
3829    }
3830  }
3831  for (unsigned i = HalfSize; i < HalfSize*2; ++i) {
3832    if (SVOp->getMaskElt(i) > 0) {
3833      SndHalf = SVOp->getMaskElt(i)/HalfSize;
3834      break;
3835    }
3836  }
3837
3838  return (FstHalf | (SndHalf << 4));
3839}
3840
3841/// isVPERMILPMask - Return true if the specified VECTOR_SHUFFLE operand
3842/// specifies a shuffle of elements that is suitable for input to VPERMILPD*.
3843/// Note that VPERMIL mask matching is different depending whether theunderlying
3844/// type is 32 or 64. In the VPERMILPS the high half of the mask should point
3845/// to the same elements of the low, but to the higher half of the source.
3846/// In VPERMILPD the two lanes could be shuffled independently of each other
3847/// with the same restriction that lanes can't be crossed. Also handles PSHUFDY.
3848static bool isVPERMILPMask(ArrayRef<int> Mask, EVT VT, bool HasAVX) {
3849  if (!HasAVX)
3850    return false;
3851
3852  unsigned NumElts = VT.getVectorNumElements();
3853  // Only match 256-bit with 32/64-bit types
3854  if (VT.getSizeInBits() != 256 || (NumElts != 4 && NumElts != 8))
3855    return false;
3856
3857  unsigned NumLanes = VT.getSizeInBits()/128;
3858  unsigned LaneSize = NumElts/NumLanes;
3859  for (unsigned l = 0; l != NumElts; l += LaneSize) {
3860    for (unsigned i = 0; i != LaneSize; ++i) {
3861      if (!isUndefOrInRange(Mask[i+l], l, l+LaneSize))
3862        return false;
3863      if (NumElts != 8 || l == 0)
3864        continue;
3865      // VPERMILPS handling
3866      if (Mask[i] < 0)
3867        continue;
3868      if (!isUndefOrEqual(Mask[i+l], Mask[i]+l))
3869        return false;
3870    }
3871  }
3872
3873  return true;
3874}
3875
3876/// isCommutedMOVLMask - Returns true if the shuffle mask is except the reverse
3877/// of what x86 movss want. X86 movs requires the lowest  element to be lowest
3878/// element of vector 2 and the other elements to come from vector 1 in order.
3879static bool isCommutedMOVLMask(ArrayRef<int> Mask, EVT VT,
3880                               bool V2IsSplat = false, bool V2IsUndef = false) {
3881  if (!VT.is128BitVector())
3882    return false;
3883
3884  unsigned NumOps = VT.getVectorNumElements();
3885  if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
3886    return false;
3887
3888  if (!isUndefOrEqual(Mask[0], 0))
3889    return false;
3890
3891  for (unsigned i = 1; i != NumOps; ++i)
3892    if (!(isUndefOrEqual(Mask[i], i+NumOps) ||
3893          (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) ||
3894          (V2IsSplat && isUndefOrEqual(Mask[i], NumOps))))
3895      return false;
3896
3897  return true;
3898}
3899
3900/// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3901/// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
3902/// Masks to match: <1, 1, 3, 3> or <1, 1, 3, 3, 5, 5, 7, 7>
3903static bool isMOVSHDUPMask(ArrayRef<int> Mask, EVT VT,
3904                           const X86Subtarget *Subtarget) {
3905  if (!Subtarget->hasSSE3())
3906    return false;
3907
3908  unsigned NumElems = VT.getVectorNumElements();
3909
3910  if ((VT.getSizeInBits() == 128 && NumElems != 4) ||
3911      (VT.getSizeInBits() == 256 && NumElems != 8))
3912    return false;
3913
3914  // "i+1" is the value the indexed mask element must have
3915  for (unsigned i = 0; i != NumElems; i += 2)
3916    if (!isUndefOrEqual(Mask[i], i+1) ||
3917        !isUndefOrEqual(Mask[i+1], i+1))
3918      return false;
3919
3920  return true;
3921}
3922
3923/// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3924/// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
3925/// Masks to match: <0, 0, 2, 2> or <0, 0, 2, 2, 4, 4, 6, 6>
3926static bool isMOVSLDUPMask(ArrayRef<int> Mask, EVT VT,
3927                           const X86Subtarget *Subtarget) {
3928  if (!Subtarget->hasSSE3())
3929    return false;
3930
3931  unsigned NumElems = VT.getVectorNumElements();
3932
3933  if ((VT.getSizeInBits() == 128 && NumElems != 4) ||
3934      (VT.getSizeInBits() == 256 && NumElems != 8))
3935    return false;
3936
3937  // "i" is the value the indexed mask element must have
3938  for (unsigned i = 0; i != NumElems; i += 2)
3939    if (!isUndefOrEqual(Mask[i], i) ||
3940        !isUndefOrEqual(Mask[i+1], i))
3941      return false;
3942
3943  return true;
3944}
3945
3946/// isMOVDDUPYMask - Return true if the specified VECTOR_SHUFFLE operand
3947/// specifies a shuffle of elements that is suitable for input to 256-bit
3948/// version of MOVDDUP.
3949static bool isMOVDDUPYMask(ArrayRef<int> Mask, EVT VT, bool HasAVX) {
3950  if (!HasAVX || !VT.is256BitVector())
3951    return false;
3952
3953  unsigned NumElts = VT.getVectorNumElements();
3954  if (NumElts != 4)
3955    return false;
3956
3957  for (unsigned i = 0; i != NumElts/2; ++i)
3958    if (!isUndefOrEqual(Mask[i], 0))
3959      return false;
3960  for (unsigned i = NumElts/2; i != NumElts; ++i)
3961    if (!isUndefOrEqual(Mask[i], NumElts/2))
3962      return false;
3963  return true;
3964}
3965
3966/// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3967/// specifies a shuffle of elements that is suitable for input to 128-bit
3968/// version of MOVDDUP.
3969static bool isMOVDDUPMask(ArrayRef<int> Mask, EVT VT) {
3970  if (!VT.is128BitVector())
3971    return false;
3972
3973  unsigned e = VT.getVectorNumElements() / 2;
3974  for (unsigned i = 0; i != e; ++i)
3975    if (!isUndefOrEqual(Mask[i], i))
3976      return false;
3977  for (unsigned i = 0; i != e; ++i)
3978    if (!isUndefOrEqual(Mask[e+i], i))
3979      return false;
3980  return true;
3981}
3982
3983/// isVEXTRACTF128Index - Return true if the specified
3984/// EXTRACT_SUBVECTOR operand specifies a vector extract that is
3985/// suitable for input to VEXTRACTF128.
3986bool X86::isVEXTRACTF128Index(SDNode *N) {
3987  if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
3988    return false;
3989
3990  // The index should be aligned on a 128-bit boundary.
3991  uint64_t Index =
3992    cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
3993
3994  unsigned VL = N->getValueType(0).getVectorNumElements();
3995  unsigned VBits = N->getValueType(0).getSizeInBits();
3996  unsigned ElSize = VBits / VL;
3997  bool Result = (Index * ElSize) % 128 == 0;
3998
3999  return Result;
4000}
4001
4002/// isVINSERTF128Index - Return true if the specified INSERT_SUBVECTOR
4003/// operand specifies a subvector insert that is suitable for input to
4004/// VINSERTF128.
4005bool X86::isVINSERTF128Index(SDNode *N) {
4006  if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4007    return false;
4008
4009  // The index should be aligned on a 128-bit boundary.
4010  uint64_t Index =
4011    cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4012
4013  unsigned VL = N->getValueType(0).getVectorNumElements();
4014  unsigned VBits = N->getValueType(0).getSizeInBits();
4015  unsigned ElSize = VBits / VL;
4016  bool Result = (Index * ElSize) % 128 == 0;
4017
4018  return Result;
4019}
4020
4021/// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
4022/// the specified VECTOR_SHUFFLE mask with PSHUF* and SHUFP* instructions.
4023/// Handles 128-bit and 256-bit.
4024static unsigned getShuffleSHUFImmediate(ShuffleVectorSDNode *N) {
4025  EVT VT = N->getValueType(0);
4026
4027  assert((VT.is128BitVector() || VT.is256BitVector()) &&
4028         "Unsupported vector type for PSHUF/SHUFP");
4029
4030  // Handle 128 and 256-bit vector lengths. AVX defines PSHUF/SHUFP to operate
4031  // independently on 128-bit lanes.
4032  unsigned NumElts = VT.getVectorNumElements();
4033  unsigned NumLanes = VT.getSizeInBits()/128;
4034  unsigned NumLaneElts = NumElts/NumLanes;
4035
4036  assert((NumLaneElts == 2 || NumLaneElts == 4) &&
4037         "Only supports 2 or 4 elements per lane");
4038
4039  unsigned Shift = (NumLaneElts == 4) ? 1 : 0;
4040  unsigned Mask = 0;
4041  for (unsigned i = 0; i != NumElts; ++i) {
4042    int Elt = N->getMaskElt(i);
4043    if (Elt < 0) continue;
4044    Elt &= NumLaneElts - 1;
4045    unsigned ShAmt = (i << Shift) % 8;
4046    Mask |= Elt << ShAmt;
4047  }
4048
4049  return Mask;
4050}
4051
4052/// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
4053/// the specified VECTOR_SHUFFLE mask with the PSHUFHW instruction.
4054static unsigned getShufflePSHUFHWImmediate(ShuffleVectorSDNode *N) {
4055  EVT VT = N->getValueType(0);
4056
4057  assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4058         "Unsupported vector type for PSHUFHW");
4059
4060  unsigned NumElts = VT.getVectorNumElements();
4061
4062  unsigned Mask = 0;
4063  for (unsigned l = 0; l != NumElts; l += 8) {
4064    // 8 nodes per lane, but we only care about the last 4.
4065    for (unsigned i = 0; i < 4; ++i) {
4066      int Elt = N->getMaskElt(l+i+4);
4067      if (Elt < 0) continue;
4068      Elt &= 0x3; // only 2-bits.
4069      Mask |= Elt << (i * 2);
4070    }
4071  }
4072
4073  return Mask;
4074}
4075
4076/// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
4077/// the specified VECTOR_SHUFFLE mask with the PSHUFLW instruction.
4078static unsigned getShufflePSHUFLWImmediate(ShuffleVectorSDNode *N) {
4079  EVT VT = N->getValueType(0);
4080
4081  assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4082         "Unsupported vector type for PSHUFHW");
4083
4084  unsigned NumElts = VT.getVectorNumElements();
4085
4086  unsigned Mask = 0;
4087  for (unsigned l = 0; l != NumElts; l += 8) {
4088    // 8 nodes per lane, but we only care about the first 4.
4089    for (unsigned i = 0; i < 4; ++i) {
4090      int Elt = N->getMaskElt(l+i);
4091      if (Elt < 0) continue;
4092      Elt &= 0x3; // only 2-bits
4093      Mask |= Elt << (i * 2);
4094    }
4095  }
4096
4097  return Mask;
4098}
4099
4100/// getShufflePALIGNRImmediate - Return the appropriate immediate to shuffle
4101/// the specified VECTOR_SHUFFLE mask with the PALIGNR instruction.
4102static unsigned getShufflePALIGNRImmediate(ShuffleVectorSDNode *SVOp) {
4103  EVT VT = SVOp->getValueType(0);
4104  unsigned EltSize = VT.getVectorElementType().getSizeInBits() >> 3;
4105
4106  unsigned NumElts = VT.getVectorNumElements();
4107  unsigned NumLanes = VT.getSizeInBits()/128;
4108  unsigned NumLaneElts = NumElts/NumLanes;
4109
4110  int Val = 0;
4111  unsigned i;
4112  for (i = 0; i != NumElts; ++i) {
4113    Val = SVOp->getMaskElt(i);
4114    if (Val >= 0)
4115      break;
4116  }
4117  if (Val >= (int)NumElts)
4118    Val -= NumElts - NumLaneElts;
4119
4120  assert(Val - i > 0 && "PALIGNR imm should be positive");
4121  return (Val - i) * EltSize;
4122}
4123
4124/// getExtractVEXTRACTF128Immediate - Return the appropriate immediate
4125/// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF128
4126/// instructions.
4127unsigned X86::getExtractVEXTRACTF128Immediate(SDNode *N) {
4128  if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4129    llvm_unreachable("Illegal extract subvector for VEXTRACTF128");
4130
4131  uint64_t Index =
4132    cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4133
4134  EVT VecVT = N->getOperand(0).getValueType();
4135  EVT ElVT = VecVT.getVectorElementType();
4136
4137  unsigned NumElemsPerChunk = 128 / ElVT.getSizeInBits();
4138  return Index / NumElemsPerChunk;
4139}
4140
4141/// getInsertVINSERTF128Immediate - Return the appropriate immediate
4142/// to insert at the specified INSERT_SUBVECTOR index with VINSERTF128
4143/// instructions.
4144unsigned X86::getInsertVINSERTF128Immediate(SDNode *N) {
4145  if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4146    llvm_unreachable("Illegal insert subvector for VINSERTF128");
4147
4148  uint64_t Index =
4149    cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4150
4151  EVT VecVT = N->getValueType(0);
4152  EVT ElVT = VecVT.getVectorElementType();
4153
4154  unsigned NumElemsPerChunk = 128 / ElVT.getSizeInBits();
4155  return Index / NumElemsPerChunk;
4156}
4157
4158/// getShuffleCLImmediate - Return the appropriate immediate to shuffle
4159/// the specified VECTOR_SHUFFLE mask with VPERMQ and VPERMPD instructions.
4160/// Handles 256-bit.
4161static unsigned getShuffleCLImmediate(ShuffleVectorSDNode *N) {
4162  EVT VT = N->getValueType(0);
4163
4164  unsigned NumElts = VT.getVectorNumElements();
4165
4166  assert((VT.is256BitVector() && NumElts == 4) &&
4167         "Unsupported vector type for VPERMQ/VPERMPD");
4168
4169  unsigned Mask = 0;
4170  for (unsigned i = 0; i != NumElts; ++i) {
4171    int Elt = N->getMaskElt(i);
4172    if (Elt < 0)
4173      continue;
4174    Mask |= Elt << (i*2);
4175  }
4176
4177  return Mask;
4178}
4179/// isZeroNode - Returns true if Elt is a constant zero or a floating point
4180/// constant +0.0.
4181bool X86::isZeroNode(SDValue Elt) {
4182  return ((isa<ConstantSDNode>(Elt) &&
4183           cast<ConstantSDNode>(Elt)->isNullValue()) ||
4184          (isa<ConstantFPSDNode>(Elt) &&
4185           cast<ConstantFPSDNode>(Elt)->getValueAPF().isPosZero()));
4186}
4187
4188/// CommuteVectorShuffle - Swap vector_shuffle operands as well as values in
4189/// their permute mask.
4190static SDValue CommuteVectorShuffle(ShuffleVectorSDNode *SVOp,
4191                                    SelectionDAG &DAG) {
4192  EVT VT = SVOp->getValueType(0);
4193  unsigned NumElems = VT.getVectorNumElements();
4194  SmallVector<int, 8> MaskVec;
4195
4196  for (unsigned i = 0; i != NumElems; ++i) {
4197    int Idx = SVOp->getMaskElt(i);
4198    if (Idx >= 0) {
4199      if (Idx < (int)NumElems)
4200        Idx += NumElems;
4201      else
4202        Idx -= NumElems;
4203    }
4204    MaskVec.push_back(Idx);
4205  }
4206  return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(1),
4207                              SVOp->getOperand(0), &MaskVec[0]);
4208}
4209
4210/// ShouldXformToMOVHLPS - Return true if the node should be transformed to
4211/// match movhlps. The lower half elements should come from upper half of
4212/// V1 (and in order), and the upper half elements should come from the upper
4213/// half of V2 (and in order).
4214static bool ShouldXformToMOVHLPS(ArrayRef<int> Mask, EVT VT) {
4215  if (!VT.is128BitVector())
4216    return false;
4217  if (VT.getVectorNumElements() != 4)
4218    return false;
4219  for (unsigned i = 0, e = 2; i != e; ++i)
4220    if (!isUndefOrEqual(Mask[i], i+2))
4221      return false;
4222  for (unsigned i = 2; i != 4; ++i)
4223    if (!isUndefOrEqual(Mask[i], i+4))
4224      return false;
4225  return true;
4226}
4227
4228/// isScalarLoadToVector - Returns true if the node is a scalar load that
4229/// is promoted to a vector. It also returns the LoadSDNode by reference if
4230/// required.
4231static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = NULL) {
4232  if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
4233    return false;
4234  N = N->getOperand(0).getNode();
4235  if (!ISD::isNON_EXTLoad(N))
4236    return false;
4237  if (LD)
4238    *LD = cast<LoadSDNode>(N);
4239  return true;
4240}
4241
4242// Test whether the given value is a vector value which will be legalized
4243// into a load.
4244static bool WillBeConstantPoolLoad(SDNode *N) {
4245  if (N->getOpcode() != ISD::BUILD_VECTOR)
4246    return false;
4247
4248  // Check for any non-constant elements.
4249  for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
4250    switch (N->getOperand(i).getNode()->getOpcode()) {
4251    case ISD::UNDEF:
4252    case ISD::ConstantFP:
4253    case ISD::Constant:
4254      break;
4255    default:
4256      return false;
4257    }
4258
4259  // Vectors of all-zeros and all-ones are materialized with special
4260  // instructions rather than being loaded.
4261  return !ISD::isBuildVectorAllZeros(N) &&
4262         !ISD::isBuildVectorAllOnes(N);
4263}
4264
4265/// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
4266/// match movlp{s|d}. The lower half elements should come from lower half of
4267/// V1 (and in order), and the upper half elements should come from the upper
4268/// half of V2 (and in order). And since V1 will become the source of the
4269/// MOVLP, it must be either a vector load or a scalar load to vector.
4270static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2,
4271                               ArrayRef<int> Mask, EVT VT) {
4272  if (!VT.is128BitVector())
4273    return false;
4274
4275  if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
4276    return false;
4277  // Is V2 is a vector load, don't do this transformation. We will try to use
4278  // load folding shufps op.
4279  if (ISD::isNON_EXTLoad(V2) || WillBeConstantPoolLoad(V2))
4280    return false;
4281
4282  unsigned NumElems = VT.getVectorNumElements();
4283
4284  if (NumElems != 2 && NumElems != 4)
4285    return false;
4286  for (unsigned i = 0, e = NumElems/2; i != e; ++i)
4287    if (!isUndefOrEqual(Mask[i], i))
4288      return false;
4289  for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
4290    if (!isUndefOrEqual(Mask[i], i+NumElems))
4291      return false;
4292  return true;
4293}
4294
4295/// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
4296/// all the same.
4297static bool isSplatVector(SDNode *N) {
4298  if (N->getOpcode() != ISD::BUILD_VECTOR)
4299    return false;
4300
4301  SDValue SplatValue = N->getOperand(0);
4302  for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
4303    if (N->getOperand(i) != SplatValue)
4304      return false;
4305  return true;
4306}
4307
4308/// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
4309/// to an zero vector.
4310/// FIXME: move to dag combiner / method on ShuffleVectorSDNode
4311static bool isZeroShuffle(ShuffleVectorSDNode *N) {
4312  SDValue V1 = N->getOperand(0);
4313  SDValue V2 = N->getOperand(1);
4314  unsigned NumElems = N->getValueType(0).getVectorNumElements();
4315  for (unsigned i = 0; i != NumElems; ++i) {
4316    int Idx = N->getMaskElt(i);
4317    if (Idx >= (int)NumElems) {
4318      unsigned Opc = V2.getOpcode();
4319      if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
4320        continue;
4321      if (Opc != ISD::BUILD_VECTOR ||
4322          !X86::isZeroNode(V2.getOperand(Idx-NumElems)))
4323        return false;
4324    } else if (Idx >= 0) {
4325      unsigned Opc = V1.getOpcode();
4326      if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
4327        continue;
4328      if (Opc != ISD::BUILD_VECTOR ||
4329          !X86::isZeroNode(V1.getOperand(Idx)))
4330        return false;
4331    }
4332  }
4333  return true;
4334}
4335
4336/// getZeroVector - Returns a vector of specified type with all zero elements.
4337///
4338static SDValue getZeroVector(EVT VT, const X86Subtarget *Subtarget,
4339                             SelectionDAG &DAG, DebugLoc dl) {
4340  assert(VT.isVector() && "Expected a vector type");
4341  unsigned Size = VT.getSizeInBits();
4342
4343  // Always build SSE zero vectors as <4 x i32> bitcasted
4344  // to their dest type. This ensures they get CSE'd.
4345  SDValue Vec;
4346  if (Size == 128) {  // SSE
4347    if (Subtarget->hasSSE2()) {  // SSE2
4348      SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4349      Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4350    } else { // SSE1
4351      SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4352      Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
4353    }
4354  } else if (Size == 256) { // AVX
4355    if (Subtarget->hasAVX2()) { // AVX2
4356      SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4357      SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4358      Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops, 8);
4359    } else {
4360      // 256-bit logic and arithmetic instructions in AVX are all
4361      // floating-point, no support for integer ops. Emit fp zeroed vectors.
4362      SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4363      SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4364      Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops, 8);
4365    }
4366  } else
4367    llvm_unreachable("Unexpected vector type");
4368
4369  return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4370}
4371
4372/// getOnesVector - Returns a vector of specified type with all bits set.
4373/// Always build ones vectors as <4 x i32> or <8 x i32>. For 256-bit types with
4374/// no AVX2 supprt, use two <4 x i32> inserted in a <8 x i32> appropriately.
4375/// Then bitcast to their original type, ensuring they get CSE'd.
4376static SDValue getOnesVector(EVT VT, bool HasAVX2, SelectionDAG &DAG,
4377                             DebugLoc dl) {
4378  assert(VT.isVector() && "Expected a vector type");
4379  unsigned Size = VT.getSizeInBits();
4380
4381  SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
4382  SDValue Vec;
4383  if (Size == 256) {
4384    if (HasAVX2) { // AVX2
4385      SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4386      Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops, 8);
4387    } else { // AVX
4388      Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4389      Vec = Concat128BitVectors(Vec, Vec, MVT::v8i32, 8, DAG, dl);
4390    }
4391  } else if (Size == 128) {
4392    Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4393  } else
4394    llvm_unreachable("Unexpected vector type");
4395
4396  return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4397}
4398
4399/// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
4400/// that point to V2 points to its first element.
4401static void NormalizeMask(SmallVectorImpl<int> &Mask, unsigned NumElems) {
4402  for (unsigned i = 0; i != NumElems; ++i) {
4403    if (Mask[i] > (int)NumElems) {
4404      Mask[i] = NumElems;
4405    }
4406  }
4407}
4408
4409/// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
4410/// operation of specified width.
4411static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
4412                       SDValue V2) {
4413  unsigned NumElems = VT.getVectorNumElements();
4414  SmallVector<int, 8> Mask;
4415  Mask.push_back(NumElems);
4416  for (unsigned i = 1; i != NumElems; ++i)
4417    Mask.push_back(i);
4418  return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4419}
4420
4421/// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
4422static SDValue getUnpackl(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
4423                          SDValue V2) {
4424  unsigned NumElems = VT.getVectorNumElements();
4425  SmallVector<int, 8> Mask;
4426  for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
4427    Mask.push_back(i);
4428    Mask.push_back(i + NumElems);
4429  }
4430  return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4431}
4432
4433/// getUnpackh - Returns a vector_shuffle node for an unpackh operation.
4434static SDValue getUnpackh(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
4435                          SDValue V2) {
4436  unsigned NumElems = VT.getVectorNumElements();
4437  SmallVector<int, 8> Mask;
4438  for (unsigned i = 0, Half = NumElems/2; i != Half; ++i) {
4439    Mask.push_back(i + Half);
4440    Mask.push_back(i + NumElems + Half);
4441  }
4442  return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4443}
4444
4445// PromoteSplati8i16 - All i16 and i8 vector types can't be used directly by
4446// a generic shuffle instruction because the target has no such instructions.
4447// Generate shuffles which repeat i16 and i8 several times until they can be
4448// represented by v4f32 and then be manipulated by target suported shuffles.
4449static SDValue PromoteSplati8i16(SDValue V, SelectionDAG &DAG, int &EltNo) {
4450  EVT VT = V.getValueType();
4451  int NumElems = VT.getVectorNumElements();
4452  DebugLoc dl = V.getDebugLoc();
4453
4454  while (NumElems > 4) {
4455    if (EltNo < NumElems/2) {
4456      V = getUnpackl(DAG, dl, VT, V, V);
4457    } else {
4458      V = getUnpackh(DAG, dl, VT, V, V);
4459      EltNo -= NumElems/2;
4460    }
4461    NumElems >>= 1;
4462  }
4463  return V;
4464}
4465
4466/// getLegalSplat - Generate a legal splat with supported x86 shuffles
4467static SDValue getLegalSplat(SelectionDAG &DAG, SDValue V, int EltNo) {
4468  EVT VT = V.getValueType();
4469  DebugLoc dl = V.getDebugLoc();
4470  unsigned Size = VT.getSizeInBits();
4471
4472  if (Size == 128) {
4473    V = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V);
4474    int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo };
4475    V = DAG.getVectorShuffle(MVT::v4f32, dl, V, DAG.getUNDEF(MVT::v4f32),
4476                             &SplatMask[0]);
4477  } else if (Size == 256) {
4478    // To use VPERMILPS to splat scalars, the second half of indicies must
4479    // refer to the higher part, which is a duplication of the lower one,
4480    // because VPERMILPS can only handle in-lane permutations.
4481    int SplatMask[8] = { EltNo, EltNo, EltNo, EltNo,
4482                         EltNo+4, EltNo+4, EltNo+4, EltNo+4 };
4483
4484    V = DAG.getNode(ISD::BITCAST, dl, MVT::v8f32, V);
4485    V = DAG.getVectorShuffle(MVT::v8f32, dl, V, DAG.getUNDEF(MVT::v8f32),
4486                             &SplatMask[0]);
4487  } else
4488    llvm_unreachable("Vector size not supported");
4489
4490  return DAG.getNode(ISD::BITCAST, dl, VT, V);
4491}
4492
4493/// PromoteSplat - Splat is promoted to target supported vector shuffles.
4494static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG) {
4495  EVT SrcVT = SV->getValueType(0);
4496  SDValue V1 = SV->getOperand(0);
4497  DebugLoc dl = SV->getDebugLoc();
4498
4499  int EltNo = SV->getSplatIndex();
4500  int NumElems = SrcVT.getVectorNumElements();
4501  unsigned Size = SrcVT.getSizeInBits();
4502
4503  assert(((Size == 128 && NumElems > 4) || Size == 256) &&
4504          "Unknown how to promote splat for type");
4505
4506  // Extract the 128-bit part containing the splat element and update
4507  // the splat element index when it refers to the higher register.
4508  if (Size == 256) {
4509    V1 = Extract128BitVector(V1, EltNo, DAG, dl);
4510    if (EltNo >= NumElems/2)
4511      EltNo -= NumElems/2;
4512  }
4513
4514  // All i16 and i8 vector types can't be used directly by a generic shuffle
4515  // instruction because the target has no such instruction. Generate shuffles
4516  // which repeat i16 and i8 several times until they fit in i32, and then can
4517  // be manipulated by target suported shuffles.
4518  EVT EltVT = SrcVT.getVectorElementType();
4519  if (EltVT == MVT::i8 || EltVT == MVT::i16)
4520    V1 = PromoteSplati8i16(V1, DAG, EltNo);
4521
4522  // Recreate the 256-bit vector and place the same 128-bit vector
4523  // into the low and high part. This is necessary because we want
4524  // to use VPERM* to shuffle the vectors
4525  if (Size == 256) {
4526    V1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, SrcVT, V1, V1);
4527  }
4528
4529  return getLegalSplat(DAG, V1, EltNo);
4530}
4531
4532/// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
4533/// vector of zero or undef vector.  This produces a shuffle where the low
4534/// element of V2 is swizzled into the zero/undef vector, landing at element
4535/// Idx.  This produces a shuffle mask like 4,1,2,3 (idx=0) or  0,1,2,4 (idx=3).
4536static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
4537                                           bool IsZero,
4538                                           const X86Subtarget *Subtarget,
4539                                           SelectionDAG &DAG) {
4540  EVT VT = V2.getValueType();
4541  SDValue V1 = IsZero
4542    ? getZeroVector(VT, Subtarget, DAG, V2.getDebugLoc()) : DAG.getUNDEF(VT);
4543  unsigned NumElems = VT.getVectorNumElements();
4544  SmallVector<int, 16> MaskVec;
4545  for (unsigned i = 0; i != NumElems; ++i)
4546    // If this is the insertion idx, put the low elt of V2 here.
4547    MaskVec.push_back(i == Idx ? NumElems : i);
4548  return DAG.getVectorShuffle(VT, V2.getDebugLoc(), V1, V2, &MaskVec[0]);
4549}
4550
4551/// getTargetShuffleMask - Calculates the shuffle mask corresponding to the
4552/// target specific opcode. Returns true if the Mask could be calculated.
4553/// Sets IsUnary to true if only uses one source.
4554static bool getTargetShuffleMask(SDNode *N, MVT VT,
4555                                 SmallVectorImpl<int> &Mask, bool &IsUnary) {
4556  unsigned NumElems = VT.getVectorNumElements();
4557  SDValue ImmN;
4558
4559  IsUnary = false;
4560  switch(N->getOpcode()) {
4561  case X86ISD::SHUFP:
4562    ImmN = N->getOperand(N->getNumOperands()-1);
4563    DecodeSHUFPMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4564    break;
4565  case X86ISD::UNPCKH:
4566    DecodeUNPCKHMask(VT, Mask);
4567    break;
4568  case X86ISD::UNPCKL:
4569    DecodeUNPCKLMask(VT, Mask);
4570    break;
4571  case X86ISD::MOVHLPS:
4572    DecodeMOVHLPSMask(NumElems, Mask);
4573    break;
4574  case X86ISD::MOVLHPS:
4575    DecodeMOVLHPSMask(NumElems, Mask);
4576    break;
4577  case X86ISD::PSHUFD:
4578  case X86ISD::VPERMILP:
4579    ImmN = N->getOperand(N->getNumOperands()-1);
4580    DecodePSHUFMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4581    IsUnary = true;
4582    break;
4583  case X86ISD::PSHUFHW:
4584    ImmN = N->getOperand(N->getNumOperands()-1);
4585    DecodePSHUFHWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4586    IsUnary = true;
4587    break;
4588  case X86ISD::PSHUFLW:
4589    ImmN = N->getOperand(N->getNumOperands()-1);
4590    DecodePSHUFLWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4591    IsUnary = true;
4592    break;
4593  case X86ISD::VPERMI:
4594    ImmN = N->getOperand(N->getNumOperands()-1);
4595    DecodeVPERMMask(cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4596    IsUnary = true;
4597    break;
4598  case X86ISD::MOVSS:
4599  case X86ISD::MOVSD: {
4600    // The index 0 always comes from the first element of the second source,
4601    // this is why MOVSS and MOVSD are used in the first place. The other
4602    // elements come from the other positions of the first source vector
4603    Mask.push_back(NumElems);
4604    for (unsigned i = 1; i != NumElems; ++i) {
4605      Mask.push_back(i);
4606    }
4607    break;
4608  }
4609  case X86ISD::VPERM2X128:
4610    ImmN = N->getOperand(N->getNumOperands()-1);
4611    DecodeVPERM2X128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4612    if (Mask.empty()) return false;
4613    break;
4614  case X86ISD::MOVDDUP:
4615  case X86ISD::MOVLHPD:
4616  case X86ISD::MOVLPD:
4617  case X86ISD::MOVLPS:
4618  case X86ISD::MOVSHDUP:
4619  case X86ISD::MOVSLDUP:
4620  case X86ISD::PALIGN:
4621    // Not yet implemented
4622    return false;
4623  default: llvm_unreachable("unknown target shuffle node");
4624  }
4625
4626  return true;
4627}
4628
4629/// getShuffleScalarElt - Returns the scalar element that will make up the ith
4630/// element of the result of the vector shuffle.
4631static SDValue getShuffleScalarElt(SDNode *N, unsigned Index, SelectionDAG &DAG,
4632                                   unsigned Depth) {
4633  if (Depth == 6)
4634    return SDValue();  // Limit search depth.
4635
4636  SDValue V = SDValue(N, 0);
4637  EVT VT = V.getValueType();
4638  unsigned Opcode = V.getOpcode();
4639
4640  // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
4641  if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
4642    int Elt = SV->getMaskElt(Index);
4643
4644    if (Elt < 0)
4645      return DAG.getUNDEF(VT.getVectorElementType());
4646
4647    unsigned NumElems = VT.getVectorNumElements();
4648    SDValue NewV = (Elt < (int)NumElems) ? SV->getOperand(0)
4649                                         : SV->getOperand(1);
4650    return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG, Depth+1);
4651  }
4652
4653  // Recurse into target specific vector shuffles to find scalars.
4654  if (isTargetShuffle(Opcode)) {
4655    MVT ShufVT = V.getValueType().getSimpleVT();
4656    unsigned NumElems = ShufVT.getVectorNumElements();
4657    SmallVector<int, 16> ShuffleMask;
4658    bool IsUnary;
4659
4660    if (!getTargetShuffleMask(N, ShufVT, ShuffleMask, IsUnary))
4661      return SDValue();
4662
4663    int Elt = ShuffleMask[Index];
4664    if (Elt < 0)
4665      return DAG.getUNDEF(ShufVT.getVectorElementType());
4666
4667    SDValue NewV = (Elt < (int)NumElems) ? N->getOperand(0)
4668                                         : N->getOperand(1);
4669    return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG,
4670                               Depth+1);
4671  }
4672
4673  // Actual nodes that may contain scalar elements
4674  if (Opcode == ISD::BITCAST) {
4675    V = V.getOperand(0);
4676    EVT SrcVT = V.getValueType();
4677    unsigned NumElems = VT.getVectorNumElements();
4678
4679    if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
4680      return SDValue();
4681  }
4682
4683  if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
4684    return (Index == 0) ? V.getOperand(0)
4685                        : DAG.getUNDEF(VT.getVectorElementType());
4686
4687  if (V.getOpcode() == ISD::BUILD_VECTOR)
4688    return V.getOperand(Index);
4689
4690  return SDValue();
4691}
4692
4693/// getNumOfConsecutiveZeros - Return the number of elements of a vector
4694/// shuffle operation which come from a consecutively from a zero. The
4695/// search can start in two different directions, from left or right.
4696static
4697unsigned getNumOfConsecutiveZeros(ShuffleVectorSDNode *SVOp, unsigned NumElems,
4698                                  bool ZerosFromLeft, SelectionDAG &DAG) {
4699  unsigned i;
4700  for (i = 0; i != NumElems; ++i) {
4701    unsigned Index = ZerosFromLeft ? i : NumElems-i-1;
4702    SDValue Elt = getShuffleScalarElt(SVOp, Index, DAG, 0);
4703    if (!(Elt.getNode() &&
4704         (Elt.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elt))))
4705      break;
4706  }
4707
4708  return i;
4709}
4710
4711/// isShuffleMaskConsecutive - Check if the shuffle mask indicies [MaskI, MaskE)
4712/// correspond consecutively to elements from one of the vector operands,
4713/// starting from its index OpIdx. Also tell OpNum which source vector operand.
4714static
4715bool isShuffleMaskConsecutive(ShuffleVectorSDNode *SVOp,
4716                              unsigned MaskI, unsigned MaskE, unsigned OpIdx,
4717                              unsigned NumElems, unsigned &OpNum) {
4718  bool SeenV1 = false;
4719  bool SeenV2 = false;
4720
4721  for (unsigned i = MaskI; i != MaskE; ++i, ++OpIdx) {
4722    int Idx = SVOp->getMaskElt(i);
4723    // Ignore undef indicies
4724    if (Idx < 0)
4725      continue;
4726
4727    if (Idx < (int)NumElems)
4728      SeenV1 = true;
4729    else
4730      SeenV2 = true;
4731
4732    // Only accept consecutive elements from the same vector
4733    if ((Idx % NumElems != OpIdx) || (SeenV1 && SeenV2))
4734      return false;
4735  }
4736
4737  OpNum = SeenV1 ? 0 : 1;
4738  return true;
4739}
4740
4741/// isVectorShiftRight - Returns true if the shuffle can be implemented as a
4742/// logical left shift of a vector.
4743static bool isVectorShiftRight(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4744                               bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4745  unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
4746  unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems,
4747              false /* check zeros from right */, DAG);
4748  unsigned OpSrc;
4749
4750  if (!NumZeros)
4751    return false;
4752
4753  // Considering the elements in the mask that are not consecutive zeros,
4754  // check if they consecutively come from only one of the source vectors.
4755  //
4756  //               V1 = {X, A, B, C}     0
4757  //                         \  \  \    /
4758  //   vector_shuffle V1, V2 <1, 2, 3, X>
4759  //
4760  if (!isShuffleMaskConsecutive(SVOp,
4761            0,                   // Mask Start Index
4762            NumElems-NumZeros,   // Mask End Index(exclusive)
4763            NumZeros,            // Where to start looking in the src vector
4764            NumElems,            // Number of elements in vector
4765            OpSrc))              // Which source operand ?
4766    return false;
4767
4768  isLeft = false;
4769  ShAmt = NumZeros;
4770  ShVal = SVOp->getOperand(OpSrc);
4771  return true;
4772}
4773
4774/// isVectorShiftLeft - Returns true if the shuffle can be implemented as a
4775/// logical left shift of a vector.
4776static bool isVectorShiftLeft(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4777                              bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4778  unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
4779  unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems,
4780              true /* check zeros from left */, DAG);
4781  unsigned OpSrc;
4782
4783  if (!NumZeros)
4784    return false;
4785
4786  // Considering the elements in the mask that are not consecutive zeros,
4787  // check if they consecutively come from only one of the source vectors.
4788  //
4789  //                           0    { A, B, X, X } = V2
4790  //                          / \    /  /
4791  //   vector_shuffle V1, V2 <X, X, 4, 5>
4792  //
4793  if (!isShuffleMaskConsecutive(SVOp,
4794            NumZeros,     // Mask Start Index
4795            NumElems,     // Mask End Index(exclusive)
4796            0,            // Where to start looking in the src vector
4797            NumElems,     // Number of elements in vector
4798            OpSrc))       // Which source operand ?
4799    return false;
4800
4801  isLeft = true;
4802  ShAmt = NumZeros;
4803  ShVal = SVOp->getOperand(OpSrc);
4804  return true;
4805}
4806
4807/// isVectorShift - Returns true if the shuffle can be implemented as a
4808/// logical left or right shift of a vector.
4809static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4810                          bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4811  // Although the logic below support any bitwidth size, there are no
4812  // shift instructions which handle more than 128-bit vectors.
4813  if (!SVOp->getValueType(0).is128BitVector())
4814    return false;
4815
4816  if (isVectorShiftLeft(SVOp, DAG, isLeft, ShVal, ShAmt) ||
4817      isVectorShiftRight(SVOp, DAG, isLeft, ShVal, ShAmt))
4818    return true;
4819
4820  return false;
4821}
4822
4823/// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
4824///
4825static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
4826                                       unsigned NumNonZero, unsigned NumZero,
4827                                       SelectionDAG &DAG,
4828                                       const X86Subtarget* Subtarget,
4829                                       const TargetLowering &TLI) {
4830  if (NumNonZero > 8)
4831    return SDValue();
4832
4833  DebugLoc dl = Op.getDebugLoc();
4834  SDValue V(0, 0);
4835  bool First = true;
4836  for (unsigned i = 0; i < 16; ++i) {
4837    bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
4838    if (ThisIsNonZero && First) {
4839      if (NumZero)
4840        V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
4841      else
4842        V = DAG.getUNDEF(MVT::v8i16);
4843      First = false;
4844    }
4845
4846    if ((i & 1) != 0) {
4847      SDValue ThisElt(0, 0), LastElt(0, 0);
4848      bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
4849      if (LastIsNonZero) {
4850        LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
4851                              MVT::i16, Op.getOperand(i-1));
4852      }
4853      if (ThisIsNonZero) {
4854        ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
4855        ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
4856                              ThisElt, DAG.getConstant(8, MVT::i8));
4857        if (LastIsNonZero)
4858          ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
4859      } else
4860        ThisElt = LastElt;
4861
4862      if (ThisElt.getNode())
4863        V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
4864                        DAG.getIntPtrConstant(i/2));
4865    }
4866  }
4867
4868  return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V);
4869}
4870
4871/// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
4872///
4873static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
4874                                     unsigned NumNonZero, unsigned NumZero,
4875                                     SelectionDAG &DAG,
4876                                     const X86Subtarget* Subtarget,
4877                                     const TargetLowering &TLI) {
4878  if (NumNonZero > 4)
4879    return SDValue();
4880
4881  DebugLoc dl = Op.getDebugLoc();
4882  SDValue V(0, 0);
4883  bool First = true;
4884  for (unsigned i = 0; i < 8; ++i) {
4885    bool isNonZero = (NonZeros & (1 << i)) != 0;
4886    if (isNonZero) {
4887      if (First) {
4888        if (NumZero)
4889          V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
4890        else
4891          V = DAG.getUNDEF(MVT::v8i16);
4892        First = false;
4893      }
4894      V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
4895                      MVT::v8i16, V, Op.getOperand(i),
4896                      DAG.getIntPtrConstant(i));
4897    }
4898  }
4899
4900  return V;
4901}
4902
4903/// getVShift - Return a vector logical shift node.
4904///
4905static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
4906                         unsigned NumBits, SelectionDAG &DAG,
4907                         const TargetLowering &TLI, DebugLoc dl) {
4908  assert(VT.is128BitVector() && "Unknown type for VShift");
4909  EVT ShVT = MVT::v2i64;
4910  unsigned Opc = isLeft ? X86ISD::VSHLDQ : X86ISD::VSRLDQ;
4911  SrcOp = DAG.getNode(ISD::BITCAST, dl, ShVT, SrcOp);
4912  return DAG.getNode(ISD::BITCAST, dl, VT,
4913                     DAG.getNode(Opc, dl, ShVT, SrcOp,
4914                             DAG.getConstant(NumBits,
4915                                  TLI.getShiftAmountTy(SrcOp.getValueType()))));
4916}
4917
4918SDValue
4919X86TargetLowering::LowerAsSplatVectorLoad(SDValue SrcOp, EVT VT, DebugLoc dl,
4920                                          SelectionDAG &DAG) const {
4921
4922  // Check if the scalar load can be widened into a vector load. And if
4923  // the address is "base + cst" see if the cst can be "absorbed" into
4924  // the shuffle mask.
4925  if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
4926    SDValue Ptr = LD->getBasePtr();
4927    if (!ISD::isNormalLoad(LD) || LD->isVolatile())
4928      return SDValue();
4929    EVT PVT = LD->getValueType(0);
4930    if (PVT != MVT::i32 && PVT != MVT::f32)
4931      return SDValue();
4932
4933    int FI = -1;
4934    int64_t Offset = 0;
4935    if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
4936      FI = FINode->getIndex();
4937      Offset = 0;
4938    } else if (DAG.isBaseWithConstantOffset(Ptr) &&
4939               isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
4940      FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
4941      Offset = Ptr.getConstantOperandVal(1);
4942      Ptr = Ptr.getOperand(0);
4943    } else {
4944      return SDValue();
4945    }
4946
4947    // FIXME: 256-bit vector instructions don't require a strict alignment,
4948    // improve this code to support it better.
4949    unsigned RequiredAlign = VT.getSizeInBits()/8;
4950    SDValue Chain = LD->getChain();
4951    // Make sure the stack object alignment is at least 16 or 32.
4952    MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
4953    if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
4954      if (MFI->isFixedObjectIndex(FI)) {
4955        // Can't change the alignment. FIXME: It's possible to compute
4956        // the exact stack offset and reference FI + adjust offset instead.
4957        // If someone *really* cares about this. That's the way to implement it.
4958        return SDValue();
4959      } else {
4960        MFI->setObjectAlignment(FI, RequiredAlign);
4961      }
4962    }
4963
4964    // (Offset % 16 or 32) must be multiple of 4. Then address is then
4965    // Ptr + (Offset & ~15).
4966    if (Offset < 0)
4967      return SDValue();
4968    if ((Offset % RequiredAlign) & 3)
4969      return SDValue();
4970    int64_t StartOffset = Offset & ~(RequiredAlign-1);
4971    if (StartOffset)
4972      Ptr = DAG.getNode(ISD::ADD, Ptr.getDebugLoc(), Ptr.getValueType(),
4973                        Ptr,DAG.getConstant(StartOffset, Ptr.getValueType()));
4974
4975    int EltNo = (Offset - StartOffset) >> 2;
4976    unsigned NumElems = VT.getVectorNumElements();
4977
4978    EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
4979    SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
4980                             LD->getPointerInfo().getWithOffset(StartOffset),
4981                             false, false, false, 0);
4982
4983    SmallVector<int, 8> Mask;
4984    for (unsigned i = 0; i != NumElems; ++i)
4985      Mask.push_back(EltNo);
4986
4987    return DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &Mask[0]);
4988  }
4989
4990  return SDValue();
4991}
4992
4993/// EltsFromConsecutiveLoads - Given the initializing elements 'Elts' of a
4994/// vector of type 'VT', see if the elements can be replaced by a single large
4995/// load which has the same value as a build_vector whose operands are 'elts'.
4996///
4997/// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
4998///
4999/// FIXME: we'd also like to handle the case where the last elements are zero
5000/// rather than undef via VZEXT_LOAD, but we do not detect that case today.
5001/// There's even a handy isZeroNode for that purpose.
5002static SDValue EltsFromConsecutiveLoads(EVT VT, SmallVectorImpl<SDValue> &Elts,
5003                                        DebugLoc &DL, SelectionDAG &DAG) {
5004  EVT EltVT = VT.getVectorElementType();
5005  unsigned NumElems = Elts.size();
5006
5007  LoadSDNode *LDBase = NULL;
5008  unsigned LastLoadedElt = -1U;
5009
5010  // For each element in the initializer, see if we've found a load or an undef.
5011  // If we don't find an initial load element, or later load elements are
5012  // non-consecutive, bail out.
5013  for (unsigned i = 0; i < NumElems; ++i) {
5014    SDValue Elt = Elts[i];
5015
5016    if (!Elt.getNode() ||
5017        (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
5018      return SDValue();
5019    if (!LDBase) {
5020      if (Elt.getNode()->getOpcode() == ISD::UNDEF)
5021        return SDValue();
5022      LDBase = cast<LoadSDNode>(Elt.getNode());
5023      LastLoadedElt = i;
5024      continue;
5025    }
5026    if (Elt.getOpcode() == ISD::UNDEF)
5027      continue;
5028
5029    LoadSDNode *LD = cast<LoadSDNode>(Elt);
5030    if (!DAG.isConsecutiveLoad(LD, LDBase, EltVT.getSizeInBits()/8, i))
5031      return SDValue();
5032    LastLoadedElt = i;
5033  }
5034
5035  // If we have found an entire vector of loads and undefs, then return a large
5036  // load of the entire vector width starting at the base pointer.  If we found
5037  // consecutive loads for the low half, generate a vzext_load node.
5038  if (LastLoadedElt == NumElems - 1) {
5039    if (DAG.InferPtrAlignment(LDBase->getBasePtr()) >= 16)
5040      return DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5041                         LDBase->getPointerInfo(),
5042                         LDBase->isVolatile(), LDBase->isNonTemporal(),
5043                         LDBase->isInvariant(), 0);
5044    return DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5045                       LDBase->getPointerInfo(),
5046                       LDBase->isVolatile(), LDBase->isNonTemporal(),
5047                       LDBase->isInvariant(), LDBase->getAlignment());
5048  }
5049  if (NumElems == 4 && LastLoadedElt == 1 &&
5050      DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) {
5051    SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
5052    SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
5053    SDValue ResNode =
5054        DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops, 2, MVT::i64,
5055                                LDBase->getPointerInfo(),
5056                                LDBase->getAlignment(),
5057                                false/*isVolatile*/, true/*ReadMem*/,
5058                                false/*WriteMem*/);
5059
5060    // Make sure the newly-created LOAD is in the same position as LDBase in
5061    // terms of dependency. We create a TokenFactor for LDBase and ResNode, and
5062    // update uses of LDBase's output chain to use the TokenFactor.
5063    if (LDBase->hasAnyUseOfValue(1)) {
5064      SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5065                             SDValue(LDBase, 1), SDValue(ResNode.getNode(), 1));
5066      DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5067      DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5068                             SDValue(ResNode.getNode(), 1));
5069    }
5070
5071    return DAG.getNode(ISD::BITCAST, DL, VT, ResNode);
5072  }
5073  return SDValue();
5074}
5075
5076/// LowerVectorBroadcast - Attempt to use the vbroadcast instruction
5077/// to generate a splat value for the following cases:
5078/// 1. A splat BUILD_VECTOR which uses a single scalar load, or a constant.
5079/// 2. A splat shuffle which uses a scalar_to_vector node which comes from
5080/// a scalar load, or a constant.
5081/// The VBROADCAST node is returned when a pattern is found,
5082/// or SDValue() otherwise.
5083SDValue
5084X86TargetLowering::LowerVectorBroadcast(SDValue Op, SelectionDAG &DAG) const {
5085  if (!Subtarget->hasAVX())
5086    return SDValue();
5087
5088  EVT VT = Op.getValueType();
5089  DebugLoc dl = Op.getDebugLoc();
5090
5091  assert((VT.is128BitVector() || VT.is256BitVector()) &&
5092         "Unsupported vector type for broadcast.");
5093
5094  SDValue Ld;
5095  bool ConstSplatVal;
5096
5097  switch (Op.getOpcode()) {
5098    default:
5099      // Unknown pattern found.
5100      return SDValue();
5101
5102    case ISD::BUILD_VECTOR: {
5103      // The BUILD_VECTOR node must be a splat.
5104      if (!isSplatVector(Op.getNode()))
5105        return SDValue();
5106
5107      Ld = Op.getOperand(0);
5108      ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5109                     Ld.getOpcode() == ISD::ConstantFP);
5110
5111      // The suspected load node has several users. Make sure that all
5112      // of its users are from the BUILD_VECTOR node.
5113      // Constants may have multiple users.
5114      if (!ConstSplatVal && !Ld->hasNUsesOfValue(VT.getVectorNumElements(), 0))
5115        return SDValue();
5116      break;
5117    }
5118
5119    case ISD::VECTOR_SHUFFLE: {
5120      ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5121
5122      // Shuffles must have a splat mask where the first element is
5123      // broadcasted.
5124      if ((!SVOp->isSplat()) || SVOp->getMaskElt(0) != 0)
5125        return SDValue();
5126
5127      SDValue Sc = Op.getOperand(0);
5128      if (Sc.getOpcode() != ISD::SCALAR_TO_VECTOR &&
5129          Sc.getOpcode() != ISD::BUILD_VECTOR) {
5130
5131        if (!Subtarget->hasAVX2())
5132          return SDValue();
5133
5134        // Use the register form of the broadcast instruction available on AVX2.
5135        if (VT.is256BitVector())
5136          Sc = Extract128BitVector(Sc, 0, DAG, dl);
5137        return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Sc);
5138      }
5139
5140      Ld = Sc.getOperand(0);
5141      ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5142                       Ld.getOpcode() == ISD::ConstantFP);
5143
5144      // The scalar_to_vector node and the suspected
5145      // load node must have exactly one user.
5146      // Constants may have multiple users.
5147      if (!ConstSplatVal && (!Sc.hasOneUse() || !Ld.hasOneUse()))
5148        return SDValue();
5149      break;
5150    }
5151  }
5152
5153  bool Is256 = VT.is256BitVector();
5154
5155  // Handle the broadcasting a single constant scalar from the constant pool
5156  // into a vector. On Sandybridge it is still better to load a constant vector
5157  // from the constant pool and not to broadcast it from a scalar.
5158  if (ConstSplatVal && Subtarget->hasAVX2()) {
5159    EVT CVT = Ld.getValueType();
5160    assert(!CVT.isVector() && "Must not broadcast a vector type");
5161    unsigned ScalarSize = CVT.getSizeInBits();
5162
5163    if (ScalarSize == 32 || (Is256 && ScalarSize == 64)) {
5164      const Constant *C = 0;
5165      if (ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Ld))
5166        C = CI->getConstantIntValue();
5167      else if (ConstantFPSDNode *CF = dyn_cast<ConstantFPSDNode>(Ld))
5168        C = CF->getConstantFPValue();
5169
5170      assert(C && "Invalid constant type");
5171
5172      SDValue CP = DAG.getConstantPool(C, getPointerTy());
5173      unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
5174      Ld = DAG.getLoad(CVT, dl, DAG.getEntryNode(), CP,
5175                       MachinePointerInfo::getConstantPool(),
5176                       false, false, false, Alignment);
5177
5178      return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5179    }
5180  }
5181
5182  bool IsLoad = ISD::isNormalLoad(Ld.getNode());
5183  unsigned ScalarSize = Ld.getValueType().getSizeInBits();
5184
5185  // Handle AVX2 in-register broadcasts.
5186  if (!IsLoad && Subtarget->hasAVX2() &&
5187      (ScalarSize == 32 || (Is256 && ScalarSize == 64)))
5188    return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5189
5190  // The scalar source must be a normal load.
5191  if (!IsLoad)
5192    return SDValue();
5193
5194  if (ScalarSize == 32 || (Is256 && ScalarSize == 64))
5195    return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5196
5197  // The integer check is needed for the 64-bit into 128-bit so it doesn't match
5198  // double since there is no vbroadcastsd xmm
5199  if (Subtarget->hasAVX2() && Ld.getValueType().isInteger()) {
5200    if (ScalarSize == 8 || ScalarSize == 16 || ScalarSize == 64)
5201      return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5202  }
5203
5204  // Unsupported broadcast.
5205  return SDValue();
5206}
5207
5208SDValue
5209X86TargetLowering::buildFromShuffleMostly(SDValue Op, SelectionDAG &DAG) const {
5210  EVT VT = Op.getValueType();
5211
5212  // Skip if insert_vec_elt is not supported.
5213  if (!isOperationLegalOrCustom(ISD::INSERT_VECTOR_ELT, VT))
5214    return SDValue();
5215
5216  DebugLoc DL = Op.getDebugLoc();
5217  unsigned NumElems = Op.getNumOperands();
5218
5219  SDValue VecIn1;
5220  SDValue VecIn2;
5221  SmallVector<unsigned, 4> InsertIndices;
5222  SmallVector<int, 8> Mask(NumElems, -1);
5223
5224  for (unsigned i = 0; i != NumElems; ++i) {
5225    unsigned Opc = Op.getOperand(i).getOpcode();
5226
5227    if (Opc == ISD::UNDEF)
5228      continue;
5229
5230    if (Opc != ISD::EXTRACT_VECTOR_ELT) {
5231      // Quit if more than 1 elements need inserting.
5232      if (InsertIndices.size() > 1)
5233        return SDValue();
5234
5235      InsertIndices.push_back(i);
5236      continue;
5237    }
5238
5239    SDValue ExtractedFromVec = Op.getOperand(i).getOperand(0);
5240    SDValue ExtIdx = Op.getOperand(i).getOperand(1);
5241
5242    // Quit if extracted from vector of different type.
5243    if (ExtractedFromVec.getValueType() != VT)
5244      return SDValue();
5245
5246    // Quit if non-constant index.
5247    if (!isa<ConstantSDNode>(ExtIdx))
5248      return SDValue();
5249
5250    if (VecIn1.getNode() == 0)
5251      VecIn1 = ExtractedFromVec;
5252    else if (VecIn1 != ExtractedFromVec) {
5253      if (VecIn2.getNode() == 0)
5254        VecIn2 = ExtractedFromVec;
5255      else if (VecIn2 != ExtractedFromVec)
5256        // Quit if more than 2 vectors to shuffle
5257        return SDValue();
5258    }
5259
5260    unsigned Idx = cast<ConstantSDNode>(ExtIdx)->getZExtValue();
5261
5262    if (ExtractedFromVec == VecIn1)
5263      Mask[i] = Idx;
5264    else if (ExtractedFromVec == VecIn2)
5265      Mask[i] = Idx + NumElems;
5266  }
5267
5268  if (VecIn1.getNode() == 0)
5269    return SDValue();
5270
5271  VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
5272  SDValue NV = DAG.getVectorShuffle(VT, DL, VecIn1, VecIn2, &Mask[0]);
5273  for (unsigned i = 0, e = InsertIndices.size(); i != e; ++i) {
5274    unsigned Idx = InsertIndices[i];
5275    NV = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, NV, Op.getOperand(Idx),
5276                     DAG.getIntPtrConstant(Idx));
5277  }
5278
5279  return NV;
5280}
5281
5282SDValue
5283X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
5284  DebugLoc dl = Op.getDebugLoc();
5285
5286  EVT VT = Op.getValueType();
5287  EVT ExtVT = VT.getVectorElementType();
5288  unsigned NumElems = Op.getNumOperands();
5289
5290  // Vectors containing all zeros can be matched by pxor and xorps later
5291  if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5292    // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
5293    // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
5294    if (VT == MVT::v4i32 || VT == MVT::v8i32)
5295      return Op;
5296
5297    return getZeroVector(VT, Subtarget, DAG, dl);
5298  }
5299
5300  // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
5301  // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use
5302  // vpcmpeqd on 256-bit vectors.
5303  if (ISD::isBuildVectorAllOnes(Op.getNode())) {
5304    if (VT == MVT::v4i32 || (VT == MVT::v8i32 && Subtarget->hasAVX2()))
5305      return Op;
5306
5307    return getOnesVector(VT, Subtarget->hasAVX2(), DAG, dl);
5308  }
5309
5310  SDValue Broadcast = LowerVectorBroadcast(Op, DAG);
5311  if (Broadcast.getNode())
5312    return Broadcast;
5313
5314  unsigned EVTBits = ExtVT.getSizeInBits();
5315
5316  unsigned NumZero  = 0;
5317  unsigned NumNonZero = 0;
5318  unsigned NonZeros = 0;
5319  bool IsAllConstants = true;
5320  SmallSet<SDValue, 8> Values;
5321  for (unsigned i = 0; i < NumElems; ++i) {
5322    SDValue Elt = Op.getOperand(i);
5323    if (Elt.getOpcode() == ISD::UNDEF)
5324      continue;
5325    Values.insert(Elt);
5326    if (Elt.getOpcode() != ISD::Constant &&
5327        Elt.getOpcode() != ISD::ConstantFP)
5328      IsAllConstants = false;
5329    if (X86::isZeroNode(Elt))
5330      NumZero++;
5331    else {
5332      NonZeros |= (1 << i);
5333      NumNonZero++;
5334    }
5335  }
5336
5337  // All undef vector. Return an UNDEF.  All zero vectors were handled above.
5338  if (NumNonZero == 0)
5339    return DAG.getUNDEF(VT);
5340
5341  // Special case for single non-zero, non-undef, element.
5342  if (NumNonZero == 1) {
5343    unsigned Idx = CountTrailingZeros_32(NonZeros);
5344    SDValue Item = Op.getOperand(Idx);
5345
5346    // If this is an insertion of an i64 value on x86-32, and if the top bits of
5347    // the value are obviously zero, truncate the value to i32 and do the
5348    // insertion that way.  Only do this if the value is non-constant or if the
5349    // value is a constant being inserted into element 0.  It is cheaper to do
5350    // a constant pool load than it is to do a movd + shuffle.
5351    if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
5352        (!IsAllConstants || Idx == 0)) {
5353      if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
5354        // Handle SSE only.
5355        assert(VT == MVT::v2i64 && "Expected an SSE value type!");
5356        EVT VecVT = MVT::v4i32;
5357        unsigned VecElts = 4;
5358
5359        // Truncate the value (which may itself be a constant) to i32, and
5360        // convert it to a vector with movd (S2V+shuffle to zero extend).
5361        Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
5362        Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
5363        Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5364
5365        // Now we have our 32-bit value zero extended in the low element of
5366        // a vector.  If Idx != 0, swizzle it into place.
5367        if (Idx != 0) {
5368          SmallVector<int, 4> Mask;
5369          Mask.push_back(Idx);
5370          for (unsigned i = 1; i != VecElts; ++i)
5371            Mask.push_back(i);
5372          Item = DAG.getVectorShuffle(VecVT, dl, Item, DAG.getUNDEF(VecVT),
5373                                      &Mask[0]);
5374        }
5375        return DAG.getNode(ISD::BITCAST, dl, VT, Item);
5376      }
5377    }
5378
5379    // If we have a constant or non-constant insertion into the low element of
5380    // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
5381    // the rest of the elements.  This will be matched as movd/movq/movss/movsd
5382    // depending on what the source datatype is.
5383    if (Idx == 0) {
5384      if (NumZero == 0)
5385        return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5386
5387      if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
5388          (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
5389        if (VT.is256BitVector()) {
5390          SDValue ZeroVec = getZeroVector(VT, Subtarget, DAG, dl);
5391          return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, ZeroVec,
5392                             Item, DAG.getIntPtrConstant(0));
5393        }
5394        assert(VT.is128BitVector() && "Expected an SSE value type!");
5395        Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5396        // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
5397        return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5398      }
5399
5400      if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
5401        Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
5402        Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
5403        if (VT.is256BitVector()) {
5404          SDValue ZeroVec = getZeroVector(MVT::v8i32, Subtarget, DAG, dl);
5405          Item = Insert128BitVector(ZeroVec, Item, 0, DAG, dl);
5406        } else {
5407          assert(VT.is128BitVector() && "Expected an SSE value type!");
5408          Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5409        }
5410        return DAG.getNode(ISD::BITCAST, dl, VT, Item);
5411      }
5412    }
5413
5414    // Is it a vector logical left shift?
5415    if (NumElems == 2 && Idx == 1 &&
5416        X86::isZeroNode(Op.getOperand(0)) &&
5417        !X86::isZeroNode(Op.getOperand(1))) {
5418      unsigned NumBits = VT.getSizeInBits();
5419      return getVShift(true, VT,
5420                       DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
5421                                   VT, Op.getOperand(1)),
5422                       NumBits/2, DAG, *this, dl);
5423    }
5424
5425    if (IsAllConstants) // Otherwise, it's better to do a constpool load.
5426      return SDValue();
5427
5428    // Otherwise, if this is a vector with i32 or f32 elements, and the element
5429    // is a non-constant being inserted into an element other than the low one,
5430    // we can't use a constant pool load.  Instead, use SCALAR_TO_VECTOR (aka
5431    // movd/movss) to move this into the low element, then shuffle it into
5432    // place.
5433    if (EVTBits == 32) {
5434      Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5435
5436      // Turn it into a shuffle of zero and zero-extended scalar to vector.
5437      Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0, Subtarget, DAG);
5438      SmallVector<int, 8> MaskVec;
5439      for (unsigned i = 0; i != NumElems; ++i)
5440        MaskVec.push_back(i == Idx ? 0 : 1);
5441      return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
5442    }
5443  }
5444
5445  // Splat is obviously ok. Let legalizer expand it to a shuffle.
5446  if (Values.size() == 1) {
5447    if (EVTBits == 32) {
5448      // Instead of a shuffle like this:
5449      // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
5450      // Check if it's possible to issue this instead.
5451      // shuffle (vload ptr)), undef, <1, 1, 1, 1>
5452      unsigned Idx = CountTrailingZeros_32(NonZeros);
5453      SDValue Item = Op.getOperand(Idx);
5454      if (Op.getNode()->isOnlyUserOf(Item.getNode()))
5455        return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
5456    }
5457    return SDValue();
5458  }
5459
5460  // A vector full of immediates; various special cases are already
5461  // handled, so this is best done with a single constant-pool load.
5462  if (IsAllConstants)
5463    return SDValue();
5464
5465  // For AVX-length vectors, build the individual 128-bit pieces and use
5466  // shuffles to put them in place.
5467  if (VT.is256BitVector()) {
5468    SmallVector<SDValue, 32> V;
5469    for (unsigned i = 0; i != NumElems; ++i)
5470      V.push_back(Op.getOperand(i));
5471
5472    EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
5473
5474    // Build both the lower and upper subvector.
5475    SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[0], NumElems/2);
5476    SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[NumElems / 2],
5477                                NumElems/2);
5478
5479    // Recreate the wider vector with the lower and upper part.
5480    return Concat128BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
5481  }
5482
5483  // Let legalizer expand 2-wide build_vectors.
5484  if (EVTBits == 64) {
5485    if (NumNonZero == 1) {
5486      // One half is zero or undef.
5487      unsigned Idx = CountTrailingZeros_32(NonZeros);
5488      SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
5489                                 Op.getOperand(Idx));
5490      return getShuffleVectorZeroOrUndef(V2, Idx, true, Subtarget, DAG);
5491    }
5492    return SDValue();
5493  }
5494
5495  // If element VT is < 32 bits, convert it to inserts into a zero vector.
5496  if (EVTBits == 8 && NumElems == 16) {
5497    SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
5498                                        Subtarget, *this);
5499    if (V.getNode()) return V;
5500  }
5501
5502  if (EVTBits == 16 && NumElems == 8) {
5503    SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
5504                                      Subtarget, *this);
5505    if (V.getNode()) return V;
5506  }
5507
5508  // If element VT is == 32 bits, turn it into a number of shuffles.
5509  SmallVector<SDValue, 8> V(NumElems);
5510  if (NumElems == 4 && NumZero > 0) {
5511    for (unsigned i = 0; i < 4; ++i) {
5512      bool isZero = !(NonZeros & (1 << i));
5513      if (isZero)
5514        V[i] = getZeroVector(VT, Subtarget, DAG, dl);
5515      else
5516        V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
5517    }
5518
5519    for (unsigned i = 0; i < 2; ++i) {
5520      switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
5521        default: break;
5522        case 0:
5523          V[i] = V[i*2];  // Must be a zero vector.
5524          break;
5525        case 1:
5526          V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
5527          break;
5528        case 2:
5529          V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
5530          break;
5531        case 3:
5532          V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
5533          break;
5534      }
5535    }
5536
5537    bool Reverse1 = (NonZeros & 0x3) == 2;
5538    bool Reverse2 = ((NonZeros & (0x3 << 2)) >> 2) == 2;
5539    int MaskVec[] = {
5540      Reverse1 ? 1 : 0,
5541      Reverse1 ? 0 : 1,
5542      static_cast<int>(Reverse2 ? NumElems+1 : NumElems),
5543      static_cast<int>(Reverse2 ? NumElems   : NumElems+1)
5544    };
5545    return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
5546  }
5547
5548  if (Values.size() > 1 && VT.is128BitVector()) {
5549    // Check for a build vector of consecutive loads.
5550    for (unsigned i = 0; i < NumElems; ++i)
5551      V[i] = Op.getOperand(i);
5552
5553    // Check for elements which are consecutive loads.
5554    SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG);
5555    if (LD.getNode())
5556      return LD;
5557
5558    // Check for a build vector from mostly shuffle plus few inserting.
5559    SDValue Sh = buildFromShuffleMostly(Op, DAG);
5560    if (Sh.getNode())
5561      return Sh;
5562
5563    // For SSE 4.1, use insertps to put the high elements into the low element.
5564    if (getSubtarget()->hasSSE41()) {
5565      SDValue Result;
5566      if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
5567        Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
5568      else
5569        Result = DAG.getUNDEF(VT);
5570
5571      for (unsigned i = 1; i < NumElems; ++i) {
5572        if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
5573        Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
5574                             Op.getOperand(i), DAG.getIntPtrConstant(i));
5575      }
5576      return Result;
5577    }
5578
5579    // Otherwise, expand into a number of unpckl*, start by extending each of
5580    // our (non-undef) elements to the full vector width with the element in the
5581    // bottom slot of the vector (which generates no code for SSE).
5582    for (unsigned i = 0; i < NumElems; ++i) {
5583      if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
5584        V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
5585      else
5586        V[i] = DAG.getUNDEF(VT);
5587    }
5588
5589    // Next, we iteratively mix elements, e.g. for v4f32:
5590    //   Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
5591    //         : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
5592    //   Step 2: unpcklps X, Y ==>    <3, 2, 1, 0>
5593    unsigned EltStride = NumElems >> 1;
5594    while (EltStride != 0) {
5595      for (unsigned i = 0; i < EltStride; ++i) {
5596        // If V[i+EltStride] is undef and this is the first round of mixing,
5597        // then it is safe to just drop this shuffle: V[i] is already in the
5598        // right place, the one element (since it's the first round) being
5599        // inserted as undef can be dropped.  This isn't safe for successive
5600        // rounds because they will permute elements within both vectors.
5601        if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
5602            EltStride == NumElems/2)
5603          continue;
5604
5605        V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
5606      }
5607      EltStride >>= 1;
5608    }
5609    return V[0];
5610  }
5611  return SDValue();
5612}
5613
5614// LowerAVXCONCAT_VECTORS - 256-bit AVX can use the vinsertf128 instruction
5615// to create 256-bit vectors from two other 128-bit ones.
5616static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5617  DebugLoc dl = Op.getDebugLoc();
5618  EVT ResVT = Op.getValueType();
5619
5620  assert(ResVT.is256BitVector() && "Value type must be 256-bit wide");
5621
5622  SDValue V1 = Op.getOperand(0);
5623  SDValue V2 = Op.getOperand(1);
5624  unsigned NumElems = ResVT.getVectorNumElements();
5625
5626  return Concat128BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
5627}
5628
5629static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5630  assert(Op.getNumOperands() == 2);
5631
5632  // 256-bit AVX can use the vinsertf128 instruction to create 256-bit vectors
5633  // from two other 128-bit ones.
5634  return LowerAVXCONCAT_VECTORS(Op, DAG);
5635}
5636
5637// Try to lower a shuffle node into a simple blend instruction.
5638static SDValue
5639LowerVECTOR_SHUFFLEtoBlend(ShuffleVectorSDNode *SVOp,
5640                           const X86Subtarget *Subtarget, SelectionDAG &DAG) {
5641  SDValue V1 = SVOp->getOperand(0);
5642  SDValue V2 = SVOp->getOperand(1);
5643  DebugLoc dl = SVOp->getDebugLoc();
5644  MVT VT = SVOp->getValueType(0).getSimpleVT();
5645  unsigned NumElems = VT.getVectorNumElements();
5646
5647  if (!Subtarget->hasSSE41())
5648    return SDValue();
5649
5650  unsigned ISDNo = 0;
5651  MVT OpTy;
5652
5653  switch (VT.SimpleTy) {
5654  default: return SDValue();
5655  case MVT::v8i16:
5656    ISDNo = X86ISD::BLENDPW;
5657    OpTy = MVT::v8i16;
5658    break;
5659  case MVT::v4i32:
5660  case MVT::v4f32:
5661    ISDNo = X86ISD::BLENDPS;
5662    OpTy = MVT::v4f32;
5663    break;
5664  case MVT::v2i64:
5665  case MVT::v2f64:
5666    ISDNo = X86ISD::BLENDPD;
5667    OpTy = MVT::v2f64;
5668    break;
5669  case MVT::v8i32:
5670  case MVT::v8f32:
5671    if (!Subtarget->hasAVX())
5672      return SDValue();
5673    ISDNo = X86ISD::BLENDPS;
5674    OpTy = MVT::v8f32;
5675    break;
5676  case MVT::v4i64:
5677  case MVT::v4f64:
5678    if (!Subtarget->hasAVX())
5679      return SDValue();
5680    ISDNo = X86ISD::BLENDPD;
5681    OpTy = MVT::v4f64;
5682    break;
5683  }
5684  assert(ISDNo && "Invalid Op Number");
5685
5686  unsigned MaskVals = 0;
5687
5688  for (unsigned i = 0; i != NumElems; ++i) {
5689    int EltIdx = SVOp->getMaskElt(i);
5690    if (EltIdx == (int)i || EltIdx < 0)
5691      MaskVals |= (1<<i);
5692    else if (EltIdx == (int)(i + NumElems))
5693      continue; // Bit is set to zero;
5694    else
5695      return SDValue();
5696  }
5697
5698  V1 = DAG.getNode(ISD::BITCAST, dl, OpTy, V1);
5699  V2 = DAG.getNode(ISD::BITCAST, dl, OpTy, V2);
5700  SDValue Ret =  DAG.getNode(ISDNo, dl, OpTy, V1, V2,
5701                             DAG.getConstant(MaskVals, MVT::i32));
5702  return DAG.getNode(ISD::BITCAST, dl, VT, Ret);
5703}
5704
5705// v8i16 shuffles - Prefer shuffles in the following order:
5706// 1. [all]   pshuflw, pshufhw, optional move
5707// 2. [ssse3] 1 x pshufb
5708// 3. [ssse3] 2 x pshufb + 1 x por
5709// 4. [all]   mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
5710static SDValue
5711LowerVECTOR_SHUFFLEv8i16(SDValue Op, const X86Subtarget *Subtarget,
5712                         SelectionDAG &DAG) {
5713  ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5714  SDValue V1 = SVOp->getOperand(0);
5715  SDValue V2 = SVOp->getOperand(1);
5716  DebugLoc dl = SVOp->getDebugLoc();
5717  SmallVector<int, 8> MaskVals;
5718
5719  // Determine if more than 1 of the words in each of the low and high quadwords
5720  // of the result come from the same quadword of one of the two inputs.  Undef
5721  // mask values count as coming from any quadword, for better codegen.
5722  unsigned LoQuad[] = { 0, 0, 0, 0 };
5723  unsigned HiQuad[] = { 0, 0, 0, 0 };
5724  std::bitset<4> InputQuads;
5725  for (unsigned i = 0; i < 8; ++i) {
5726    unsigned *Quad = i < 4 ? LoQuad : HiQuad;
5727    int EltIdx = SVOp->getMaskElt(i);
5728    MaskVals.push_back(EltIdx);
5729    if (EltIdx < 0) {
5730      ++Quad[0];
5731      ++Quad[1];
5732      ++Quad[2];
5733      ++Quad[3];
5734      continue;
5735    }
5736    ++Quad[EltIdx / 4];
5737    InputQuads.set(EltIdx / 4);
5738  }
5739
5740  int BestLoQuad = -1;
5741  unsigned MaxQuad = 1;
5742  for (unsigned i = 0; i < 4; ++i) {
5743    if (LoQuad[i] > MaxQuad) {
5744      BestLoQuad = i;
5745      MaxQuad = LoQuad[i];
5746    }
5747  }
5748
5749  int BestHiQuad = -1;
5750  MaxQuad = 1;
5751  for (unsigned i = 0; i < 4; ++i) {
5752    if (HiQuad[i] > MaxQuad) {
5753      BestHiQuad = i;
5754      MaxQuad = HiQuad[i];
5755    }
5756  }
5757
5758  // For SSSE3, If all 8 words of the result come from only 1 quadword of each
5759  // of the two input vectors, shuffle them into one input vector so only a
5760  // single pshufb instruction is necessary. If There are more than 2 input
5761  // quads, disable the next transformation since it does not help SSSE3.
5762  bool V1Used = InputQuads[0] || InputQuads[1];
5763  bool V2Used = InputQuads[2] || InputQuads[3];
5764  if (Subtarget->hasSSSE3()) {
5765    if (InputQuads.count() == 2 && V1Used && V2Used) {
5766      BestLoQuad = InputQuads[0] ? 0 : 1;
5767      BestHiQuad = InputQuads[2] ? 2 : 3;
5768    }
5769    if (InputQuads.count() > 2) {
5770      BestLoQuad = -1;
5771      BestHiQuad = -1;
5772    }
5773  }
5774
5775  // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
5776  // the shuffle mask.  If a quad is scored as -1, that means that it contains
5777  // words from all 4 input quadwords.
5778  SDValue NewV;
5779  if (BestLoQuad >= 0 || BestHiQuad >= 0) {
5780    int MaskV[] = {
5781      BestLoQuad < 0 ? 0 : BestLoQuad,
5782      BestHiQuad < 0 ? 1 : BestHiQuad
5783    };
5784    NewV = DAG.getVectorShuffle(MVT::v2i64, dl,
5785                  DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1),
5786                  DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2), &MaskV[0]);
5787    NewV = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, NewV);
5788
5789    // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
5790    // source words for the shuffle, to aid later transformations.
5791    bool AllWordsInNewV = true;
5792    bool InOrder[2] = { true, true };
5793    for (unsigned i = 0; i != 8; ++i) {
5794      int idx = MaskVals[i];
5795      if (idx != (int)i)
5796        InOrder[i/4] = false;
5797      if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
5798        continue;
5799      AllWordsInNewV = false;
5800      break;
5801    }
5802
5803    bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
5804    if (AllWordsInNewV) {
5805      for (int i = 0; i != 8; ++i) {
5806        int idx = MaskVals[i];
5807        if (idx < 0)
5808          continue;
5809        idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
5810        if ((idx != i) && idx < 4)
5811          pshufhw = false;
5812        if ((idx != i) && idx > 3)
5813          pshuflw = false;
5814      }
5815      V1 = NewV;
5816      V2Used = false;
5817      BestLoQuad = 0;
5818      BestHiQuad = 1;
5819    }
5820
5821    // If we've eliminated the use of V2, and the new mask is a pshuflw or
5822    // pshufhw, that's as cheap as it gets.  Return the new shuffle.
5823    if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
5824      unsigned Opc = pshufhw ? X86ISD::PSHUFHW : X86ISD::PSHUFLW;
5825      unsigned TargetMask = 0;
5826      NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV,
5827                                  DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
5828      ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
5829      TargetMask = pshufhw ? getShufflePSHUFHWImmediate(SVOp):
5830                             getShufflePSHUFLWImmediate(SVOp);
5831      V1 = NewV.getOperand(0);
5832      return getTargetShuffleNode(Opc, dl, MVT::v8i16, V1, TargetMask, DAG);
5833    }
5834  }
5835
5836  // If we have SSSE3, and all words of the result are from 1 input vector,
5837  // case 2 is generated, otherwise case 3 is generated.  If no SSSE3
5838  // is present, fall back to case 4.
5839  if (Subtarget->hasSSSE3()) {
5840    SmallVector<SDValue,16> pshufbMask;
5841
5842    // If we have elements from both input vectors, set the high bit of the
5843    // shuffle mask element to zero out elements that come from V2 in the V1
5844    // mask, and elements that come from V1 in the V2 mask, so that the two
5845    // results can be OR'd together.
5846    bool TwoInputs = V1Used && V2Used;
5847    for (unsigned i = 0; i != 8; ++i) {
5848      int EltIdx = MaskVals[i] * 2;
5849      int Idx0 = (TwoInputs && (EltIdx >= 16)) ? 0x80 : EltIdx;
5850      int Idx1 = (TwoInputs && (EltIdx >= 16)) ? 0x80 : EltIdx+1;
5851      pshufbMask.push_back(DAG.getConstant(Idx0,   MVT::i8));
5852      pshufbMask.push_back(DAG.getConstant(Idx1, MVT::i8));
5853    }
5854    V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V1);
5855    V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
5856                     DAG.getNode(ISD::BUILD_VECTOR, dl,
5857                                 MVT::v16i8, &pshufbMask[0], 16));
5858    if (!TwoInputs)
5859      return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5860
5861    // Calculate the shuffle mask for the second input, shuffle it, and
5862    // OR it with the first shuffled input.
5863    pshufbMask.clear();
5864    for (unsigned i = 0; i != 8; ++i) {
5865      int EltIdx = MaskVals[i] * 2;
5866      int Idx0 = (EltIdx < 16) ? 0x80 : EltIdx - 16;
5867      int Idx1 = (EltIdx < 16) ? 0x80 : EltIdx - 15;
5868      pshufbMask.push_back(DAG.getConstant(Idx0, MVT::i8));
5869      pshufbMask.push_back(DAG.getConstant(Idx1, MVT::i8));
5870    }
5871    V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V2);
5872    V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
5873                     DAG.getNode(ISD::BUILD_VECTOR, dl,
5874                                 MVT::v16i8, &pshufbMask[0], 16));
5875    V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
5876    return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5877  }
5878
5879  // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
5880  // and update MaskVals with new element order.
5881  std::bitset<8> InOrder;
5882  if (BestLoQuad >= 0) {
5883    int MaskV[] = { -1, -1, -1, -1, 4, 5, 6, 7 };
5884    for (int i = 0; i != 4; ++i) {
5885      int idx = MaskVals[i];
5886      if (idx < 0) {
5887        InOrder.set(i);
5888      } else if ((idx / 4) == BestLoQuad) {
5889        MaskV[i] = idx & 3;
5890        InOrder.set(i);
5891      }
5892    }
5893    NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
5894                                &MaskV[0]);
5895
5896    if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3()) {
5897      ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
5898      NewV = getTargetShuffleNode(X86ISD::PSHUFLW, dl, MVT::v8i16,
5899                                  NewV.getOperand(0),
5900                                  getShufflePSHUFLWImmediate(SVOp), DAG);
5901    }
5902  }
5903
5904  // If BestHi >= 0, generate a pshufhw to put the high elements in order,
5905  // and update MaskVals with the new element order.
5906  if (BestHiQuad >= 0) {
5907    int MaskV[] = { 0, 1, 2, 3, -1, -1, -1, -1 };
5908    for (unsigned i = 4; i != 8; ++i) {
5909      int idx = MaskVals[i];
5910      if (idx < 0) {
5911        InOrder.set(i);
5912      } else if ((idx / 4) == BestHiQuad) {
5913        MaskV[i] = (idx & 3) + 4;
5914        InOrder.set(i);
5915      }
5916    }
5917    NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
5918                                &MaskV[0]);
5919
5920    if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3()) {
5921      ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
5922      NewV = getTargetShuffleNode(X86ISD::PSHUFHW, dl, MVT::v8i16,
5923                                  NewV.getOperand(0),
5924                                  getShufflePSHUFHWImmediate(SVOp), DAG);
5925    }
5926  }
5927
5928  // In case BestHi & BestLo were both -1, which means each quadword has a word
5929  // from each of the four input quadwords, calculate the InOrder bitvector now
5930  // before falling through to the insert/extract cleanup.
5931  if (BestLoQuad == -1 && BestHiQuad == -1) {
5932    NewV = V1;
5933    for (int i = 0; i != 8; ++i)
5934      if (MaskVals[i] < 0 || MaskVals[i] == i)
5935        InOrder.set(i);
5936  }
5937
5938  // The other elements are put in the right place using pextrw and pinsrw.
5939  for (unsigned i = 0; i != 8; ++i) {
5940    if (InOrder[i])
5941      continue;
5942    int EltIdx = MaskVals[i];
5943    if (EltIdx < 0)
5944      continue;
5945    SDValue ExtOp = (EltIdx < 8) ?
5946      DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
5947                  DAG.getIntPtrConstant(EltIdx)) :
5948      DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
5949                  DAG.getIntPtrConstant(EltIdx - 8));
5950    NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
5951                       DAG.getIntPtrConstant(i));
5952  }
5953  return NewV;
5954}
5955
5956// v16i8 shuffles - Prefer shuffles in the following order:
5957// 1. [ssse3] 1 x pshufb
5958// 2. [ssse3] 2 x pshufb + 1 x por
5959// 3. [all]   v8i16 shuffle + N x pextrw + rotate + pinsrw
5960static
5961SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
5962                                 SelectionDAG &DAG,
5963                                 const X86TargetLowering &TLI) {
5964  SDValue V1 = SVOp->getOperand(0);
5965  SDValue V2 = SVOp->getOperand(1);
5966  DebugLoc dl = SVOp->getDebugLoc();
5967  ArrayRef<int> MaskVals = SVOp->getMask();
5968
5969  // If we have SSSE3, case 1 is generated when all result bytes come from
5970  // one of  the inputs.  Otherwise, case 2 is generated.  If no SSSE3 is
5971  // present, fall back to case 3.
5972
5973  // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
5974  if (TLI.getSubtarget()->hasSSSE3()) {
5975    SmallVector<SDValue,16> pshufbMask;
5976
5977    // If all result elements are from one input vector, then only translate
5978    // undef mask values to 0x80 (zero out result) in the pshufb mask.
5979    //
5980    // Otherwise, we have elements from both input vectors, and must zero out
5981    // elements that come from V2 in the first mask, and V1 in the second mask
5982    // so that we can OR them together.
5983    for (unsigned i = 0; i != 16; ++i) {
5984      int EltIdx = MaskVals[i];
5985      if (EltIdx < 0 || EltIdx >= 16)
5986        EltIdx = 0x80;
5987      pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
5988    }
5989    V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
5990                     DAG.getNode(ISD::BUILD_VECTOR, dl,
5991                                 MVT::v16i8, &pshufbMask[0], 16));
5992
5993    // As PSHUFB will zero elements with negative indices, it's safe to ignore
5994    // the 2nd operand if it's undefined or zero.
5995    if (V2.getOpcode() == ISD::UNDEF ||
5996        ISD::isBuildVectorAllZeros(V2.getNode()))
5997      return V1;
5998
5999    // Calculate the shuffle mask for the second input, shuffle it, and
6000    // OR it with the first shuffled input.
6001    pshufbMask.clear();
6002    for (unsigned i = 0; i != 16; ++i) {
6003      int EltIdx = MaskVals[i];
6004      EltIdx = (EltIdx < 16) ? 0x80 : EltIdx - 16;
6005      pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
6006    }
6007    V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
6008                     DAG.getNode(ISD::BUILD_VECTOR, dl,
6009                                 MVT::v16i8, &pshufbMask[0], 16));
6010    return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
6011  }
6012
6013  // No SSSE3 - Calculate in place words and then fix all out of place words
6014  // With 0-16 extracts & inserts.  Worst case is 16 bytes out of order from
6015  // the 16 different words that comprise the two doublequadword input vectors.
6016  V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
6017  V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
6018  SDValue NewV = V1;
6019  for (int i = 0; i != 8; ++i) {
6020    int Elt0 = MaskVals[i*2];
6021    int Elt1 = MaskVals[i*2+1];
6022
6023    // This word of the result is all undef, skip it.
6024    if (Elt0 < 0 && Elt1 < 0)
6025      continue;
6026
6027    // This word of the result is already in the correct place, skip it.
6028    if ((Elt0 == i*2) && (Elt1 == i*2+1))
6029      continue;
6030
6031    SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
6032    SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
6033    SDValue InsElt;
6034
6035    // If Elt0 and Elt1 are defined, are consecutive, and can be load
6036    // using a single extract together, load it and store it.
6037    if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
6038      InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
6039                           DAG.getIntPtrConstant(Elt1 / 2));
6040      NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
6041                        DAG.getIntPtrConstant(i));
6042      continue;
6043    }
6044
6045    // If Elt1 is defined, extract it from the appropriate source.  If the
6046    // source byte is not also odd, shift the extracted word left 8 bits
6047    // otherwise clear the bottom 8 bits if we need to do an or.
6048    if (Elt1 >= 0) {
6049      InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
6050                           DAG.getIntPtrConstant(Elt1 / 2));
6051      if ((Elt1 & 1) == 0)
6052        InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
6053                             DAG.getConstant(8,
6054                                  TLI.getShiftAmountTy(InsElt.getValueType())));
6055      else if (Elt0 >= 0)
6056        InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
6057                             DAG.getConstant(0xFF00, MVT::i16));
6058    }
6059    // If Elt0 is defined, extract it from the appropriate source.  If the
6060    // source byte is not also even, shift the extracted word right 8 bits. If
6061    // Elt1 was also defined, OR the extracted values together before
6062    // inserting them in the result.
6063    if (Elt0 >= 0) {
6064      SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
6065                                    Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
6066      if ((Elt0 & 1) != 0)
6067        InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
6068                              DAG.getConstant(8,
6069                                 TLI.getShiftAmountTy(InsElt0.getValueType())));
6070      else if (Elt1 >= 0)
6071        InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
6072                             DAG.getConstant(0x00FF, MVT::i16));
6073      InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
6074                         : InsElt0;
6075    }
6076    NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
6077                       DAG.getIntPtrConstant(i));
6078  }
6079  return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, NewV);
6080}
6081
6082// v32i8 shuffles - Translate to VPSHUFB if possible.
6083static
6084SDValue LowerVECTOR_SHUFFLEv32i8(ShuffleVectorSDNode *SVOp,
6085                                 const X86Subtarget *Subtarget,
6086                                 SelectionDAG &DAG) {
6087  EVT VT = SVOp->getValueType(0);
6088  SDValue V1 = SVOp->getOperand(0);
6089  SDValue V2 = SVOp->getOperand(1);
6090  DebugLoc dl = SVOp->getDebugLoc();
6091  SmallVector<int, 32> MaskVals(SVOp->getMask().begin(), SVOp->getMask().end());
6092
6093  bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
6094  bool V1IsAllZero = ISD::isBuildVectorAllZeros(V1.getNode());
6095  bool V2IsAllZero = ISD::isBuildVectorAllZeros(V2.getNode());
6096
6097  // VPSHUFB may be generated if
6098  // (1) one of input vector is undefined or zeroinitializer.
6099  // The mask value 0x80 puts 0 in the corresponding slot of the vector.
6100  // And (2) the mask indexes don't cross the 128-bit lane.
6101  if (VT != MVT::v32i8 || !Subtarget->hasAVX2() ||
6102      (!V2IsUndef && !V2IsAllZero && !V1IsAllZero))
6103    return SDValue();
6104
6105  if (V1IsAllZero && !V2IsAllZero) {
6106    CommuteVectorShuffleMask(MaskVals, 32);
6107    V1 = V2;
6108  }
6109  SmallVector<SDValue, 32> pshufbMask;
6110  for (unsigned i = 0; i != 32; i++) {
6111    int EltIdx = MaskVals[i];
6112    if (EltIdx < 0 || EltIdx >= 32)
6113      EltIdx = 0x80;
6114    else {
6115      if ((EltIdx >= 16 && i < 16) || (EltIdx < 16 && i >= 16))
6116        // Cross lane is not allowed.
6117        return SDValue();
6118      EltIdx &= 0xf;
6119    }
6120    pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
6121  }
6122  return DAG.getNode(X86ISD::PSHUFB, dl, MVT::v32i8, V1,
6123                      DAG.getNode(ISD::BUILD_VECTOR, dl,
6124                                  MVT::v32i8, &pshufbMask[0], 32));
6125}
6126
6127/// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
6128/// ones, or rewriting v4i32 / v4f32 as 2 wide ones if possible. This can be
6129/// done when every pair / quad of shuffle mask elements point to elements in
6130/// the right sequence. e.g.
6131/// vector_shuffle X, Y, <2, 3, | 10, 11, | 0, 1, | 14, 15>
6132static
6133SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
6134                                 SelectionDAG &DAG, DebugLoc dl) {
6135  MVT VT = SVOp->getValueType(0).getSimpleVT();
6136  unsigned NumElems = VT.getVectorNumElements();
6137  MVT NewVT;
6138  unsigned Scale;
6139  switch (VT.SimpleTy) {
6140  default: llvm_unreachable("Unexpected!");
6141  case MVT::v4f32:  NewVT = MVT::v2f64; Scale = 2; break;
6142  case MVT::v4i32:  NewVT = MVT::v2i64; Scale = 2; break;
6143  case MVT::v8i16:  NewVT = MVT::v4i32; Scale = 2; break;
6144  case MVT::v16i8:  NewVT = MVT::v4i32; Scale = 4; break;
6145  case MVT::v16i16: NewVT = MVT::v8i32; Scale = 2; break;
6146  case MVT::v32i8:  NewVT = MVT::v8i32; Scale = 4; break;
6147  }
6148
6149  SmallVector<int, 8> MaskVec;
6150  for (unsigned i = 0; i != NumElems; i += Scale) {
6151    int StartIdx = -1;
6152    for (unsigned j = 0; j != Scale; ++j) {
6153      int EltIdx = SVOp->getMaskElt(i+j);
6154      if (EltIdx < 0)
6155        continue;
6156      if (StartIdx < 0)
6157        StartIdx = (EltIdx / Scale);
6158      if (EltIdx != (int)(StartIdx*Scale + j))
6159        return SDValue();
6160    }
6161    MaskVec.push_back(StartIdx);
6162  }
6163
6164  SDValue V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(0));
6165  SDValue V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(1));
6166  return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
6167}
6168
6169/// getVZextMovL - Return a zero-extending vector move low node.
6170///
6171static SDValue getVZextMovL(EVT VT, EVT OpVT,
6172                            SDValue SrcOp, SelectionDAG &DAG,
6173                            const X86Subtarget *Subtarget, DebugLoc dl) {
6174  if (VT == MVT::v2f64 || VT == MVT::v4f32) {
6175    LoadSDNode *LD = NULL;
6176    if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
6177      LD = dyn_cast<LoadSDNode>(SrcOp);
6178    if (!LD) {
6179      // movssrr and movsdrr do not clear top bits. Try to use movd, movq
6180      // instead.
6181      MVT ExtVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
6182      if ((ExtVT != MVT::i64 || Subtarget->is64Bit()) &&
6183          SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
6184          SrcOp.getOperand(0).getOpcode() == ISD::BITCAST &&
6185          SrcOp.getOperand(0).getOperand(0).getValueType() == ExtVT) {
6186        // PR2108
6187        OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
6188        return DAG.getNode(ISD::BITCAST, dl, VT,
6189                           DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
6190                                       DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6191                                                   OpVT,
6192                                                   SrcOp.getOperand(0)
6193                                                          .getOperand(0))));
6194      }
6195    }
6196  }
6197
6198  return DAG.getNode(ISD::BITCAST, dl, VT,
6199                     DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
6200                                 DAG.getNode(ISD::BITCAST, dl,
6201                                             OpVT, SrcOp)));
6202}
6203
6204/// LowerVECTOR_SHUFFLE_256 - Handle all 256-bit wide vectors shuffles
6205/// which could not be matched by any known target speficic shuffle
6206static SDValue
6207LowerVECTOR_SHUFFLE_256(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
6208
6209  SDValue NewOp = Compact8x32ShuffleNode(SVOp, DAG);
6210  if (NewOp.getNode())
6211    return NewOp;
6212
6213  EVT VT = SVOp->getValueType(0);
6214
6215  unsigned NumElems = VT.getVectorNumElements();
6216  unsigned NumLaneElems = NumElems / 2;
6217
6218  DebugLoc dl = SVOp->getDebugLoc();
6219  MVT EltVT = VT.getVectorElementType().getSimpleVT();
6220  EVT NVT = MVT::getVectorVT(EltVT, NumLaneElems);
6221  SDValue Output[2];
6222
6223  SmallVector<int, 16> Mask;
6224  for (unsigned l = 0; l < 2; ++l) {
6225    // Build a shuffle mask for the output, discovering on the fly which
6226    // input vectors to use as shuffle operands (recorded in InputUsed).
6227    // If building a suitable shuffle vector proves too hard, then bail
6228    // out with UseBuildVector set.
6229    bool UseBuildVector = false;
6230    int InputUsed[2] = { -1, -1 }; // Not yet discovered.
6231    unsigned LaneStart = l * NumLaneElems;
6232    for (unsigned i = 0; i != NumLaneElems; ++i) {
6233      // The mask element.  This indexes into the input.
6234      int Idx = SVOp->getMaskElt(i+LaneStart);
6235      if (Idx < 0) {
6236        // the mask element does not index into any input vector.
6237        Mask.push_back(-1);
6238        continue;
6239      }
6240
6241      // The input vector this mask element indexes into.
6242      int Input = Idx / NumLaneElems;
6243
6244      // Turn the index into an offset from the start of the input vector.
6245      Idx -= Input * NumLaneElems;
6246
6247      // Find or create a shuffle vector operand to hold this input.
6248      unsigned OpNo;
6249      for (OpNo = 0; OpNo < array_lengthof(InputUsed); ++OpNo) {
6250        if (InputUsed[OpNo] == Input)
6251          // This input vector is already an operand.
6252          break;
6253        if (InputUsed[OpNo] < 0) {
6254          // Create a new operand for this input vector.
6255          InputUsed[OpNo] = Input;
6256          break;
6257        }
6258      }
6259
6260      if (OpNo >= array_lengthof(InputUsed)) {
6261        // More than two input vectors used!  Give up on trying to create a
6262        // shuffle vector.  Insert all elements into a BUILD_VECTOR instead.
6263        UseBuildVector = true;
6264        break;
6265      }
6266
6267      // Add the mask index for the new shuffle vector.
6268      Mask.push_back(Idx + OpNo * NumLaneElems);
6269    }
6270
6271    if (UseBuildVector) {
6272      SmallVector<SDValue, 16> SVOps;
6273      for (unsigned i = 0; i != NumLaneElems; ++i) {
6274        // The mask element.  This indexes into the input.
6275        int Idx = SVOp->getMaskElt(i+LaneStart);
6276        if (Idx < 0) {
6277          SVOps.push_back(DAG.getUNDEF(EltVT));
6278          continue;
6279        }
6280
6281        // The input vector this mask element indexes into.
6282        int Input = Idx / NumElems;
6283
6284        // Turn the index into an offset from the start of the input vector.
6285        Idx -= Input * NumElems;
6286
6287        // Extract the vector element by hand.
6288        SVOps.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
6289                                    SVOp->getOperand(Input),
6290                                    DAG.getIntPtrConstant(Idx)));
6291      }
6292
6293      // Construct the output using a BUILD_VECTOR.
6294      Output[l] = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, &SVOps[0],
6295                              SVOps.size());
6296    } else if (InputUsed[0] < 0) {
6297      // No input vectors were used! The result is undefined.
6298      Output[l] = DAG.getUNDEF(NVT);
6299    } else {
6300      SDValue Op0 = Extract128BitVector(SVOp->getOperand(InputUsed[0] / 2),
6301                                        (InputUsed[0] % 2) * NumLaneElems,
6302                                        DAG, dl);
6303      // If only one input was used, use an undefined vector for the other.
6304      SDValue Op1 = (InputUsed[1] < 0) ? DAG.getUNDEF(NVT) :
6305        Extract128BitVector(SVOp->getOperand(InputUsed[1] / 2),
6306                            (InputUsed[1] % 2) * NumLaneElems, DAG, dl);
6307      // At least one input vector was used. Create a new shuffle vector.
6308      Output[l] = DAG.getVectorShuffle(NVT, dl, Op0, Op1, &Mask[0]);
6309    }
6310
6311    Mask.clear();
6312  }
6313
6314  // Concatenate the result back
6315  return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Output[0], Output[1]);
6316}
6317
6318/// LowerVECTOR_SHUFFLE_128v4 - Handle all 128-bit wide vectors with
6319/// 4 elements, and match them with several different shuffle types.
6320static SDValue
6321LowerVECTOR_SHUFFLE_128v4(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
6322  SDValue V1 = SVOp->getOperand(0);
6323  SDValue V2 = SVOp->getOperand(1);
6324  DebugLoc dl = SVOp->getDebugLoc();
6325  EVT VT = SVOp->getValueType(0);
6326
6327  assert(VT.is128BitVector() && "Unsupported vector size");
6328
6329  std::pair<int, int> Locs[4];
6330  int Mask1[] = { -1, -1, -1, -1 };
6331  SmallVector<int, 8> PermMask(SVOp->getMask().begin(), SVOp->getMask().end());
6332
6333  unsigned NumHi = 0;
6334  unsigned NumLo = 0;
6335  for (unsigned i = 0; i != 4; ++i) {
6336    int Idx = PermMask[i];
6337    if (Idx < 0) {
6338      Locs[i] = std::make_pair(-1, -1);
6339    } else {
6340      assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
6341      if (Idx < 4) {
6342        Locs[i] = std::make_pair(0, NumLo);
6343        Mask1[NumLo] = Idx;
6344        NumLo++;
6345      } else {
6346        Locs[i] = std::make_pair(1, NumHi);
6347        if (2+NumHi < 4)
6348          Mask1[2+NumHi] = Idx;
6349        NumHi++;
6350      }
6351    }
6352  }
6353
6354  if (NumLo <= 2 && NumHi <= 2) {
6355    // If no more than two elements come from either vector. This can be
6356    // implemented with two shuffles. First shuffle gather the elements.
6357    // The second shuffle, which takes the first shuffle as both of its
6358    // vector operands, put the elements into the right order.
6359    V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6360
6361    int Mask2[] = { -1, -1, -1, -1 };
6362
6363    for (unsigned i = 0; i != 4; ++i)
6364      if (Locs[i].first != -1) {
6365        unsigned Idx = (i < 2) ? 0 : 4;
6366        Idx += Locs[i].first * 2 + Locs[i].second;
6367        Mask2[i] = Idx;
6368      }
6369
6370    return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
6371  }
6372
6373  if (NumLo == 3 || NumHi == 3) {
6374    // Otherwise, we must have three elements from one vector, call it X, and
6375    // one element from the other, call it Y.  First, use a shufps to build an
6376    // intermediate vector with the one element from Y and the element from X
6377    // that will be in the same half in the final destination (the indexes don't
6378    // matter). Then, use a shufps to build the final vector, taking the half
6379    // containing the element from Y from the intermediate, and the other half
6380    // from X.
6381    if (NumHi == 3) {
6382      // Normalize it so the 3 elements come from V1.
6383      CommuteVectorShuffleMask(PermMask, 4);
6384      std::swap(V1, V2);
6385    }
6386
6387    // Find the element from V2.
6388    unsigned HiIndex;
6389    for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
6390      int Val = PermMask[HiIndex];
6391      if (Val < 0)
6392        continue;
6393      if (Val >= 4)
6394        break;
6395    }
6396
6397    Mask1[0] = PermMask[HiIndex];
6398    Mask1[1] = -1;
6399    Mask1[2] = PermMask[HiIndex^1];
6400    Mask1[3] = -1;
6401    V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6402
6403    if (HiIndex >= 2) {
6404      Mask1[0] = PermMask[0];
6405      Mask1[1] = PermMask[1];
6406      Mask1[2] = HiIndex & 1 ? 6 : 4;
6407      Mask1[3] = HiIndex & 1 ? 4 : 6;
6408      return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6409    }
6410
6411    Mask1[0] = HiIndex & 1 ? 2 : 0;
6412    Mask1[1] = HiIndex & 1 ? 0 : 2;
6413    Mask1[2] = PermMask[2];
6414    Mask1[3] = PermMask[3];
6415    if (Mask1[2] >= 0)
6416      Mask1[2] += 4;
6417    if (Mask1[3] >= 0)
6418      Mask1[3] += 4;
6419    return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
6420  }
6421
6422  // Break it into (shuffle shuffle_hi, shuffle_lo).
6423  int LoMask[] = { -1, -1, -1, -1 };
6424  int HiMask[] = { -1, -1, -1, -1 };
6425
6426  int *MaskPtr = LoMask;
6427  unsigned MaskIdx = 0;
6428  unsigned LoIdx = 0;
6429  unsigned HiIdx = 2;
6430  for (unsigned i = 0; i != 4; ++i) {
6431    if (i == 2) {
6432      MaskPtr = HiMask;
6433      MaskIdx = 1;
6434      LoIdx = 0;
6435      HiIdx = 2;
6436    }
6437    int Idx = PermMask[i];
6438    if (Idx < 0) {
6439      Locs[i] = std::make_pair(-1, -1);
6440    } else if (Idx < 4) {
6441      Locs[i] = std::make_pair(MaskIdx, LoIdx);
6442      MaskPtr[LoIdx] = Idx;
6443      LoIdx++;
6444    } else {
6445      Locs[i] = std::make_pair(MaskIdx, HiIdx);
6446      MaskPtr[HiIdx] = Idx;
6447      HiIdx++;
6448    }
6449  }
6450
6451  SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
6452  SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
6453  int MaskOps[] = { -1, -1, -1, -1 };
6454  for (unsigned i = 0; i != 4; ++i)
6455    if (Locs[i].first != -1)
6456      MaskOps[i] = Locs[i].first * 4 + Locs[i].second;
6457  return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
6458}
6459
6460static bool MayFoldVectorLoad(SDValue V) {
6461  while (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
6462    V = V.getOperand(0);
6463
6464  if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
6465    V = V.getOperand(0);
6466  if (V.hasOneUse() && V.getOpcode() == ISD::BUILD_VECTOR &&
6467      V.getNumOperands() == 2 && V.getOperand(1).getOpcode() == ISD::UNDEF)
6468    // BUILD_VECTOR (load), undef
6469    V = V.getOperand(0);
6470
6471  return MayFoldLoad(V);
6472}
6473
6474// FIXME: the version above should always be used. Since there's
6475// a bug where several vector shuffles can't be folded because the
6476// DAG is not updated during lowering and a node claims to have two
6477// uses while it only has one, use this version, and let isel match
6478// another instruction if the load really happens to have more than
6479// one use. Remove this version after this bug get fixed.
6480// rdar://8434668, PR8156
6481static bool RelaxedMayFoldVectorLoad(SDValue V) {
6482  if (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
6483    V = V.getOperand(0);
6484  if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
6485    V = V.getOperand(0);
6486  if (ISD::isNormalLoad(V.getNode()))
6487    return true;
6488  return false;
6489}
6490
6491static
6492SDValue getMOVDDup(SDValue &Op, DebugLoc &dl, SDValue V1, SelectionDAG &DAG) {
6493  EVT VT = Op.getValueType();
6494
6495  // Canonizalize to v2f64.
6496  V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
6497  return DAG.getNode(ISD::BITCAST, dl, VT,
6498                     getTargetShuffleNode(X86ISD::MOVDDUP, dl, MVT::v2f64,
6499                                          V1, DAG));
6500}
6501
6502static
6503SDValue getMOVLowToHigh(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG,
6504                        bool HasSSE2) {
6505  SDValue V1 = Op.getOperand(0);
6506  SDValue V2 = Op.getOperand(1);
6507  EVT VT = Op.getValueType();
6508
6509  assert(VT != MVT::v2i64 && "unsupported shuffle type");
6510
6511  if (HasSSE2 && VT == MVT::v2f64)
6512    return getTargetShuffleNode(X86ISD::MOVLHPD, dl, VT, V1, V2, DAG);
6513
6514  // v4f32 or v4i32: canonizalized to v4f32 (which is legal for SSE1)
6515  return DAG.getNode(ISD::BITCAST, dl, VT,
6516                     getTargetShuffleNode(X86ISD::MOVLHPS, dl, MVT::v4f32,
6517                           DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V1),
6518                           DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V2), DAG));
6519}
6520
6521static
6522SDValue getMOVHighToLow(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG) {
6523  SDValue V1 = Op.getOperand(0);
6524  SDValue V2 = Op.getOperand(1);
6525  EVT VT = Op.getValueType();
6526
6527  assert((VT == MVT::v4i32 || VT == MVT::v4f32) &&
6528         "unsupported shuffle type");
6529
6530  if (V2.getOpcode() == ISD::UNDEF)
6531    V2 = V1;
6532
6533  // v4i32 or v4f32
6534  return getTargetShuffleNode(X86ISD::MOVHLPS, dl, VT, V1, V2, DAG);
6535}
6536
6537static
6538SDValue getMOVLP(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG, bool HasSSE2) {
6539  SDValue V1 = Op.getOperand(0);
6540  SDValue V2 = Op.getOperand(1);
6541  EVT VT = Op.getValueType();
6542  unsigned NumElems = VT.getVectorNumElements();
6543
6544  // Use MOVLPS and MOVLPD in case V1 or V2 are loads. During isel, the second
6545  // operand of these instructions is only memory, so check if there's a
6546  // potencial load folding here, otherwise use SHUFPS or MOVSD to match the
6547  // same masks.
6548  bool CanFoldLoad = false;
6549
6550  // Trivial case, when V2 comes from a load.
6551  if (MayFoldVectorLoad(V2))
6552    CanFoldLoad = true;
6553
6554  // When V1 is a load, it can be folded later into a store in isel, example:
6555  //  (store (v4f32 (X86Movlps (load addr:$src1), VR128:$src2)), addr:$src1)
6556  //    turns into:
6557  //  (MOVLPSmr addr:$src1, VR128:$src2)
6558  // So, recognize this potential and also use MOVLPS or MOVLPD
6559  else if (MayFoldVectorLoad(V1) && MayFoldIntoStore(Op))
6560    CanFoldLoad = true;
6561
6562  ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6563  if (CanFoldLoad) {
6564    if (HasSSE2 && NumElems == 2)
6565      return getTargetShuffleNode(X86ISD::MOVLPD, dl, VT, V1, V2, DAG);
6566
6567    if (NumElems == 4)
6568      // If we don't care about the second element, proceed to use movss.
6569      if (SVOp->getMaskElt(1) != -1)
6570        return getTargetShuffleNode(X86ISD::MOVLPS, dl, VT, V1, V2, DAG);
6571  }
6572
6573  // movl and movlp will both match v2i64, but v2i64 is never matched by
6574  // movl earlier because we make it strict to avoid messing with the movlp load
6575  // folding logic (see the code above getMOVLP call). Match it here then,
6576  // this is horrible, but will stay like this until we move all shuffle
6577  // matching to x86 specific nodes. Note that for the 1st condition all
6578  // types are matched with movsd.
6579  if (HasSSE2) {
6580    // FIXME: isMOVLMask should be checked and matched before getMOVLP,
6581    // as to remove this logic from here, as much as possible
6582    if (NumElems == 2 || !isMOVLMask(SVOp->getMask(), VT))
6583      return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
6584    return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
6585  }
6586
6587  assert(VT != MVT::v4i32 && "unsupported shuffle type");
6588
6589  // Invert the operand order and use SHUFPS to match it.
6590  return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V2, V1,
6591                              getShuffleSHUFImmediate(SVOp), DAG);
6592}
6593
6594// Reduce a vector shuffle to zext.
6595SDValue
6596X86TargetLowering::lowerVectorIntExtend(SDValue Op, SelectionDAG &DAG) const {
6597  // PMOVZX is only available from SSE41.
6598  if (!Subtarget->hasSSE41())
6599    return SDValue();
6600
6601  EVT VT = Op.getValueType();
6602
6603  // Only AVX2 support 256-bit vector integer extending.
6604  if (!Subtarget->hasAVX2() && VT.is256BitVector())
6605    return SDValue();
6606
6607  ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6608  DebugLoc DL = Op.getDebugLoc();
6609  SDValue V1 = Op.getOperand(0);
6610  SDValue V2 = Op.getOperand(1);
6611  unsigned NumElems = VT.getVectorNumElements();
6612
6613  // Extending is an unary operation and the element type of the source vector
6614  // won't be equal to or larger than i64.
6615  if (V2.getOpcode() != ISD::UNDEF || !VT.isInteger() ||
6616      VT.getVectorElementType() == MVT::i64)
6617    return SDValue();
6618
6619  // Find the expansion ratio, e.g. expanding from i8 to i32 has a ratio of 4.
6620  unsigned Shift = 1; // Start from 2, i.e. 1 << 1.
6621  while ((1U << Shift) < NumElems) {
6622    if (SVOp->getMaskElt(1U << Shift) == 1)
6623      break;
6624    Shift += 1;
6625    // The maximal ratio is 8, i.e. from i8 to i64.
6626    if (Shift > 3)
6627      return SDValue();
6628  }
6629
6630  // Check the shuffle mask.
6631  unsigned Mask = (1U << Shift) - 1;
6632  for (unsigned i = 0; i != NumElems; ++i) {
6633    int EltIdx = SVOp->getMaskElt(i);
6634    if ((i & Mask) != 0 && EltIdx != -1)
6635      return SDValue();
6636    if ((i & Mask) == 0 && (unsigned)EltIdx != (i >> Shift))
6637      return SDValue();
6638  }
6639
6640  unsigned NBits = VT.getVectorElementType().getSizeInBits() << Shift;
6641  EVT NeVT = EVT::getIntegerVT(*DAG.getContext(), NBits);
6642  EVT NVT = EVT::getVectorVT(*DAG.getContext(), NeVT, NumElems >> Shift);
6643
6644  if (!isTypeLegal(NVT))
6645    return SDValue();
6646
6647  // Simplify the operand as it's prepared to be fed into shuffle.
6648  unsigned SignificantBits = NVT.getSizeInBits() >> Shift;
6649  if (V1.getOpcode() == ISD::BITCAST &&
6650      V1.getOperand(0).getOpcode() == ISD::SCALAR_TO_VECTOR &&
6651      V1.getOperand(0).getOperand(0).getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
6652      V1.getOperand(0)
6653        .getOperand(0).getValueType().getSizeInBits() == SignificantBits) {
6654    // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast x)
6655    SDValue V = V1.getOperand(0).getOperand(0).getOperand(0);
6656    ConstantSDNode *CIdx =
6657      dyn_cast<ConstantSDNode>(V1.getOperand(0).getOperand(0).getOperand(1));
6658    // If it's foldable, i.e. normal load with single use, we will let code
6659    // selection to fold it. Otherwise, we will short the conversion sequence.
6660    if (CIdx && CIdx->getZExtValue() == 0 &&
6661        (!ISD::isNormalLoad(V.getNode()) || !V.hasOneUse()))
6662      V1 = DAG.getNode(ISD::BITCAST, DL, V1.getValueType(), V);
6663  }
6664
6665  return DAG.getNode(ISD::BITCAST, DL, VT,
6666                     DAG.getNode(X86ISD::VZEXT, DL, NVT, V1));
6667}
6668
6669SDValue
6670X86TargetLowering::NormalizeVectorShuffle(SDValue Op, SelectionDAG &DAG) const {
6671  ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6672  EVT VT = Op.getValueType();
6673  DebugLoc dl = Op.getDebugLoc();
6674  SDValue V1 = Op.getOperand(0);
6675  SDValue V2 = Op.getOperand(1);
6676
6677  if (isZeroShuffle(SVOp))
6678    return getZeroVector(VT, Subtarget, DAG, dl);
6679
6680  // Handle splat operations
6681  if (SVOp->isSplat()) {
6682    unsigned NumElem = VT.getVectorNumElements();
6683    int Size = VT.getSizeInBits();
6684
6685    // Use vbroadcast whenever the splat comes from a foldable load
6686    SDValue Broadcast = LowerVectorBroadcast(Op, DAG);
6687    if (Broadcast.getNode())
6688      return Broadcast;
6689
6690    // Handle splats by matching through known shuffle masks
6691    if ((Size == 128 && NumElem <= 4) ||
6692        (Size == 256 && NumElem <= 8))
6693      return SDValue();
6694
6695    // All remaning splats are promoted to target supported vector shuffles.
6696    return PromoteSplat(SVOp, DAG);
6697  }
6698
6699  // Check integer expanding shuffles.
6700  SDValue NewOp = lowerVectorIntExtend(Op, DAG);
6701  if (NewOp.getNode())
6702    return NewOp;
6703
6704  // If the shuffle can be profitably rewritten as a narrower shuffle, then
6705  // do it!
6706  if (VT == MVT::v8i16  || VT == MVT::v16i8 ||
6707      VT == MVT::v16i16 || VT == MVT::v32i8) {
6708    SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
6709    if (NewOp.getNode())
6710      return DAG.getNode(ISD::BITCAST, dl, VT, NewOp);
6711  } else if ((VT == MVT::v4i32 ||
6712             (VT == MVT::v4f32 && Subtarget->hasSSE2()))) {
6713    // FIXME: Figure out a cleaner way to do this.
6714    // Try to make use of movq to zero out the top part.
6715    if (ISD::isBuildVectorAllZeros(V2.getNode())) {
6716      SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
6717      if (NewOp.getNode()) {
6718        EVT NewVT = NewOp.getValueType();
6719        if (isCommutedMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(),
6720                               NewVT, true, false))
6721          return getVZextMovL(VT, NewVT, NewOp.getOperand(0),
6722                              DAG, Subtarget, dl);
6723      }
6724    } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
6725      SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
6726      if (NewOp.getNode()) {
6727        EVT NewVT = NewOp.getValueType();
6728        if (isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(), NewVT))
6729          return getVZextMovL(VT, NewVT, NewOp.getOperand(1),
6730                              DAG, Subtarget, dl);
6731      }
6732    }
6733  }
6734  return SDValue();
6735}
6736
6737SDValue
6738X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) const {
6739  ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6740  SDValue V1 = Op.getOperand(0);
6741  SDValue V2 = Op.getOperand(1);
6742  EVT VT = Op.getValueType();
6743  DebugLoc dl = Op.getDebugLoc();
6744  unsigned NumElems = VT.getVectorNumElements();
6745  bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
6746  bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
6747  bool V1IsSplat = false;
6748  bool V2IsSplat = false;
6749  bool HasSSE2 = Subtarget->hasSSE2();
6750  bool HasAVX    = Subtarget->hasAVX();
6751  bool HasAVX2   = Subtarget->hasAVX2();
6752  MachineFunction &MF = DAG.getMachineFunction();
6753  bool OptForSize = MF.getFunction()->getFnAttributes().
6754    hasAttribute(Attributes::OptimizeForSize);
6755
6756  assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
6757
6758  if (V1IsUndef && V2IsUndef)
6759    return DAG.getUNDEF(VT);
6760
6761  assert(!V1IsUndef && "Op 1 of shuffle should not be undef");
6762
6763  // Vector shuffle lowering takes 3 steps:
6764  //
6765  // 1) Normalize the input vectors. Here splats, zeroed vectors, profitable
6766  //    narrowing and commutation of operands should be handled.
6767  // 2) Matching of shuffles with known shuffle masks to x86 target specific
6768  //    shuffle nodes.
6769  // 3) Rewriting of unmatched masks into new generic shuffle operations,
6770  //    so the shuffle can be broken into other shuffles and the legalizer can
6771  //    try the lowering again.
6772  //
6773  // The general idea is that no vector_shuffle operation should be left to
6774  // be matched during isel, all of them must be converted to a target specific
6775  // node here.
6776
6777  // Normalize the input vectors. Here splats, zeroed vectors, profitable
6778  // narrowing and commutation of operands should be handled. The actual code
6779  // doesn't include all of those, work in progress...
6780  SDValue NewOp = NormalizeVectorShuffle(Op, DAG);
6781  if (NewOp.getNode())
6782    return NewOp;
6783
6784  SmallVector<int, 8> M(SVOp->getMask().begin(), SVOp->getMask().end());
6785
6786  // NOTE: isPSHUFDMask can also match both masks below (unpckl_undef and
6787  // unpckh_undef). Only use pshufd if speed is more important than size.
6788  if (OptForSize && isUNPCKL_v_undef_Mask(M, VT, HasAVX2))
6789    return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
6790  if (OptForSize && isUNPCKH_v_undef_Mask(M, VT, HasAVX2))
6791    return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
6792
6793  if (isMOVDDUPMask(M, VT) && Subtarget->hasSSE3() &&
6794      V2IsUndef && RelaxedMayFoldVectorLoad(V1))
6795    return getMOVDDup(Op, dl, V1, DAG);
6796
6797  if (isMOVHLPS_v_undef_Mask(M, VT))
6798    return getMOVHighToLow(Op, dl, DAG);
6799
6800  // Use to match splats
6801  if (HasSSE2 && isUNPCKHMask(M, VT, HasAVX2) && V2IsUndef &&
6802      (VT == MVT::v2f64 || VT == MVT::v2i64))
6803    return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
6804
6805  if (isPSHUFDMask(M, VT)) {
6806    // The actual implementation will match the mask in the if above and then
6807    // during isel it can match several different instructions, not only pshufd
6808    // as its name says, sad but true, emulate the behavior for now...
6809    if (isMOVDDUPMask(M, VT) && ((VT == MVT::v4f32 || VT == MVT::v2i64)))
6810      return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V1, DAG);
6811
6812    unsigned TargetMask = getShuffleSHUFImmediate(SVOp);
6813
6814    if (HasAVX && (VT == MVT::v4f32 || VT == MVT::v2f64))
6815      return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1, TargetMask, DAG);
6816
6817    if (HasSSE2 && (VT == MVT::v4f32 || VT == MVT::v4i32))
6818      return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1, TargetMask, DAG);
6819
6820    return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V1,
6821                                TargetMask, DAG);
6822  }
6823
6824  // Check if this can be converted into a logical shift.
6825  bool isLeft = false;
6826  unsigned ShAmt = 0;
6827  SDValue ShVal;
6828  bool isShift = HasSSE2 && isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
6829  if (isShift && ShVal.hasOneUse()) {
6830    // If the shifted value has multiple uses, it may be cheaper to use
6831    // v_set0 + movlhps or movhlps, etc.
6832    EVT EltVT = VT.getVectorElementType();
6833    ShAmt *= EltVT.getSizeInBits();
6834    return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
6835  }
6836
6837  if (isMOVLMask(M, VT)) {
6838    if (ISD::isBuildVectorAllZeros(V1.getNode()))
6839      return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
6840    if (!isMOVLPMask(M, VT)) {
6841      if (HasSSE2 && (VT == MVT::v2i64 || VT == MVT::v2f64))
6842        return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
6843
6844      if (VT == MVT::v4i32 || VT == MVT::v4f32)
6845        return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
6846    }
6847  }
6848
6849  // FIXME: fold these into legal mask.
6850  if (isMOVLHPSMask(M, VT) && !isUNPCKLMask(M, VT, HasAVX2))
6851    return getMOVLowToHigh(Op, dl, DAG, HasSSE2);
6852
6853  if (isMOVHLPSMask(M, VT))
6854    return getMOVHighToLow(Op, dl, DAG);
6855
6856  if (V2IsUndef && isMOVSHDUPMask(M, VT, Subtarget))
6857    return getTargetShuffleNode(X86ISD::MOVSHDUP, dl, VT, V1, DAG);
6858
6859  if (V2IsUndef && isMOVSLDUPMask(M, VT, Subtarget))
6860    return getTargetShuffleNode(X86ISD::MOVSLDUP, dl, VT, V1, DAG);
6861
6862  if (isMOVLPMask(M, VT))
6863    return getMOVLP(Op, dl, DAG, HasSSE2);
6864
6865  if (ShouldXformToMOVHLPS(M, VT) ||
6866      ShouldXformToMOVLP(V1.getNode(), V2.getNode(), M, VT))
6867    return CommuteVectorShuffle(SVOp, DAG);
6868
6869  if (isShift) {
6870    // No better options. Use a vshldq / vsrldq.
6871    EVT EltVT = VT.getVectorElementType();
6872    ShAmt *= EltVT.getSizeInBits();
6873    return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
6874  }
6875
6876  bool Commuted = false;
6877  // FIXME: This should also accept a bitcast of a splat?  Be careful, not
6878  // 1,1,1,1 -> v8i16 though.
6879  V1IsSplat = isSplatVector(V1.getNode());
6880  V2IsSplat = isSplatVector(V2.getNode());
6881
6882  // Canonicalize the splat or undef, if present, to be on the RHS.
6883  if (!V2IsUndef && V1IsSplat && !V2IsSplat) {
6884    CommuteVectorShuffleMask(M, NumElems);
6885    std::swap(V1, V2);
6886    std::swap(V1IsSplat, V2IsSplat);
6887    Commuted = true;
6888  }
6889
6890  if (isCommutedMOVLMask(M, VT, V2IsSplat, V2IsUndef)) {
6891    // Shuffling low element of v1 into undef, just return v1.
6892    if (V2IsUndef)
6893      return V1;
6894    // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
6895    // the instruction selector will not match, so get a canonical MOVL with
6896    // swapped operands to undo the commute.
6897    return getMOVL(DAG, dl, VT, V2, V1);
6898  }
6899
6900  if (isUNPCKLMask(M, VT, HasAVX2))
6901    return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
6902
6903  if (isUNPCKHMask(M, VT, HasAVX2))
6904    return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
6905
6906  if (V2IsSplat) {
6907    // Normalize mask so all entries that point to V2 points to its first
6908    // element then try to match unpck{h|l} again. If match, return a
6909    // new vector_shuffle with the corrected mask.p
6910    SmallVector<int, 8> NewMask(M.begin(), M.end());
6911    NormalizeMask(NewMask, NumElems);
6912    if (isUNPCKLMask(NewMask, VT, HasAVX2, true))
6913      return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
6914    if (isUNPCKHMask(NewMask, VT, HasAVX2, true))
6915      return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
6916  }
6917
6918  if (Commuted) {
6919    // Commute is back and try unpck* again.
6920    // FIXME: this seems wrong.
6921    CommuteVectorShuffleMask(M, NumElems);
6922    std::swap(V1, V2);
6923    std::swap(V1IsSplat, V2IsSplat);
6924    Commuted = false;
6925
6926    if (isUNPCKLMask(M, VT, HasAVX2))
6927      return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
6928
6929    if (isUNPCKHMask(M, VT, HasAVX2))
6930      return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
6931  }
6932
6933  // Normalize the node to match x86 shuffle ops if needed
6934  if (!V2IsUndef && (isSHUFPMask(M, VT, HasAVX, /* Commuted */ true)))
6935    return CommuteVectorShuffle(SVOp, DAG);
6936
6937  // The checks below are all present in isShuffleMaskLegal, but they are
6938  // inlined here right now to enable us to directly emit target specific
6939  // nodes, and remove one by one until they don't return Op anymore.
6940
6941  if (isPALIGNRMask(M, VT, Subtarget))
6942    return getTargetShuffleNode(X86ISD::PALIGN, dl, VT, V1, V2,
6943                                getShufflePALIGNRImmediate(SVOp),
6944                                DAG);
6945
6946  if (ShuffleVectorSDNode::isSplatMask(&M[0], VT) &&
6947      SVOp->getSplatIndex() == 0 && V2IsUndef) {
6948    if (VT == MVT::v2f64 || VT == MVT::v2i64)
6949      return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
6950  }
6951
6952  if (isPSHUFHWMask(M, VT, HasAVX2))
6953    return getTargetShuffleNode(X86ISD::PSHUFHW, dl, VT, V1,
6954                                getShufflePSHUFHWImmediate(SVOp),
6955                                DAG);
6956
6957  if (isPSHUFLWMask(M, VT, HasAVX2))
6958    return getTargetShuffleNode(X86ISD::PSHUFLW, dl, VT, V1,
6959                                getShufflePSHUFLWImmediate(SVOp),
6960                                DAG);
6961
6962  if (isSHUFPMask(M, VT, HasAVX))
6963    return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V2,
6964                                getShuffleSHUFImmediate(SVOp), DAG);
6965
6966  if (isUNPCKL_v_undef_Mask(M, VT, HasAVX2))
6967    return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
6968  if (isUNPCKH_v_undef_Mask(M, VT, HasAVX2))
6969    return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
6970
6971  //===--------------------------------------------------------------------===//
6972  // Generate target specific nodes for 128 or 256-bit shuffles only
6973  // supported in the AVX instruction set.
6974  //
6975
6976  // Handle VMOVDDUPY permutations
6977  if (V2IsUndef && isMOVDDUPYMask(M, VT, HasAVX))
6978    return getTargetShuffleNode(X86ISD::MOVDDUP, dl, VT, V1, DAG);
6979
6980  // Handle VPERMILPS/D* permutations
6981  if (isVPERMILPMask(M, VT, HasAVX)) {
6982    if (HasAVX2 && VT == MVT::v8i32)
6983      return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1,
6984                                  getShuffleSHUFImmediate(SVOp), DAG);
6985    return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1,
6986                                getShuffleSHUFImmediate(SVOp), DAG);
6987  }
6988
6989  // Handle VPERM2F128/VPERM2I128 permutations
6990  if (isVPERM2X128Mask(M, VT, HasAVX))
6991    return getTargetShuffleNode(X86ISD::VPERM2X128, dl, VT, V1,
6992                                V2, getShuffleVPERM2X128Immediate(SVOp), DAG);
6993
6994  SDValue BlendOp = LowerVECTOR_SHUFFLEtoBlend(SVOp, Subtarget, DAG);
6995  if (BlendOp.getNode())
6996    return BlendOp;
6997
6998  if (V2IsUndef && HasAVX2 && (VT == MVT::v8i32 || VT == MVT::v8f32)) {
6999    SmallVector<SDValue, 8> permclMask;
7000    for (unsigned i = 0; i != 8; ++i) {
7001      permclMask.push_back(DAG.getConstant((M[i]>=0) ? M[i] : 0, MVT::i32));
7002    }
7003    SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32,
7004                               &permclMask[0], 8);
7005    // Bitcast is for VPERMPS since mask is v8i32 but node takes v8f32
7006    return DAG.getNode(X86ISD::VPERMV, dl, VT,
7007                       DAG.getNode(ISD::BITCAST, dl, VT, Mask), V1);
7008  }
7009
7010  if (V2IsUndef && HasAVX2 && (VT == MVT::v4i64 || VT == MVT::v4f64))
7011    return getTargetShuffleNode(X86ISD::VPERMI, dl, VT, V1,
7012                                getShuffleCLImmediate(SVOp), DAG);
7013
7014
7015  //===--------------------------------------------------------------------===//
7016  // Since no target specific shuffle was selected for this generic one,
7017  // lower it into other known shuffles. FIXME: this isn't true yet, but
7018  // this is the plan.
7019  //
7020
7021  // Handle v8i16 specifically since SSE can do byte extraction and insertion.
7022  if (VT == MVT::v8i16) {
7023    SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(Op, Subtarget, DAG);
7024    if (NewOp.getNode())
7025      return NewOp;
7026  }
7027
7028  if (VT == MVT::v16i8) {
7029    SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, DAG, *this);
7030    if (NewOp.getNode())
7031      return NewOp;
7032  }
7033
7034  if (VT == MVT::v32i8) {
7035    SDValue NewOp = LowerVECTOR_SHUFFLEv32i8(SVOp, Subtarget, DAG);
7036    if (NewOp.getNode())
7037      return NewOp;
7038  }
7039
7040  // Handle all 128-bit wide vectors with 4 elements, and match them with
7041  // several different shuffle types.
7042  if (NumElems == 4 && VT.is128BitVector())
7043    return LowerVECTOR_SHUFFLE_128v4(SVOp, DAG);
7044
7045  // Handle general 256-bit shuffles
7046  if (VT.is256BitVector())
7047    return LowerVECTOR_SHUFFLE_256(SVOp, DAG);
7048
7049  return SDValue();
7050}
7051
7052SDValue
7053X86TargetLowering::LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op,
7054                                                SelectionDAG &DAG) const {
7055  EVT VT = Op.getValueType();
7056  DebugLoc dl = Op.getDebugLoc();
7057
7058  if (!Op.getOperand(0).getValueType().is128BitVector())
7059    return SDValue();
7060
7061  if (VT.getSizeInBits() == 8) {
7062    SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
7063                                  Op.getOperand(0), Op.getOperand(1));
7064    SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
7065                                  DAG.getValueType(VT));
7066    return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
7067  }
7068
7069  if (VT.getSizeInBits() == 16) {
7070    unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7071    // If Idx is 0, it's cheaper to do a move instead of a pextrw.
7072    if (Idx == 0)
7073      return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
7074                         DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
7075                                     DAG.getNode(ISD::BITCAST, dl,
7076                                                 MVT::v4i32,
7077                                                 Op.getOperand(0)),
7078                                     Op.getOperand(1)));
7079    SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
7080                                  Op.getOperand(0), Op.getOperand(1));
7081    SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
7082                                  DAG.getValueType(VT));
7083    return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
7084  }
7085
7086  if (VT == MVT::f32) {
7087    // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
7088    // the result back to FR32 register. It's only worth matching if the
7089    // result has a single use which is a store or a bitcast to i32.  And in
7090    // the case of a store, it's not worth it if the index is a constant 0,
7091    // because a MOVSSmr can be used instead, which is smaller and faster.
7092    if (!Op.hasOneUse())
7093      return SDValue();
7094    SDNode *User = *Op.getNode()->use_begin();
7095    if ((User->getOpcode() != ISD::STORE ||
7096         (isa<ConstantSDNode>(Op.getOperand(1)) &&
7097          cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
7098        (User->getOpcode() != ISD::BITCAST ||
7099         User->getValueType(0) != MVT::i32))
7100      return SDValue();
7101    SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
7102                                  DAG.getNode(ISD::BITCAST, dl, MVT::v4i32,
7103                                              Op.getOperand(0)),
7104                                              Op.getOperand(1));
7105    return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Extract);
7106  }
7107
7108  if (VT == MVT::i32 || VT == MVT::i64) {
7109    // ExtractPS/pextrq works with constant index.
7110    if (isa<ConstantSDNode>(Op.getOperand(1)))
7111      return Op;
7112  }
7113  return SDValue();
7114}
7115
7116
7117SDValue
7118X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
7119                                           SelectionDAG &DAG) const {
7120  if (!isa<ConstantSDNode>(Op.getOperand(1)))
7121    return SDValue();
7122
7123  SDValue Vec = Op.getOperand(0);
7124  EVT VecVT = Vec.getValueType();
7125
7126  // If this is a 256-bit vector result, first extract the 128-bit vector and
7127  // then extract the element from the 128-bit vector.
7128  if (VecVT.is256BitVector()) {
7129    DebugLoc dl = Op.getNode()->getDebugLoc();
7130    unsigned NumElems = VecVT.getVectorNumElements();
7131    SDValue Idx = Op.getOperand(1);
7132    unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
7133
7134    // Get the 128-bit vector.
7135    Vec = Extract128BitVector(Vec, IdxVal, DAG, dl);
7136
7137    if (IdxVal >= NumElems/2)
7138      IdxVal -= NumElems/2;
7139    return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
7140                       DAG.getConstant(IdxVal, MVT::i32));
7141  }
7142
7143  assert(VecVT.is128BitVector() && "Unexpected vector length");
7144
7145  if (Subtarget->hasSSE41()) {
7146    SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
7147    if (Res.getNode())
7148      return Res;
7149  }
7150
7151  EVT VT = Op.getValueType();
7152  DebugLoc dl = Op.getDebugLoc();
7153  // TODO: handle v16i8.
7154  if (VT.getSizeInBits() == 16) {
7155    SDValue Vec = Op.getOperand(0);
7156    unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7157    if (Idx == 0)
7158      return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
7159                         DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
7160                                     DAG.getNode(ISD::BITCAST, dl,
7161                                                 MVT::v4i32, Vec),
7162                                     Op.getOperand(1)));
7163    // Transform it so it match pextrw which produces a 32-bit result.
7164    EVT EltVT = MVT::i32;
7165    SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
7166                                  Op.getOperand(0), Op.getOperand(1));
7167    SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
7168                                  DAG.getValueType(VT));
7169    return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
7170  }
7171
7172  if (VT.getSizeInBits() == 32) {
7173    unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7174    if (Idx == 0)
7175      return Op;
7176
7177    // SHUFPS the element to the lowest double word, then movss.
7178    int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
7179    EVT VVT = Op.getOperand(0).getValueType();
7180    SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
7181                                       DAG.getUNDEF(VVT), Mask);
7182    return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
7183                       DAG.getIntPtrConstant(0));
7184  }
7185
7186  if (VT.getSizeInBits() == 64) {
7187    // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
7188    // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
7189    //        to match extract_elt for f64.
7190    unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7191    if (Idx == 0)
7192      return Op;
7193
7194    // UNPCKHPD the element to the lowest double word, then movsd.
7195    // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
7196    // to a f64mem, the whole operation is folded into a single MOVHPDmr.
7197    int Mask[2] = { 1, -1 };
7198    EVT VVT = Op.getOperand(0).getValueType();
7199    SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
7200                                       DAG.getUNDEF(VVT), Mask);
7201    return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
7202                       DAG.getIntPtrConstant(0));
7203  }
7204
7205  return SDValue();
7206}
7207
7208SDValue
7209X86TargetLowering::LowerINSERT_VECTOR_ELT_SSE4(SDValue Op,
7210                                               SelectionDAG &DAG) const {
7211  EVT VT = Op.getValueType();
7212  EVT EltVT = VT.getVectorElementType();
7213  DebugLoc dl = Op.getDebugLoc();
7214
7215  SDValue N0 = Op.getOperand(0);
7216  SDValue N1 = Op.getOperand(1);
7217  SDValue N2 = Op.getOperand(2);
7218
7219  if (!VT.is128BitVector())
7220    return SDValue();
7221
7222  if ((EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) &&
7223      isa<ConstantSDNode>(N2)) {
7224    unsigned Opc;
7225    if (VT == MVT::v8i16)
7226      Opc = X86ISD::PINSRW;
7227    else if (VT == MVT::v16i8)
7228      Opc = X86ISD::PINSRB;
7229    else
7230      Opc = X86ISD::PINSRB;
7231
7232    // Transform it so it match pinsr{b,w} which expects a GR32 as its second
7233    // argument.
7234    if (N1.getValueType() != MVT::i32)
7235      N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
7236    if (N2.getValueType() != MVT::i32)
7237      N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
7238    return DAG.getNode(Opc, dl, VT, N0, N1, N2);
7239  }
7240
7241  if (EltVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
7242    // Bits [7:6] of the constant are the source select.  This will always be
7243    //  zero here.  The DAG Combiner may combine an extract_elt index into these
7244    //  bits.  For example (insert (extract, 3), 2) could be matched by putting
7245    //  the '3' into bits [7:6] of X86ISD::INSERTPS.
7246    // Bits [5:4] of the constant are the destination select.  This is the
7247    //  value of the incoming immediate.
7248    // Bits [3:0] of the constant are the zero mask.  The DAG Combiner may
7249    //   combine either bitwise AND or insert of float 0.0 to set these bits.
7250    N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
7251    // Create this as a scalar to vector..
7252    N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
7253    return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
7254  }
7255
7256  if ((EltVT == MVT::i32 || EltVT == MVT::i64) && isa<ConstantSDNode>(N2)) {
7257    // PINSR* works with constant index.
7258    return Op;
7259  }
7260  return SDValue();
7261}
7262
7263SDValue
7264X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) const {
7265  EVT VT = Op.getValueType();
7266  EVT EltVT = VT.getVectorElementType();
7267
7268  DebugLoc dl = Op.getDebugLoc();
7269  SDValue N0 = Op.getOperand(0);
7270  SDValue N1 = Op.getOperand(1);
7271  SDValue N2 = Op.getOperand(2);
7272
7273  // If this is a 256-bit vector result, first extract the 128-bit vector,
7274  // insert the element into the extracted half and then place it back.
7275  if (VT.is256BitVector()) {
7276    if (!isa<ConstantSDNode>(N2))
7277      return SDValue();
7278
7279    // Get the desired 128-bit vector half.
7280    unsigned NumElems = VT.getVectorNumElements();
7281    unsigned IdxVal = cast<ConstantSDNode>(N2)->getZExtValue();
7282    SDValue V = Extract128BitVector(N0, IdxVal, DAG, dl);
7283
7284    // Insert the element into the desired half.
7285    bool Upper = IdxVal >= NumElems/2;
7286    V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V, N1,
7287                 DAG.getConstant(Upper ? IdxVal-NumElems/2 : IdxVal, MVT::i32));
7288
7289    // Insert the changed part back to the 256-bit vector
7290    return Insert128BitVector(N0, V, IdxVal, DAG, dl);
7291  }
7292
7293  if (Subtarget->hasSSE41())
7294    return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
7295
7296  if (EltVT == MVT::i8)
7297    return SDValue();
7298
7299  if (EltVT.getSizeInBits() == 16 && isa<ConstantSDNode>(N2)) {
7300    // Transform it so it match pinsrw which expects a 16-bit value in a GR32
7301    // as its second argument.
7302    if (N1.getValueType() != MVT::i32)
7303      N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
7304    if (N2.getValueType() != MVT::i32)
7305      N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
7306    return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
7307  }
7308  return SDValue();
7309}
7310
7311static SDValue LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
7312  LLVMContext *Context = DAG.getContext();
7313  DebugLoc dl = Op.getDebugLoc();
7314  EVT OpVT = Op.getValueType();
7315
7316  // If this is a 256-bit vector result, first insert into a 128-bit
7317  // vector and then insert into the 256-bit vector.
7318  if (!OpVT.is128BitVector()) {
7319    // Insert into a 128-bit vector.
7320    EVT VT128 = EVT::getVectorVT(*Context,
7321                                 OpVT.getVectorElementType(),
7322                                 OpVT.getVectorNumElements() / 2);
7323
7324    Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
7325
7326    // Insert the 128-bit vector.
7327    return Insert128BitVector(DAG.getUNDEF(OpVT), Op, 0, DAG, dl);
7328  }
7329
7330  if (OpVT == MVT::v1i64 &&
7331      Op.getOperand(0).getValueType() == MVT::i64)
7332    return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
7333
7334  SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
7335  assert(OpVT.is128BitVector() && "Expected an SSE type!");
7336  return DAG.getNode(ISD::BITCAST, dl, OpVT,
7337                     DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,AnyExt));
7338}
7339
7340// Lower a node with an EXTRACT_SUBVECTOR opcode.  This may result in
7341// a simple subregister reference or explicit instructions to grab
7342// upper bits of a vector.
7343static SDValue LowerEXTRACT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
7344                                      SelectionDAG &DAG) {
7345  if (Subtarget->hasAVX()) {
7346    DebugLoc dl = Op.getNode()->getDebugLoc();
7347    SDValue Vec = Op.getNode()->getOperand(0);
7348    SDValue Idx = Op.getNode()->getOperand(1);
7349
7350    if (Op.getNode()->getValueType(0).is128BitVector() &&
7351        Vec.getNode()->getValueType(0).is256BitVector() &&
7352        isa<ConstantSDNode>(Idx)) {
7353      unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
7354      return Extract128BitVector(Vec, IdxVal, DAG, dl);
7355    }
7356  }
7357  return SDValue();
7358}
7359
7360// Lower a node with an INSERT_SUBVECTOR opcode.  This may result in a
7361// simple superregister reference or explicit instructions to insert
7362// the upper bits of a vector.
7363static SDValue LowerINSERT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
7364                                     SelectionDAG &DAG) {
7365  if (Subtarget->hasAVX()) {
7366    DebugLoc dl = Op.getNode()->getDebugLoc();
7367    SDValue Vec = Op.getNode()->getOperand(0);
7368    SDValue SubVec = Op.getNode()->getOperand(1);
7369    SDValue Idx = Op.getNode()->getOperand(2);
7370
7371    if (Op.getNode()->getValueType(0).is256BitVector() &&
7372        SubVec.getNode()->getValueType(0).is128BitVector() &&
7373        isa<ConstantSDNode>(Idx)) {
7374      unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
7375      return Insert128BitVector(Vec, SubVec, IdxVal, DAG, dl);
7376    }
7377  }
7378  return SDValue();
7379}
7380
7381// ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
7382// their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
7383// one of the above mentioned nodes. It has to be wrapped because otherwise
7384// Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
7385// be used to form addressing mode. These wrapped nodes will be selected
7386// into MOV32ri.
7387SDValue
7388X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
7389  ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
7390
7391  // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7392  // global base reg.
7393  unsigned char OpFlag = 0;
7394  unsigned WrapperKind = X86ISD::Wrapper;
7395  CodeModel::Model M = getTargetMachine().getCodeModel();
7396
7397  if (Subtarget->isPICStyleRIPRel() &&
7398      (M == CodeModel::Small || M == CodeModel::Kernel))
7399    WrapperKind = X86ISD::WrapperRIP;
7400  else if (Subtarget->isPICStyleGOT())
7401    OpFlag = X86II::MO_GOTOFF;
7402  else if (Subtarget->isPICStyleStubPIC())
7403    OpFlag = X86II::MO_PIC_BASE_OFFSET;
7404
7405  SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
7406                                             CP->getAlignment(),
7407                                             CP->getOffset(), OpFlag);
7408  DebugLoc DL = CP->getDebugLoc();
7409  Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7410  // With PIC, the address is actually $g + Offset.
7411  if (OpFlag) {
7412    Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7413                         DAG.getNode(X86ISD::GlobalBaseReg,
7414                                     DebugLoc(), getPointerTy()),
7415                         Result);
7416  }
7417
7418  return Result;
7419}
7420
7421SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
7422  JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
7423
7424  // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7425  // global base reg.
7426  unsigned char OpFlag = 0;
7427  unsigned WrapperKind = X86ISD::Wrapper;
7428  CodeModel::Model M = getTargetMachine().getCodeModel();
7429
7430  if (Subtarget->isPICStyleRIPRel() &&
7431      (M == CodeModel::Small || M == CodeModel::Kernel))
7432    WrapperKind = X86ISD::WrapperRIP;
7433  else if (Subtarget->isPICStyleGOT())
7434    OpFlag = X86II::MO_GOTOFF;
7435  else if (Subtarget->isPICStyleStubPIC())
7436    OpFlag = X86II::MO_PIC_BASE_OFFSET;
7437
7438  SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
7439                                          OpFlag);
7440  DebugLoc DL = JT->getDebugLoc();
7441  Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7442
7443  // With PIC, the address is actually $g + Offset.
7444  if (OpFlag)
7445    Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7446                         DAG.getNode(X86ISD::GlobalBaseReg,
7447                                     DebugLoc(), getPointerTy()),
7448                         Result);
7449
7450  return Result;
7451}
7452
7453SDValue
7454X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
7455  const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
7456
7457  // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7458  // global base reg.
7459  unsigned char OpFlag = 0;
7460  unsigned WrapperKind = X86ISD::Wrapper;
7461  CodeModel::Model M = getTargetMachine().getCodeModel();
7462
7463  if (Subtarget->isPICStyleRIPRel() &&
7464      (M == CodeModel::Small || M == CodeModel::Kernel)) {
7465    if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
7466      OpFlag = X86II::MO_GOTPCREL;
7467    WrapperKind = X86ISD::WrapperRIP;
7468  } else if (Subtarget->isPICStyleGOT()) {
7469    OpFlag = X86II::MO_GOT;
7470  } else if (Subtarget->isPICStyleStubPIC()) {
7471    OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
7472  } else if (Subtarget->isPICStyleStubNoDynamic()) {
7473    OpFlag = X86II::MO_DARWIN_NONLAZY;
7474  }
7475
7476  SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
7477
7478  DebugLoc DL = Op.getDebugLoc();
7479  Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7480
7481
7482  // With PIC, the address is actually $g + Offset.
7483  if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
7484      !Subtarget->is64Bit()) {
7485    Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7486                         DAG.getNode(X86ISD::GlobalBaseReg,
7487                                     DebugLoc(), getPointerTy()),
7488                         Result);
7489  }
7490
7491  // For symbols that require a load from a stub to get the address, emit the
7492  // load.
7493  if (isGlobalStubReference(OpFlag))
7494    Result = DAG.getLoad(getPointerTy(), DL, DAG.getEntryNode(), Result,
7495                         MachinePointerInfo::getGOT(), false, false, false, 0);
7496
7497  return Result;
7498}
7499
7500SDValue
7501X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
7502  // Create the TargetBlockAddressAddress node.
7503  unsigned char OpFlags =
7504    Subtarget->ClassifyBlockAddressReference();
7505  CodeModel::Model M = getTargetMachine().getCodeModel();
7506  const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
7507  int64_t Offset = cast<BlockAddressSDNode>(Op)->getOffset();
7508  DebugLoc dl = Op.getDebugLoc();
7509  SDValue Result = DAG.getTargetBlockAddress(BA, getPointerTy(), Offset,
7510                                             OpFlags);
7511
7512  if (Subtarget->isPICStyleRIPRel() &&
7513      (M == CodeModel::Small || M == CodeModel::Kernel))
7514    Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
7515  else
7516    Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
7517
7518  // With PIC, the address is actually $g + Offset.
7519  if (isGlobalRelativeToPICBase(OpFlags)) {
7520    Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
7521                         DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
7522                         Result);
7523  }
7524
7525  return Result;
7526}
7527
7528SDValue
7529X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, DebugLoc dl,
7530                                      int64_t Offset,
7531                                      SelectionDAG &DAG) const {
7532  // Create the TargetGlobalAddress node, folding in the constant
7533  // offset if it is legal.
7534  unsigned char OpFlags =
7535    Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
7536  CodeModel::Model M = getTargetMachine().getCodeModel();
7537  SDValue Result;
7538  if (OpFlags == X86II::MO_NO_FLAG &&
7539      X86::isOffsetSuitableForCodeModel(Offset, M)) {
7540    // A direct static reference to a global.
7541    Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
7542    Offset = 0;
7543  } else {
7544    Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
7545  }
7546
7547  if (Subtarget->isPICStyleRIPRel() &&
7548      (M == CodeModel::Small || M == CodeModel::Kernel))
7549    Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
7550  else
7551    Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
7552
7553  // With PIC, the address is actually $g + Offset.
7554  if (isGlobalRelativeToPICBase(OpFlags)) {
7555    Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
7556                         DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
7557                         Result);
7558  }
7559
7560  // For globals that require a load from a stub to get the address, emit the
7561  // load.
7562  if (isGlobalStubReference(OpFlags))
7563    Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
7564                         MachinePointerInfo::getGOT(), false, false, false, 0);
7565
7566  // If there was a non-zero offset that we didn't fold, create an explicit
7567  // addition for it.
7568  if (Offset != 0)
7569    Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
7570                         DAG.getConstant(Offset, getPointerTy()));
7571
7572  return Result;
7573}
7574
7575SDValue
7576X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
7577  const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
7578  int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
7579  return LowerGlobalAddress(GV, Op.getDebugLoc(), Offset, DAG);
7580}
7581
7582static SDValue
7583GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
7584           SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
7585           unsigned char OperandFlags, bool LocalDynamic = false) {
7586  MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7587  SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7588  DebugLoc dl = GA->getDebugLoc();
7589  SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7590                                           GA->getValueType(0),
7591                                           GA->getOffset(),
7592                                           OperandFlags);
7593
7594  X86ISD::NodeType CallType = LocalDynamic ? X86ISD::TLSBASEADDR
7595                                           : X86ISD::TLSADDR;
7596
7597  if (InFlag) {
7598    SDValue Ops[] = { Chain,  TGA, *InFlag };
7599    Chain = DAG.getNode(CallType, dl, NodeTys, Ops, 3);
7600  } else {
7601    SDValue Ops[]  = { Chain, TGA };
7602    Chain = DAG.getNode(CallType, dl, NodeTys, Ops, 2);
7603  }
7604
7605  // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
7606  MFI->setAdjustsStack(true);
7607
7608  SDValue Flag = Chain.getValue(1);
7609  return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
7610}
7611
7612// Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
7613static SDValue
7614LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7615                                const EVT PtrVT) {
7616  SDValue InFlag;
7617  DebugLoc dl = GA->getDebugLoc();  // ? function entry point might be better
7618  SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
7619                                   DAG.getNode(X86ISD::GlobalBaseReg,
7620                                               DebugLoc(), PtrVT), InFlag);
7621  InFlag = Chain.getValue(1);
7622
7623  return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
7624}
7625
7626// Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
7627static SDValue
7628LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7629                                const EVT PtrVT) {
7630  return GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT,
7631                    X86::RAX, X86II::MO_TLSGD);
7632}
7633
7634static SDValue LowerToTLSLocalDynamicModel(GlobalAddressSDNode *GA,
7635                                           SelectionDAG &DAG,
7636                                           const EVT PtrVT,
7637                                           bool is64Bit) {
7638  DebugLoc dl = GA->getDebugLoc();
7639
7640  // Get the start address of the TLS block for this module.
7641  X86MachineFunctionInfo* MFI = DAG.getMachineFunction()
7642      .getInfo<X86MachineFunctionInfo>();
7643  MFI->incNumLocalDynamicTLSAccesses();
7644
7645  SDValue Base;
7646  if (is64Bit) {
7647    Base = GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT, X86::RAX,
7648                      X86II::MO_TLSLD, /*LocalDynamic=*/true);
7649  } else {
7650    SDValue InFlag;
7651    SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
7652        DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), PtrVT), InFlag);
7653    InFlag = Chain.getValue(1);
7654    Base = GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX,
7655                      X86II::MO_TLSLDM, /*LocalDynamic=*/true);
7656  }
7657
7658  // Note: the CleanupLocalDynamicTLSPass will remove redundant computations
7659  // of Base.
7660
7661  // Build x@dtpoff.
7662  unsigned char OperandFlags = X86II::MO_DTPOFF;
7663  unsigned WrapperKind = X86ISD::Wrapper;
7664  SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7665                                           GA->getValueType(0),
7666                                           GA->getOffset(), OperandFlags);
7667  SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
7668
7669  // Add x@dtpoff with the base.
7670  return DAG.getNode(ISD::ADD, dl, PtrVT, Offset, Base);
7671}
7672
7673// Lower ISD::GlobalTLSAddress using the "initial exec" or "local exec" model.
7674static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7675                                   const EVT PtrVT, TLSModel::Model model,
7676                                   bool is64Bit, bool isPIC) {
7677  DebugLoc dl = GA->getDebugLoc();
7678
7679  // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
7680  Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
7681                                                         is64Bit ? 257 : 256));
7682
7683  SDValue ThreadPointer = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
7684                                      DAG.getIntPtrConstant(0),
7685                                      MachinePointerInfo(Ptr),
7686                                      false, false, false, 0);
7687
7688  unsigned char OperandFlags = 0;
7689  // Most TLS accesses are not RIP relative, even on x86-64.  One exception is
7690  // initialexec.
7691  unsigned WrapperKind = X86ISD::Wrapper;
7692  if (model == TLSModel::LocalExec) {
7693    OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
7694  } else if (model == TLSModel::InitialExec) {
7695    if (is64Bit) {
7696      OperandFlags = X86II::MO_GOTTPOFF;
7697      WrapperKind = X86ISD::WrapperRIP;
7698    } else {
7699      OperandFlags = isPIC ? X86II::MO_GOTNTPOFF : X86II::MO_INDNTPOFF;
7700    }
7701  } else {
7702    llvm_unreachable("Unexpected model");
7703  }
7704
7705  // emit "addl x@ntpoff,%eax" (local exec)
7706  // or "addl x@indntpoff,%eax" (initial exec)
7707  // or "addl x@gotntpoff(%ebx) ,%eax" (initial exec, 32-bit pic)
7708  SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7709                                           GA->getValueType(0),
7710                                           GA->getOffset(), OperandFlags);
7711  SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
7712
7713  if (model == TLSModel::InitialExec) {
7714    if (isPIC && !is64Bit) {
7715      Offset = DAG.getNode(ISD::ADD, dl, PtrVT,
7716                          DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), PtrVT),
7717                           Offset);
7718    }
7719
7720    Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
7721                         MachinePointerInfo::getGOT(), false, false, false,
7722                         0);
7723  }
7724
7725  // The address of the thread local variable is the add of the thread
7726  // pointer with the offset of the variable.
7727  return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
7728}
7729
7730SDValue
7731X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
7732
7733  GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
7734  const GlobalValue *GV = GA->getGlobal();
7735
7736  if (Subtarget->isTargetELF()) {
7737    TLSModel::Model model = getTargetMachine().getTLSModel(GV);
7738
7739    switch (model) {
7740      case TLSModel::GeneralDynamic:
7741        if (Subtarget->is64Bit())
7742          return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
7743        return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
7744      case TLSModel::LocalDynamic:
7745        return LowerToTLSLocalDynamicModel(GA, DAG, getPointerTy(),
7746                                           Subtarget->is64Bit());
7747      case TLSModel::InitialExec:
7748      case TLSModel::LocalExec:
7749        return LowerToTLSExecModel(GA, DAG, getPointerTy(), model,
7750                                   Subtarget->is64Bit(),
7751                         getTargetMachine().getRelocationModel() == Reloc::PIC_);
7752    }
7753    llvm_unreachable("Unknown TLS model.");
7754  }
7755
7756  if (Subtarget->isTargetDarwin()) {
7757    // Darwin only has one model of TLS.  Lower to that.
7758    unsigned char OpFlag = 0;
7759    unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
7760                           X86ISD::WrapperRIP : X86ISD::Wrapper;
7761
7762    // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7763    // global base reg.
7764    bool PIC32 = (getTargetMachine().getRelocationModel() == Reloc::PIC_) &&
7765                  !Subtarget->is64Bit();
7766    if (PIC32)
7767      OpFlag = X86II::MO_TLVP_PIC_BASE;
7768    else
7769      OpFlag = X86II::MO_TLVP;
7770    DebugLoc DL = Op.getDebugLoc();
7771    SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
7772                                                GA->getValueType(0),
7773                                                GA->getOffset(), OpFlag);
7774    SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7775
7776    // With PIC32, the address is actually $g + Offset.
7777    if (PIC32)
7778      Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7779                           DAG.getNode(X86ISD::GlobalBaseReg,
7780                                       DebugLoc(), getPointerTy()),
7781                           Offset);
7782
7783    // Lowering the machine isd will make sure everything is in the right
7784    // location.
7785    SDValue Chain = DAG.getEntryNode();
7786    SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7787    SDValue Args[] = { Chain, Offset };
7788    Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args, 2);
7789
7790    // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
7791    MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7792    MFI->setAdjustsStack(true);
7793
7794    // And our return value (tls address) is in the standard call return value
7795    // location.
7796    unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
7797    return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy(),
7798                              Chain.getValue(1));
7799  }
7800
7801  if (Subtarget->isTargetWindows()) {
7802    // Just use the implicit TLS architecture
7803    // Need to generate someting similar to:
7804    //   mov     rdx, qword [gs:abs 58H]; Load pointer to ThreadLocalStorage
7805    //                                  ; from TEB
7806    //   mov     ecx, dword [rel _tls_index]: Load index (from C runtime)
7807    //   mov     rcx, qword [rdx+rcx*8]
7808    //   mov     eax, .tls$:tlsvar
7809    //   [rax+rcx] contains the address
7810    // Windows 64bit: gs:0x58
7811    // Windows 32bit: fs:__tls_array
7812
7813    // If GV is an alias then use the aliasee for determining
7814    // thread-localness.
7815    if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
7816      GV = GA->resolveAliasedGlobal(false);
7817    DebugLoc dl = GA->getDebugLoc();
7818    SDValue Chain = DAG.getEntryNode();
7819
7820    // Get the Thread Pointer, which is %fs:__tls_array (32-bit) or
7821    // %gs:0x58 (64-bit).
7822    Value *Ptr = Constant::getNullValue(Subtarget->is64Bit()
7823                                        ? Type::getInt8PtrTy(*DAG.getContext(),
7824                                                             256)
7825                                        : Type::getInt32PtrTy(*DAG.getContext(),
7826                                                              257));
7827
7828    SDValue ThreadPointer = DAG.getLoad(getPointerTy(), dl, Chain,
7829                                        Subtarget->is64Bit()
7830                                        ? DAG.getIntPtrConstant(0x58)
7831                                        : DAG.getExternalSymbol("_tls_array",
7832                                                                getPointerTy()),
7833                                        MachinePointerInfo(Ptr),
7834                                        false, false, false, 0);
7835
7836    // Load the _tls_index variable
7837    SDValue IDX = DAG.getExternalSymbol("_tls_index", getPointerTy());
7838    if (Subtarget->is64Bit())
7839      IDX = DAG.getExtLoad(ISD::ZEXTLOAD, dl, getPointerTy(), Chain,
7840                           IDX, MachinePointerInfo(), MVT::i32,
7841                           false, false, 0);
7842    else
7843      IDX = DAG.getLoad(getPointerTy(), dl, Chain, IDX, MachinePointerInfo(),
7844                        false, false, false, 0);
7845
7846    SDValue Scale = DAG.getConstant(Log2_64_Ceil(TD->getPointerSize()),
7847                                    getPointerTy());
7848    IDX = DAG.getNode(ISD::SHL, dl, getPointerTy(), IDX, Scale);
7849
7850    SDValue res = DAG.getNode(ISD::ADD, dl, getPointerTy(), ThreadPointer, IDX);
7851    res = DAG.getLoad(getPointerTy(), dl, Chain, res, MachinePointerInfo(),
7852                      false, false, false, 0);
7853
7854    // Get the offset of start of .tls section
7855    SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7856                                             GA->getValueType(0),
7857                                             GA->getOffset(), X86II::MO_SECREL);
7858    SDValue Offset = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), TGA);
7859
7860    // The address of the thread local variable is the add of the thread
7861    // pointer with the offset of the variable.
7862    return DAG.getNode(ISD::ADD, dl, getPointerTy(), res, Offset);
7863  }
7864
7865  llvm_unreachable("TLS not implemented for this target.");
7866}
7867
7868
7869/// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values
7870/// and take a 2 x i32 value to shift plus a shift amount.
7871SDValue X86TargetLowering::LowerShiftParts(SDValue Op, SelectionDAG &DAG) const{
7872  assert(Op.getNumOperands() == 3 && "Not a double-shift!");
7873  EVT VT = Op.getValueType();
7874  unsigned VTBits = VT.getSizeInBits();
7875  DebugLoc dl = Op.getDebugLoc();
7876  bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
7877  SDValue ShOpLo = Op.getOperand(0);
7878  SDValue ShOpHi = Op.getOperand(1);
7879  SDValue ShAmt  = Op.getOperand(2);
7880  SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
7881                                     DAG.getConstant(VTBits - 1, MVT::i8))
7882                       : DAG.getConstant(0, VT);
7883
7884  SDValue Tmp2, Tmp3;
7885  if (Op.getOpcode() == ISD::SHL_PARTS) {
7886    Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
7887    Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
7888  } else {
7889    Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
7890    Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, ShAmt);
7891  }
7892
7893  SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
7894                                DAG.getConstant(VTBits, MVT::i8));
7895  SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
7896                             AndNode, DAG.getConstant(0, MVT::i8));
7897
7898  SDValue Hi, Lo;
7899  SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
7900  SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
7901  SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
7902
7903  if (Op.getOpcode() == ISD::SHL_PARTS) {
7904    Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
7905    Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
7906  } else {
7907    Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
7908    Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
7909  }
7910
7911  SDValue Ops[2] = { Lo, Hi };
7912  return DAG.getMergeValues(Ops, 2, dl);
7913}
7914
7915SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
7916                                           SelectionDAG &DAG) const {
7917  EVT SrcVT = Op.getOperand(0).getValueType();
7918
7919  if (SrcVT.isVector())
7920    return SDValue();
7921
7922  assert(SrcVT.getSimpleVT() <= MVT::i64 && SrcVT.getSimpleVT() >= MVT::i16 &&
7923         "Unknown SINT_TO_FP to lower!");
7924
7925  // These are really Legal; return the operand so the caller accepts it as
7926  // Legal.
7927  if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
7928    return Op;
7929  if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
7930      Subtarget->is64Bit()) {
7931    return Op;
7932  }
7933
7934  DebugLoc dl = Op.getDebugLoc();
7935  unsigned Size = SrcVT.getSizeInBits()/8;
7936  MachineFunction &MF = DAG.getMachineFunction();
7937  int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
7938  SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7939  SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
7940                               StackSlot,
7941                               MachinePointerInfo::getFixedStack(SSFI),
7942                               false, false, 0);
7943  return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
7944}
7945
7946SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
7947                                     SDValue StackSlot,
7948                                     SelectionDAG &DAG) const {
7949  // Build the FILD
7950  DebugLoc DL = Op.getDebugLoc();
7951  SDVTList Tys;
7952  bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
7953  if (useSSE)
7954    Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
7955  else
7956    Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
7957
7958  unsigned ByteSize = SrcVT.getSizeInBits()/8;
7959
7960  FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
7961  MachineMemOperand *MMO;
7962  if (FI) {
7963    int SSFI = FI->getIndex();
7964    MMO =
7965      DAG.getMachineFunction()
7966      .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7967                            MachineMemOperand::MOLoad, ByteSize, ByteSize);
7968  } else {
7969    MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
7970    StackSlot = StackSlot.getOperand(1);
7971  }
7972  SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
7973  SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
7974                                           X86ISD::FILD, DL,
7975                                           Tys, Ops, array_lengthof(Ops),
7976                                           SrcVT, MMO);
7977
7978  if (useSSE) {
7979    Chain = Result.getValue(1);
7980    SDValue InFlag = Result.getValue(2);
7981
7982    // FIXME: Currently the FST is flagged to the FILD_FLAG. This
7983    // shouldn't be necessary except that RFP cannot be live across
7984    // multiple blocks. When stackifier is fixed, they can be uncoupled.
7985    MachineFunction &MF = DAG.getMachineFunction();
7986    unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
7987    int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
7988    SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7989    Tys = DAG.getVTList(MVT::Other);
7990    SDValue Ops[] = {
7991      Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
7992    };
7993    MachineMemOperand *MMO =
7994      DAG.getMachineFunction()
7995      .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7996                            MachineMemOperand::MOStore, SSFISize, SSFISize);
7997
7998    Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
7999                                    Ops, array_lengthof(Ops),
8000                                    Op.getValueType(), MMO);
8001    Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
8002                         MachinePointerInfo::getFixedStack(SSFI),
8003                         false, false, false, 0);
8004  }
8005
8006  return Result;
8007}
8008
8009// LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
8010SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
8011                                               SelectionDAG &DAG) const {
8012  // This algorithm is not obvious. Here it is what we're trying to output:
8013  /*
8014     movq       %rax,  %xmm0
8015     punpckldq  (c0),  %xmm0  // c0: (uint4){ 0x43300000U, 0x45300000U, 0U, 0U }
8016     subpd      (c1),  %xmm0  // c1: (double2){ 0x1.0p52, 0x1.0p52 * 0x1.0p32 }
8017     #ifdef __SSE3__
8018       haddpd   %xmm0, %xmm0
8019     #else
8020       pshufd   $0x4e, %xmm0, %xmm1
8021       addpd    %xmm1, %xmm0
8022     #endif
8023  */
8024
8025  DebugLoc dl = Op.getDebugLoc();
8026  LLVMContext *Context = DAG.getContext();
8027
8028  // Build some magic constants.
8029  const uint32_t CV0[] = { 0x43300000, 0x45300000, 0, 0 };
8030  Constant *C0 = ConstantDataVector::get(*Context, CV0);
8031  SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
8032
8033  SmallVector<Constant*,2> CV1;
8034  CV1.push_back(
8035        ConstantFP::get(*Context, APFloat(APInt(64, 0x4330000000000000ULL))));
8036  CV1.push_back(
8037        ConstantFP::get(*Context, APFloat(APInt(64, 0x4530000000000000ULL))));
8038  Constant *C1 = ConstantVector::get(CV1);
8039  SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
8040
8041  // Load the 64-bit value into an XMM register.
8042  SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
8043                            Op.getOperand(0));
8044  SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
8045                              MachinePointerInfo::getConstantPool(),
8046                              false, false, false, 16);
8047  SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32,
8048                              DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, XR1),
8049                              CLod0);
8050
8051  SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
8052                              MachinePointerInfo::getConstantPool(),
8053                              false, false, false, 16);
8054  SDValue XR2F = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Unpck1);
8055  SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
8056  SDValue Result;
8057
8058  if (Subtarget->hasSSE3()) {
8059    // FIXME: The 'haddpd' instruction may be slower than 'movhlps + addsd'.
8060    Result = DAG.getNode(X86ISD::FHADD, dl, MVT::v2f64, Sub, Sub);
8061  } else {
8062    SDValue S2F = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Sub);
8063    SDValue Shuffle = getTargetShuffleNode(X86ISD::PSHUFD, dl, MVT::v4i32,
8064                                           S2F, 0x4E, DAG);
8065    Result = DAG.getNode(ISD::FADD, dl, MVT::v2f64,
8066                         DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Shuffle),
8067                         Sub);
8068  }
8069
8070  return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Result,
8071                     DAG.getIntPtrConstant(0));
8072}
8073
8074// LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
8075SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
8076                                               SelectionDAG &DAG) const {
8077  DebugLoc dl = Op.getDebugLoc();
8078  // FP constant to bias correct the final result.
8079  SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
8080                                   MVT::f64);
8081
8082  // Load the 32-bit value into an XMM register.
8083  SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
8084                             Op.getOperand(0));
8085
8086  // Zero out the upper parts of the register.
8087  Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget, DAG);
8088
8089  Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
8090                     DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Load),
8091                     DAG.getIntPtrConstant(0));
8092
8093  // Or the load with the bias.
8094  SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
8095                           DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
8096                                       DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
8097                                                   MVT::v2f64, Load)),
8098                           DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
8099                                       DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
8100                                                   MVT::v2f64, Bias)));
8101  Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
8102                   DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or),
8103                   DAG.getIntPtrConstant(0));
8104
8105  // Subtract the bias.
8106  SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
8107
8108  // Handle final rounding.
8109  EVT DestVT = Op.getValueType();
8110
8111  if (DestVT.bitsLT(MVT::f64))
8112    return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
8113                       DAG.getIntPtrConstant(0));
8114  if (DestVT.bitsGT(MVT::f64))
8115    return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
8116
8117  // Handle final rounding.
8118  return Sub;
8119}
8120
8121SDValue X86TargetLowering::lowerUINT_TO_FP_vec(SDValue Op,
8122                                               SelectionDAG &DAG) const {
8123  SDValue N0 = Op.getOperand(0);
8124  EVT SVT = N0.getValueType();
8125  DebugLoc dl = Op.getDebugLoc();
8126
8127  assert((SVT == MVT::v4i8 || SVT == MVT::v4i16 ||
8128          SVT == MVT::v8i8 || SVT == MVT::v8i16) &&
8129         "Custom UINT_TO_FP is not supported!");
8130
8131  EVT NVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, SVT.getVectorNumElements());
8132  return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
8133                     DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, N0));
8134}
8135
8136SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
8137                                           SelectionDAG &DAG) const {
8138  SDValue N0 = Op.getOperand(0);
8139  DebugLoc dl = Op.getDebugLoc();
8140
8141  if (Op.getValueType().isVector())
8142    return lowerUINT_TO_FP_vec(Op, DAG);
8143
8144  // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
8145  // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
8146  // the optimization here.
8147  if (DAG.SignBitIsZero(N0))
8148    return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
8149
8150  EVT SrcVT = N0.getValueType();
8151  EVT DstVT = Op.getValueType();
8152  if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
8153    return LowerUINT_TO_FP_i64(Op, DAG);
8154  if (SrcVT == MVT::i32 && X86ScalarSSEf64)
8155    return LowerUINT_TO_FP_i32(Op, DAG);
8156  if (Subtarget->is64Bit() && SrcVT == MVT::i64 && DstVT == MVT::f32)
8157    return SDValue();
8158
8159  // Make a 64-bit buffer, and use it to build an FILD.
8160  SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
8161  if (SrcVT == MVT::i32) {
8162    SDValue WordOff = DAG.getConstant(4, getPointerTy());
8163    SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
8164                                     getPointerTy(), StackSlot, WordOff);
8165    SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
8166                                  StackSlot, MachinePointerInfo(),
8167                                  false, false, 0);
8168    SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
8169                                  OffsetSlot, MachinePointerInfo(),
8170                                  false, false, 0);
8171    SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
8172    return Fild;
8173  }
8174
8175  assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
8176  SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
8177                               StackSlot, MachinePointerInfo(),
8178                               false, false, 0);
8179  // For i64 source, we need to add the appropriate power of 2 if the input
8180  // was negative.  This is the same as the optimization in
8181  // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
8182  // we must be careful to do the computation in x87 extended precision, not
8183  // in SSE. (The generic code can't know it's OK to do this, or how to.)
8184  int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
8185  MachineMemOperand *MMO =
8186    DAG.getMachineFunction()
8187    .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8188                          MachineMemOperand::MOLoad, 8, 8);
8189
8190  SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
8191  SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
8192  SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops, 3,
8193                                         MVT::i64, MMO);
8194
8195  APInt FF(32, 0x5F800000ULL);
8196
8197  // Check whether the sign bit is set.
8198  SDValue SignSet = DAG.getSetCC(dl, getSetCCResultType(MVT::i64),
8199                                 Op.getOperand(0), DAG.getConstant(0, MVT::i64),
8200                                 ISD::SETLT);
8201
8202  // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
8203  SDValue FudgePtr = DAG.getConstantPool(
8204                             ConstantInt::get(*DAG.getContext(), FF.zext(64)),
8205                                         getPointerTy());
8206
8207  // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
8208  SDValue Zero = DAG.getIntPtrConstant(0);
8209  SDValue Four = DAG.getIntPtrConstant(4);
8210  SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
8211                               Zero, Four);
8212  FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
8213
8214  // Load the value out, extending it from f32 to f80.
8215  // FIXME: Avoid the extend by constructing the right constant pool?
8216  SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(),
8217                                 FudgePtr, MachinePointerInfo::getConstantPool(),
8218                                 MVT::f32, false, false, 4);
8219  // Extend everything to 80 bits to force it to be done on x87.
8220  SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
8221  return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add, DAG.getIntPtrConstant(0));
8222}
8223
8224std::pair<SDValue,SDValue> X86TargetLowering::
8225FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG, bool IsSigned, bool IsReplace) const {
8226  DebugLoc DL = Op.getDebugLoc();
8227
8228  EVT DstTy = Op.getValueType();
8229
8230  if (!IsSigned && !isIntegerTypeFTOL(DstTy)) {
8231    assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
8232    DstTy = MVT::i64;
8233  }
8234
8235  assert(DstTy.getSimpleVT() <= MVT::i64 &&
8236         DstTy.getSimpleVT() >= MVT::i16 &&
8237         "Unknown FP_TO_INT to lower!");
8238
8239  // These are really Legal.
8240  if (DstTy == MVT::i32 &&
8241      isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
8242    return std::make_pair(SDValue(), SDValue());
8243  if (Subtarget->is64Bit() &&
8244      DstTy == MVT::i64 &&
8245      isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
8246    return std::make_pair(SDValue(), SDValue());
8247
8248  // We lower FP->int64 either into FISTP64 followed by a load from a temporary
8249  // stack slot, or into the FTOL runtime function.
8250  MachineFunction &MF = DAG.getMachineFunction();
8251  unsigned MemSize = DstTy.getSizeInBits()/8;
8252  int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
8253  SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8254
8255  unsigned Opc;
8256  if (!IsSigned && isIntegerTypeFTOL(DstTy))
8257    Opc = X86ISD::WIN_FTOL;
8258  else
8259    switch (DstTy.getSimpleVT().SimpleTy) {
8260    default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
8261    case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
8262    case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
8263    case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
8264    }
8265
8266  SDValue Chain = DAG.getEntryNode();
8267  SDValue Value = Op.getOperand(0);
8268  EVT TheVT = Op.getOperand(0).getValueType();
8269  // FIXME This causes a redundant load/store if the SSE-class value is already
8270  // in memory, such as if it is on the callstack.
8271  if (isScalarFPTypeInSSEReg(TheVT)) {
8272    assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
8273    Chain = DAG.getStore(Chain, DL, Value, StackSlot,
8274                         MachinePointerInfo::getFixedStack(SSFI),
8275                         false, false, 0);
8276    SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
8277    SDValue Ops[] = {
8278      Chain, StackSlot, DAG.getValueType(TheVT)
8279    };
8280
8281    MachineMemOperand *MMO =
8282      MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8283                              MachineMemOperand::MOLoad, MemSize, MemSize);
8284    Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, 3,
8285                                    DstTy, MMO);
8286    Chain = Value.getValue(1);
8287    SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
8288    StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8289  }
8290
8291  MachineMemOperand *MMO =
8292    MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8293                            MachineMemOperand::MOStore, MemSize, MemSize);
8294
8295  if (Opc != X86ISD::WIN_FTOL) {
8296    // Build the FP_TO_INT*_IN_MEM
8297    SDValue Ops[] = { Chain, Value, StackSlot };
8298    SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
8299                                           Ops, 3, DstTy, MMO);
8300    return std::make_pair(FIST, StackSlot);
8301  } else {
8302    SDValue ftol = DAG.getNode(X86ISD::WIN_FTOL, DL,
8303      DAG.getVTList(MVT::Other, MVT::Glue),
8304      Chain, Value);
8305    SDValue eax = DAG.getCopyFromReg(ftol, DL, X86::EAX,
8306      MVT::i32, ftol.getValue(1));
8307    SDValue edx = DAG.getCopyFromReg(eax.getValue(1), DL, X86::EDX,
8308      MVT::i32, eax.getValue(2));
8309    SDValue Ops[] = { eax, edx };
8310    SDValue pair = IsReplace
8311      ? DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops, 2)
8312      : DAG.getMergeValues(Ops, 2, DL);
8313    return std::make_pair(pair, SDValue());
8314  }
8315}
8316
8317SDValue X86TargetLowering::lowerZERO_EXTEND(SDValue Op, SelectionDAG &DAG) const {
8318  DebugLoc DL = Op.getDebugLoc();
8319  EVT VT = Op.getValueType();
8320  SDValue In = Op.getOperand(0);
8321  EVT SVT = In.getValueType();
8322
8323  if (!VT.is256BitVector() || !SVT.is128BitVector() ||
8324      VT.getVectorNumElements() != SVT.getVectorNumElements())
8325    return SDValue();
8326
8327  assert(Subtarget->hasAVX() && "256-bit vector is observed without AVX!");
8328
8329  // AVX2 has better support of integer extending.
8330  if (Subtarget->hasAVX2())
8331    return DAG.getNode(X86ISD::VZEXT, DL, VT, In);
8332
8333  SDValue Lo = DAG.getNode(X86ISD::VZEXT, DL, MVT::v4i32, In);
8334  static const int Mask[] = {4, 5, 6, 7, -1, -1, -1, -1};
8335  SDValue Hi = DAG.getNode(X86ISD::VZEXT, DL, MVT::v4i32,
8336                           DAG.getVectorShuffle(MVT::v8i16, DL, In, DAG.getUNDEF(MVT::v8i16), &Mask[0]));
8337
8338  return DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v8i32, Lo, Hi);
8339}
8340
8341SDValue X86TargetLowering::lowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
8342  DebugLoc DL = Op.getDebugLoc();
8343  EVT VT = Op.getValueType();
8344  EVT SVT = Op.getOperand(0).getValueType();
8345
8346  if (!VT.is128BitVector() || !SVT.is256BitVector() ||
8347      VT.getVectorNumElements() != SVT.getVectorNumElements())
8348    return SDValue();
8349
8350  assert(Subtarget->hasAVX() && "256-bit vector is observed without AVX!");
8351
8352  unsigned NumElems = VT.getVectorNumElements();
8353  EVT NVT = EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(),
8354                             NumElems * 2);
8355
8356  SDValue In = Op.getOperand(0);
8357  SmallVector<int, 16> MaskVec(NumElems * 2, -1);
8358  // Prepare truncation shuffle mask
8359  for (unsigned i = 0; i != NumElems; ++i)
8360    MaskVec[i] = i * 2;
8361  SDValue V = DAG.getVectorShuffle(NVT, DL,
8362                                   DAG.getNode(ISD::BITCAST, DL, NVT, In),
8363                                   DAG.getUNDEF(NVT), &MaskVec[0]);
8364  return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V,
8365                     DAG.getIntPtrConstant(0));
8366}
8367
8368SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
8369                                           SelectionDAG &DAG) const {
8370  if (Op.getValueType().isVector()) {
8371    if (Op.getValueType() == MVT::v8i16)
8372      return DAG.getNode(ISD::TRUNCATE, Op.getDebugLoc(), Op.getValueType(),
8373                         DAG.getNode(ISD::FP_TO_SINT, Op.getDebugLoc(),
8374                                     MVT::v8i32, Op.getOperand(0)));
8375    return SDValue();
8376  }
8377
8378  std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
8379    /*IsSigned=*/ true, /*IsReplace=*/ false);
8380  SDValue FIST = Vals.first, StackSlot = Vals.second;
8381  // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
8382  if (FIST.getNode() == 0) return Op;
8383
8384  if (StackSlot.getNode())
8385    // Load the result.
8386    return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
8387                       FIST, StackSlot, MachinePointerInfo(),
8388                       false, false, false, 0);
8389
8390  // The node is the result.
8391  return FIST;
8392}
8393
8394SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
8395                                           SelectionDAG &DAG) const {
8396  std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
8397    /*IsSigned=*/ false, /*IsReplace=*/ false);
8398  SDValue FIST = Vals.first, StackSlot = Vals.second;
8399  assert(FIST.getNode() && "Unexpected failure");
8400
8401  if (StackSlot.getNode())
8402    // Load the result.
8403    return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
8404                       FIST, StackSlot, MachinePointerInfo(),
8405                       false, false, false, 0);
8406
8407  // The node is the result.
8408  return FIST;
8409}
8410
8411SDValue X86TargetLowering::lowerFP_EXTEND(SDValue Op,
8412                                          SelectionDAG &DAG) const {
8413  DebugLoc DL = Op.getDebugLoc();
8414  EVT VT = Op.getValueType();
8415  SDValue In = Op.getOperand(0);
8416  EVT SVT = In.getValueType();
8417
8418  assert(SVT == MVT::v2f32 && "Only customize MVT::v2f32 type legalization!");
8419
8420  return DAG.getNode(X86ISD::VFPEXT, DL, VT,
8421                     DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4f32,
8422                                 In, DAG.getUNDEF(SVT)));
8423}
8424
8425SDValue X86TargetLowering::LowerFABS(SDValue Op, SelectionDAG &DAG) const {
8426  LLVMContext *Context = DAG.getContext();
8427  DebugLoc dl = Op.getDebugLoc();
8428  EVT VT = Op.getValueType();
8429  EVT EltVT = VT;
8430  unsigned NumElts = VT == MVT::f64 ? 2 : 4;
8431  if (VT.isVector()) {
8432    EltVT = VT.getVectorElementType();
8433    NumElts = VT.getVectorNumElements();
8434  }
8435  Constant *C;
8436  if (EltVT == MVT::f64)
8437    C = ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63))));
8438  else
8439    C = ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31))));
8440  C = ConstantVector::getSplat(NumElts, C);
8441  SDValue CPIdx = DAG.getConstantPool(C, getPointerTy());
8442  unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
8443  SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8444                             MachinePointerInfo::getConstantPool(),
8445                             false, false, false, Alignment);
8446  if (VT.isVector()) {
8447    MVT ANDVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
8448    return DAG.getNode(ISD::BITCAST, dl, VT,
8449                       DAG.getNode(ISD::AND, dl, ANDVT,
8450                                   DAG.getNode(ISD::BITCAST, dl, ANDVT,
8451                                               Op.getOperand(0)),
8452                                   DAG.getNode(ISD::BITCAST, dl, ANDVT, Mask)));
8453  }
8454  return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
8455}
8456
8457SDValue X86TargetLowering::LowerFNEG(SDValue Op, SelectionDAG &DAG) const {
8458  LLVMContext *Context = DAG.getContext();
8459  DebugLoc dl = Op.getDebugLoc();
8460  EVT VT = Op.getValueType();
8461  EVT EltVT = VT;
8462  unsigned NumElts = VT == MVT::f64 ? 2 : 4;
8463  if (VT.isVector()) {
8464    EltVT = VT.getVectorElementType();
8465    NumElts = VT.getVectorNumElements();
8466  }
8467  Constant *C;
8468  if (EltVT == MVT::f64)
8469    C = ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63)));
8470  else
8471    C = ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31)));
8472  C = ConstantVector::getSplat(NumElts, C);
8473  SDValue CPIdx = DAG.getConstantPool(C, getPointerTy());
8474  unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
8475  SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8476                             MachinePointerInfo::getConstantPool(),
8477                             false, false, false, Alignment);
8478  if (VT.isVector()) {
8479    MVT XORVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
8480    return DAG.getNode(ISD::BITCAST, dl, VT,
8481                       DAG.getNode(ISD::XOR, dl, XORVT,
8482                                   DAG.getNode(ISD::BITCAST, dl, XORVT,
8483                                               Op.getOperand(0)),
8484                                   DAG.getNode(ISD::BITCAST, dl, XORVT, Mask)));
8485  }
8486
8487  return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
8488}
8489
8490SDValue X86TargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
8491  LLVMContext *Context = DAG.getContext();
8492  SDValue Op0 = Op.getOperand(0);
8493  SDValue Op1 = Op.getOperand(1);
8494  DebugLoc dl = Op.getDebugLoc();
8495  EVT VT = Op.getValueType();
8496  EVT SrcVT = Op1.getValueType();
8497
8498  // If second operand is smaller, extend it first.
8499  if (SrcVT.bitsLT(VT)) {
8500    Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
8501    SrcVT = VT;
8502  }
8503  // And if it is bigger, shrink it first.
8504  if (SrcVT.bitsGT(VT)) {
8505    Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
8506    SrcVT = VT;
8507  }
8508
8509  // At this point the operands and the result should have the same
8510  // type, and that won't be f80 since that is not custom lowered.
8511
8512  // First get the sign bit of second operand.
8513  SmallVector<Constant*,4> CV;
8514  if (SrcVT == MVT::f64) {
8515    CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63))));
8516    CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
8517  } else {
8518    CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31))));
8519    CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8520    CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8521    CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8522  }
8523  Constant *C = ConstantVector::get(CV);
8524  SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8525  SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
8526                              MachinePointerInfo::getConstantPool(),
8527                              false, false, false, 16);
8528  SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
8529
8530  // Shift sign bit right or left if the two operands have different types.
8531  if (SrcVT.bitsGT(VT)) {
8532    // Op0 is MVT::f32, Op1 is MVT::f64.
8533    SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
8534    SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
8535                          DAG.getConstant(32, MVT::i32));
8536    SignBit = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, SignBit);
8537    SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
8538                          DAG.getIntPtrConstant(0));
8539  }
8540
8541  // Clear first operand sign bit.
8542  CV.clear();
8543  if (VT == MVT::f64) {
8544    CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63)))));
8545    CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
8546  } else {
8547    CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31)))));
8548    CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8549    CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8550    CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8551  }
8552  C = ConstantVector::get(CV);
8553  CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8554  SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8555                              MachinePointerInfo::getConstantPool(),
8556                              false, false, false, 16);
8557  SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
8558
8559  // Or the value with the sign bit.
8560  return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
8561}
8562
8563static SDValue LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) {
8564  SDValue N0 = Op.getOperand(0);
8565  DebugLoc dl = Op.getDebugLoc();
8566  EVT VT = Op.getValueType();
8567
8568  // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
8569  SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
8570                                  DAG.getConstant(1, VT));
8571  return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, VT));
8572}
8573
8574// LowerVectorAllZeroTest - Check whether an OR'd tree is PTEST-able.
8575//
8576SDValue X86TargetLowering::LowerVectorAllZeroTest(SDValue Op, SelectionDAG &DAG) const {
8577  assert(Op.getOpcode() == ISD::OR && "Only check OR'd tree.");
8578
8579  if (!Subtarget->hasSSE41())
8580    return SDValue();
8581
8582  if (!Op->hasOneUse())
8583    return SDValue();
8584
8585  SDNode *N = Op.getNode();
8586  DebugLoc DL = N->getDebugLoc();
8587
8588  SmallVector<SDValue, 8> Opnds;
8589  DenseMap<SDValue, unsigned> VecInMap;
8590  EVT VT = MVT::Other;
8591
8592  // Recognize a special case where a vector is casted into wide integer to
8593  // test all 0s.
8594  Opnds.push_back(N->getOperand(0));
8595  Opnds.push_back(N->getOperand(1));
8596
8597  for (unsigned Slot = 0, e = Opnds.size(); Slot < e; ++Slot) {
8598    SmallVector<SDValue, 8>::const_iterator I = Opnds.begin() + Slot;
8599    // BFS traverse all OR'd operands.
8600    if (I->getOpcode() == ISD::OR) {
8601      Opnds.push_back(I->getOperand(0));
8602      Opnds.push_back(I->getOperand(1));
8603      // Re-evaluate the number of nodes to be traversed.
8604      e += 2; // 2 more nodes (LHS and RHS) are pushed.
8605      continue;
8606    }
8607
8608    // Quit if a non-EXTRACT_VECTOR_ELT
8609    if (I->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
8610      return SDValue();
8611
8612    // Quit if without a constant index.
8613    SDValue Idx = I->getOperand(1);
8614    if (!isa<ConstantSDNode>(Idx))
8615      return SDValue();
8616
8617    SDValue ExtractedFromVec = I->getOperand(0);
8618    DenseMap<SDValue, unsigned>::iterator M = VecInMap.find(ExtractedFromVec);
8619    if (M == VecInMap.end()) {
8620      VT = ExtractedFromVec.getValueType();
8621      // Quit if not 128/256-bit vector.
8622      if (!VT.is128BitVector() && !VT.is256BitVector())
8623        return SDValue();
8624      // Quit if not the same type.
8625      if (VecInMap.begin() != VecInMap.end() &&
8626          VT != VecInMap.begin()->first.getValueType())
8627        return SDValue();
8628      M = VecInMap.insert(std::make_pair(ExtractedFromVec, 0)).first;
8629    }
8630    M->second |= 1U << cast<ConstantSDNode>(Idx)->getZExtValue();
8631  }
8632
8633  assert((VT.is128BitVector() || VT.is256BitVector()) &&
8634         "Not extracted from 128-/256-bit vector.");
8635
8636  unsigned FullMask = (1U << VT.getVectorNumElements()) - 1U;
8637  SmallVector<SDValue, 8> VecIns;
8638
8639  for (DenseMap<SDValue, unsigned>::const_iterator
8640        I = VecInMap.begin(), E = VecInMap.end(); I != E; ++I) {
8641    // Quit if not all elements are used.
8642    if (I->second != FullMask)
8643      return SDValue();
8644    VecIns.push_back(I->first);
8645  }
8646
8647  EVT TestVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
8648
8649  // Cast all vectors into TestVT for PTEST.
8650  for (unsigned i = 0, e = VecIns.size(); i < e; ++i)
8651    VecIns[i] = DAG.getNode(ISD::BITCAST, DL, TestVT, VecIns[i]);
8652
8653  // If more than one full vectors are evaluated, OR them first before PTEST.
8654  for (unsigned Slot = 0, e = VecIns.size(); e - Slot > 1; Slot += 2, e += 1) {
8655    // Each iteration will OR 2 nodes and append the result until there is only
8656    // 1 node left, i.e. the final OR'd value of all vectors.
8657    SDValue LHS = VecIns[Slot];
8658    SDValue RHS = VecIns[Slot + 1];
8659    VecIns.push_back(DAG.getNode(ISD::OR, DL, TestVT, LHS, RHS));
8660  }
8661
8662  return DAG.getNode(X86ISD::PTEST, DL, MVT::i32,
8663                     VecIns.back(), VecIns.back());
8664}
8665
8666/// Emit nodes that will be selected as "test Op0,Op0", or something
8667/// equivalent.
8668SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC,
8669                                    SelectionDAG &DAG) const {
8670  DebugLoc dl = Op.getDebugLoc();
8671
8672  // CF and OF aren't always set the way we want. Determine which
8673  // of these we need.
8674  bool NeedCF = false;
8675  bool NeedOF = false;
8676  switch (X86CC) {
8677  default: break;
8678  case X86::COND_A: case X86::COND_AE:
8679  case X86::COND_B: case X86::COND_BE:
8680    NeedCF = true;
8681    break;
8682  case X86::COND_G: case X86::COND_GE:
8683  case X86::COND_L: case X86::COND_LE:
8684  case X86::COND_O: case X86::COND_NO:
8685    NeedOF = true;
8686    break;
8687  }
8688
8689  // See if we can use the EFLAGS value from the operand instead of
8690  // doing a separate TEST. TEST always sets OF and CF to 0, so unless
8691  // we prove that the arithmetic won't overflow, we can't use OF or CF.
8692  if (Op.getResNo() != 0 || NeedOF || NeedCF)
8693    // Emit a CMP with 0, which is the TEST pattern.
8694    return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
8695                       DAG.getConstant(0, Op.getValueType()));
8696
8697  unsigned Opcode = 0;
8698  unsigned NumOperands = 0;
8699
8700  // Truncate operations may prevent the merge of the SETCC instruction
8701  // and the arithmetic intruction before it. Attempt to truncate the operands
8702  // of the arithmetic instruction and use a reduced bit-width instruction.
8703  bool NeedTruncation = false;
8704  SDValue ArithOp = Op;
8705  if (Op->getOpcode() == ISD::TRUNCATE && Op->hasOneUse()) {
8706    SDValue Arith = Op->getOperand(0);
8707    // Both the trunc and the arithmetic op need to have one user each.
8708    if (Arith->hasOneUse())
8709      switch (Arith.getOpcode()) {
8710        default: break;
8711        case ISD::ADD:
8712        case ISD::SUB:
8713        case ISD::AND:
8714        case ISD::OR:
8715        case ISD::XOR: {
8716          NeedTruncation = true;
8717          ArithOp = Arith;
8718        }
8719      }
8720  }
8721
8722  // NOTICE: In the code below we use ArithOp to hold the arithmetic operation
8723  // which may be the result of a CAST.  We use the variable 'Op', which is the
8724  // non-casted variable when we check for possible users.
8725  switch (ArithOp.getOpcode()) {
8726  case ISD::ADD:
8727    // Due to an isel shortcoming, be conservative if this add is likely to be
8728    // selected as part of a load-modify-store instruction. When the root node
8729    // in a match is a store, isel doesn't know how to remap non-chain non-flag
8730    // uses of other nodes in the match, such as the ADD in this case. This
8731    // leads to the ADD being left around and reselected, with the result being
8732    // two adds in the output.  Alas, even if none our users are stores, that
8733    // doesn't prove we're O.K.  Ergo, if we have any parents that aren't
8734    // CopyToReg or SETCC, eschew INC/DEC.  A better fix seems to require
8735    // climbing the DAG back to the root, and it doesn't seem to be worth the
8736    // effort.
8737    for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
8738         UE = Op.getNode()->use_end(); UI != UE; ++UI)
8739      if (UI->getOpcode() != ISD::CopyToReg &&
8740          UI->getOpcode() != ISD::SETCC &&
8741          UI->getOpcode() != ISD::STORE)
8742        goto default_case;
8743
8744    if (ConstantSDNode *C =
8745        dyn_cast<ConstantSDNode>(ArithOp.getNode()->getOperand(1))) {
8746      // An add of one will be selected as an INC.
8747      if (C->getAPIntValue() == 1) {
8748        Opcode = X86ISD::INC;
8749        NumOperands = 1;
8750        break;
8751      }
8752
8753      // An add of negative one (subtract of one) will be selected as a DEC.
8754      if (C->getAPIntValue().isAllOnesValue()) {
8755        Opcode = X86ISD::DEC;
8756        NumOperands = 1;
8757        break;
8758      }
8759    }
8760
8761    // Otherwise use a regular EFLAGS-setting add.
8762    Opcode = X86ISD::ADD;
8763    NumOperands = 2;
8764    break;
8765  case ISD::AND: {
8766    // If the primary and result isn't used, don't bother using X86ISD::AND,
8767    // because a TEST instruction will be better.
8768    bool NonFlagUse = false;
8769    for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
8770           UE = Op.getNode()->use_end(); UI != UE; ++UI) {
8771      SDNode *User = *UI;
8772      unsigned UOpNo = UI.getOperandNo();
8773      if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
8774        // Look pass truncate.
8775        UOpNo = User->use_begin().getOperandNo();
8776        User = *User->use_begin();
8777      }
8778
8779      if (User->getOpcode() != ISD::BRCOND &&
8780          User->getOpcode() != ISD::SETCC &&
8781          !(User->getOpcode() == ISD::SELECT && UOpNo == 0)) {
8782        NonFlagUse = true;
8783        break;
8784      }
8785    }
8786
8787    if (!NonFlagUse)
8788      break;
8789  }
8790    // FALL THROUGH
8791  case ISD::SUB:
8792  case ISD::OR:
8793  case ISD::XOR:
8794    // Due to the ISEL shortcoming noted above, be conservative if this op is
8795    // likely to be selected as part of a load-modify-store instruction.
8796    for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
8797           UE = Op.getNode()->use_end(); UI != UE; ++UI)
8798      if (UI->getOpcode() == ISD::STORE)
8799        goto default_case;
8800
8801    // Otherwise use a regular EFLAGS-setting instruction.
8802    switch (ArithOp.getOpcode()) {
8803    default: llvm_unreachable("unexpected operator!");
8804    case ISD::SUB: Opcode = X86ISD::SUB; break;
8805    case ISD::XOR: Opcode = X86ISD::XOR; break;
8806    case ISD::AND: Opcode = X86ISD::AND; break;
8807    case ISD::OR: {
8808      if (!NeedTruncation && (X86CC == X86::COND_E || X86CC == X86::COND_NE)) {
8809        SDValue EFLAGS = LowerVectorAllZeroTest(Op, DAG);
8810        if (EFLAGS.getNode())
8811          return EFLAGS;
8812      }
8813      Opcode = X86ISD::OR;
8814      break;
8815    }
8816    }
8817
8818    NumOperands = 2;
8819    break;
8820  case X86ISD::ADD:
8821  case X86ISD::SUB:
8822  case X86ISD::INC:
8823  case X86ISD::DEC:
8824  case X86ISD::OR:
8825  case X86ISD::XOR:
8826  case X86ISD::AND:
8827    return SDValue(Op.getNode(), 1);
8828  default:
8829  default_case:
8830    break;
8831  }
8832
8833  // If we found that truncation is beneficial, perform the truncation and
8834  // update 'Op'.
8835  if (NeedTruncation) {
8836    EVT VT = Op.getValueType();
8837    SDValue WideVal = Op->getOperand(0);
8838    EVT WideVT = WideVal.getValueType();
8839    unsigned ConvertedOp = 0;
8840    // Use a target machine opcode to prevent further DAGCombine
8841    // optimizations that may separate the arithmetic operations
8842    // from the setcc node.
8843    switch (WideVal.getOpcode()) {
8844      default: break;
8845      case ISD::ADD: ConvertedOp = X86ISD::ADD; break;
8846      case ISD::SUB: ConvertedOp = X86ISD::SUB; break;
8847      case ISD::AND: ConvertedOp = X86ISD::AND; break;
8848      case ISD::OR:  ConvertedOp = X86ISD::OR;  break;
8849      case ISD::XOR: ConvertedOp = X86ISD::XOR; break;
8850    }
8851
8852    if (ConvertedOp) {
8853      const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8854      if (TLI.isOperationLegal(WideVal.getOpcode(), WideVT)) {
8855        SDValue V0 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(0));
8856        SDValue V1 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(1));
8857        Op = DAG.getNode(ConvertedOp, dl, VT, V0, V1);
8858      }
8859    }
8860  }
8861
8862  if (Opcode == 0)
8863    // Emit a CMP with 0, which is the TEST pattern.
8864    return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
8865                       DAG.getConstant(0, Op.getValueType()));
8866
8867  SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
8868  SmallVector<SDValue, 4> Ops;
8869  for (unsigned i = 0; i != NumOperands; ++i)
8870    Ops.push_back(Op.getOperand(i));
8871
8872  SDValue New = DAG.getNode(Opcode, dl, VTs, &Ops[0], NumOperands);
8873  DAG.ReplaceAllUsesWith(Op, New);
8874  return SDValue(New.getNode(), 1);
8875}
8876
8877/// Emit nodes that will be selected as "cmp Op0,Op1", or something
8878/// equivalent.
8879SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
8880                                   SelectionDAG &DAG) const {
8881  if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1))
8882    if (C->getAPIntValue() == 0)
8883      return EmitTest(Op0, X86CC, DAG);
8884
8885  DebugLoc dl = Op0.getDebugLoc();
8886  if ((Op0.getValueType() == MVT::i8 || Op0.getValueType() == MVT::i16 ||
8887       Op0.getValueType() == MVT::i32 || Op0.getValueType() == MVT::i64)) {
8888    // Use SUB instead of CMP to enable CSE between SUB and CMP.
8889    SDVTList VTs = DAG.getVTList(Op0.getValueType(), MVT::i32);
8890    SDValue Sub = DAG.getNode(X86ISD::SUB, dl, VTs,
8891                              Op0, Op1);
8892    return SDValue(Sub.getNode(), 1);
8893  }
8894  return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
8895}
8896
8897/// Convert a comparison if required by the subtarget.
8898SDValue X86TargetLowering::ConvertCmpIfNecessary(SDValue Cmp,
8899                                                 SelectionDAG &DAG) const {
8900  // If the subtarget does not support the FUCOMI instruction, floating-point
8901  // comparisons have to be converted.
8902  if (Subtarget->hasCMov() ||
8903      Cmp.getOpcode() != X86ISD::CMP ||
8904      !Cmp.getOperand(0).getValueType().isFloatingPoint() ||
8905      !Cmp.getOperand(1).getValueType().isFloatingPoint())
8906    return Cmp;
8907
8908  // The instruction selector will select an FUCOM instruction instead of
8909  // FUCOMI, which writes the comparison result to FPSW instead of EFLAGS. Hence
8910  // build an SDNode sequence that transfers the result from FPSW into EFLAGS:
8911  // (X86sahf (trunc (srl (X86fp_stsw (trunc (X86cmp ...)), 8))))
8912  DebugLoc dl = Cmp.getDebugLoc();
8913  SDValue TruncFPSW = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, Cmp);
8914  SDValue FNStSW = DAG.getNode(X86ISD::FNSTSW16r, dl, MVT::i16, TruncFPSW);
8915  SDValue Srl = DAG.getNode(ISD::SRL, dl, MVT::i16, FNStSW,
8916                            DAG.getConstant(8, MVT::i8));
8917  SDValue TruncSrl = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Srl);
8918  return DAG.getNode(X86ISD::SAHF, dl, MVT::i32, TruncSrl);
8919}
8920
8921/// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
8922/// if it's possible.
8923SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
8924                                     DebugLoc dl, SelectionDAG &DAG) const {
8925  SDValue Op0 = And.getOperand(0);
8926  SDValue Op1 = And.getOperand(1);
8927  if (Op0.getOpcode() == ISD::TRUNCATE)
8928    Op0 = Op0.getOperand(0);
8929  if (Op1.getOpcode() == ISD::TRUNCATE)
8930    Op1 = Op1.getOperand(0);
8931
8932  SDValue LHS, RHS;
8933  if (Op1.getOpcode() == ISD::SHL)
8934    std::swap(Op0, Op1);
8935  if (Op0.getOpcode() == ISD::SHL) {
8936    if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
8937      if (And00C->getZExtValue() == 1) {
8938        // If we looked past a truncate, check that it's only truncating away
8939        // known zeros.
8940        unsigned BitWidth = Op0.getValueSizeInBits();
8941        unsigned AndBitWidth = And.getValueSizeInBits();
8942        if (BitWidth > AndBitWidth) {
8943          APInt Zeros, Ones;
8944          DAG.ComputeMaskedBits(Op0, Zeros, Ones);
8945          if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
8946            return SDValue();
8947        }
8948        LHS = Op1;
8949        RHS = Op0.getOperand(1);
8950      }
8951  } else if (Op1.getOpcode() == ISD::Constant) {
8952    ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
8953    uint64_t AndRHSVal = AndRHS->getZExtValue();
8954    SDValue AndLHS = Op0;
8955
8956    if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) {
8957      LHS = AndLHS.getOperand(0);
8958      RHS = AndLHS.getOperand(1);
8959    }
8960
8961    // Use BT if the immediate can't be encoded in a TEST instruction.
8962    if (!isUInt<32>(AndRHSVal) && isPowerOf2_64(AndRHSVal)) {
8963      LHS = AndLHS;
8964      RHS = DAG.getConstant(Log2_64_Ceil(AndRHSVal), LHS.getValueType());
8965    }
8966  }
8967
8968  if (LHS.getNode()) {
8969    // If LHS is i8, promote it to i32 with any_extend.  There is no i8 BT
8970    // instruction.  Since the shift amount is in-range-or-undefined, we know
8971    // that doing a bittest on the i32 value is ok.  We extend to i32 because
8972    // the encoding for the i16 version is larger than the i32 version.
8973    // Also promote i16 to i32 for performance / code size reason.
8974    if (LHS.getValueType() == MVT::i8 ||
8975        LHS.getValueType() == MVT::i16)
8976      LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
8977
8978    // If the operand types disagree, extend the shift amount to match.  Since
8979    // BT ignores high bits (like shifts) we can use anyextend.
8980    if (LHS.getValueType() != RHS.getValueType())
8981      RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
8982
8983    SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
8984    unsigned Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
8985    return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
8986                       DAG.getConstant(Cond, MVT::i8), BT);
8987  }
8988
8989  return SDValue();
8990}
8991
8992SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
8993
8994  if (Op.getValueType().isVector()) return LowerVSETCC(Op, DAG);
8995
8996  assert(Op.getValueType() == MVT::i8 && "SetCC type must be 8-bit integer");
8997  SDValue Op0 = Op.getOperand(0);
8998  SDValue Op1 = Op.getOperand(1);
8999  DebugLoc dl = Op.getDebugLoc();
9000  ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
9001
9002  // Optimize to BT if possible.
9003  // Lower (X & (1 << N)) == 0 to BT(X, N).
9004  // Lower ((X >>u N) & 1) != 0 to BT(X, N).
9005  // Lower ((X >>s N) & 1) != 0 to BT(X, N).
9006  if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
9007      Op1.getOpcode() == ISD::Constant &&
9008      cast<ConstantSDNode>(Op1)->isNullValue() &&
9009      (CC == ISD::SETEQ || CC == ISD::SETNE)) {
9010    SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
9011    if (NewSetCC.getNode())
9012      return NewSetCC;
9013  }
9014
9015  // Look for X == 0, X == 1, X != 0, or X != 1.  We can simplify some forms of
9016  // these.
9017  if (Op1.getOpcode() == ISD::Constant &&
9018      (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
9019       cast<ConstantSDNode>(Op1)->isNullValue()) &&
9020      (CC == ISD::SETEQ || CC == ISD::SETNE)) {
9021
9022    // If the input is a setcc, then reuse the input setcc or use a new one with
9023    // the inverted condition.
9024    if (Op0.getOpcode() == X86ISD::SETCC) {
9025      X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
9026      bool Invert = (CC == ISD::SETNE) ^
9027        cast<ConstantSDNode>(Op1)->isNullValue();
9028      if (!Invert) return Op0;
9029
9030      CCode = X86::GetOppositeBranchCondition(CCode);
9031      return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
9032                         DAG.getConstant(CCode, MVT::i8), Op0.getOperand(1));
9033    }
9034  }
9035
9036  bool isFP = Op1.getValueType().isFloatingPoint();
9037  unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
9038  if (X86CC == X86::COND_INVALID)
9039    return SDValue();
9040
9041  SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, DAG);
9042  EFLAGS = ConvertCmpIfNecessary(EFLAGS, DAG);
9043  return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
9044                     DAG.getConstant(X86CC, MVT::i8), EFLAGS);
9045}
9046
9047// Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
9048// ones, and then concatenate the result back.
9049static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
9050  EVT VT = Op.getValueType();
9051
9052  assert(VT.is256BitVector() && Op.getOpcode() == ISD::SETCC &&
9053         "Unsupported value type for operation");
9054
9055  unsigned NumElems = VT.getVectorNumElements();
9056  DebugLoc dl = Op.getDebugLoc();
9057  SDValue CC = Op.getOperand(2);
9058
9059  // Extract the LHS vectors
9060  SDValue LHS = Op.getOperand(0);
9061  SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
9062  SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
9063
9064  // Extract the RHS vectors
9065  SDValue RHS = Op.getOperand(1);
9066  SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
9067  SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
9068
9069  // Issue the operation on the smaller types and concatenate the result back
9070  MVT EltVT = VT.getVectorElementType().getSimpleVT();
9071  EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
9072  return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
9073                     DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
9074                     DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
9075}
9076
9077
9078SDValue X86TargetLowering::LowerVSETCC(SDValue Op, SelectionDAG &DAG) const {
9079  SDValue Cond;
9080  SDValue Op0 = Op.getOperand(0);
9081  SDValue Op1 = Op.getOperand(1);
9082  SDValue CC = Op.getOperand(2);
9083  EVT VT = Op.getValueType();
9084  ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
9085  bool isFP = Op.getOperand(1).getValueType().isFloatingPoint();
9086  DebugLoc dl = Op.getDebugLoc();
9087
9088  if (isFP) {
9089#ifndef NDEBUG
9090    EVT EltVT = Op0.getValueType().getVectorElementType();
9091    assert(EltVT == MVT::f32 || EltVT == MVT::f64);
9092#endif
9093
9094    unsigned SSECC;
9095    bool Swap = false;
9096
9097    // SSE Condition code mapping:
9098    //  0 - EQ
9099    //  1 - LT
9100    //  2 - LE
9101    //  3 - UNORD
9102    //  4 - NEQ
9103    //  5 - NLT
9104    //  6 - NLE
9105    //  7 - ORD
9106    switch (SetCCOpcode) {
9107    default: llvm_unreachable("Unexpected SETCC condition");
9108    case ISD::SETOEQ:
9109    case ISD::SETEQ:  SSECC = 0; break;
9110    case ISD::SETOGT:
9111    case ISD::SETGT: Swap = true; // Fallthrough
9112    case ISD::SETLT:
9113    case ISD::SETOLT: SSECC = 1; break;
9114    case ISD::SETOGE:
9115    case ISD::SETGE: Swap = true; // Fallthrough
9116    case ISD::SETLE:
9117    case ISD::SETOLE: SSECC = 2; break;
9118    case ISD::SETUO:  SSECC = 3; break;
9119    case ISD::SETUNE:
9120    case ISD::SETNE:  SSECC = 4; break;
9121    case ISD::SETULE: Swap = true; // Fallthrough
9122    case ISD::SETUGE: SSECC = 5; break;
9123    case ISD::SETULT: Swap = true; // Fallthrough
9124    case ISD::SETUGT: SSECC = 6; break;
9125    case ISD::SETO:   SSECC = 7; break;
9126    case ISD::SETUEQ:
9127    case ISD::SETONE: SSECC = 8; break;
9128    }
9129    if (Swap)
9130      std::swap(Op0, Op1);
9131
9132    // In the two special cases we can't handle, emit two comparisons.
9133    if (SSECC == 8) {
9134      unsigned CC0, CC1;
9135      unsigned CombineOpc;
9136      if (SetCCOpcode == ISD::SETUEQ) {
9137        CC0 = 3; CC1 = 0; CombineOpc = ISD::OR;
9138      } else {
9139        assert(SetCCOpcode == ISD::SETONE);
9140        CC0 = 7; CC1 = 4; CombineOpc = ISD::AND;
9141      }
9142
9143      SDValue Cmp0 = DAG.getNode(X86ISD::CMPP, dl, VT, Op0, Op1,
9144                                 DAG.getConstant(CC0, MVT::i8));
9145      SDValue Cmp1 = DAG.getNode(X86ISD::CMPP, dl, VT, Op0, Op1,
9146                                 DAG.getConstant(CC1, MVT::i8));
9147      return DAG.getNode(CombineOpc, dl, VT, Cmp0, Cmp1);
9148    }
9149    // Handle all other FP comparisons here.
9150    return DAG.getNode(X86ISD::CMPP, dl, VT, Op0, Op1,
9151                       DAG.getConstant(SSECC, MVT::i8));
9152  }
9153
9154  // Break 256-bit integer vector compare into smaller ones.
9155  if (VT.is256BitVector() && !Subtarget->hasAVX2())
9156    return Lower256IntVSETCC(Op, DAG);
9157
9158  // We are handling one of the integer comparisons here.  Since SSE only has
9159  // GT and EQ comparisons for integer, swapping operands and multiple
9160  // operations may be required for some comparisons.
9161  unsigned Opc;
9162  bool Swap = false, Invert = false, FlipSigns = false;
9163
9164  switch (SetCCOpcode) {
9165  default: llvm_unreachable("Unexpected SETCC condition");
9166  case ISD::SETNE:  Invert = true;
9167  case ISD::SETEQ:  Opc = X86ISD::PCMPEQ; break;
9168  case ISD::SETLT:  Swap = true;
9169  case ISD::SETGT:  Opc = X86ISD::PCMPGT; break;
9170  case ISD::SETGE:  Swap = true;
9171  case ISD::SETLE:  Opc = X86ISD::PCMPGT; Invert = true; break;
9172  case ISD::SETULT: Swap = true;
9173  case ISD::SETUGT: Opc = X86ISD::PCMPGT; FlipSigns = true; break;
9174  case ISD::SETUGE: Swap = true;
9175  case ISD::SETULE: Opc = X86ISD::PCMPGT; FlipSigns = true; Invert = true; break;
9176  }
9177  if (Swap)
9178    std::swap(Op0, Op1);
9179
9180  // Check that the operation in question is available (most are plain SSE2,
9181  // but PCMPGTQ and PCMPEQQ have different requirements).
9182  if (VT == MVT::v2i64) {
9183    if (Opc == X86ISD::PCMPGT && !Subtarget->hasSSE42())
9184      return SDValue();
9185    if (Opc == X86ISD::PCMPEQ && !Subtarget->hasSSE41())
9186      return SDValue();
9187  }
9188
9189  // Since SSE has no unsigned integer comparisons, we need to flip  the sign
9190  // bits of the inputs before performing those operations.
9191  if (FlipSigns) {
9192    EVT EltVT = VT.getVectorElementType();
9193    SDValue SignBit = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()),
9194                                      EltVT);
9195    std::vector<SDValue> SignBits(VT.getVectorNumElements(), SignBit);
9196    SDValue SignVec = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &SignBits[0],
9197                                    SignBits.size());
9198    Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SignVec);
9199    Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SignVec);
9200  }
9201
9202  SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
9203
9204  // If the logical-not of the result is required, perform that now.
9205  if (Invert)
9206    Result = DAG.getNOT(dl, Result, VT);
9207
9208  return Result;
9209}
9210
9211// isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
9212static bool isX86LogicalCmp(SDValue Op) {
9213  unsigned Opc = Op.getNode()->getOpcode();
9214  if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI ||
9215      Opc == X86ISD::SAHF)
9216    return true;
9217  if (Op.getResNo() == 1 &&
9218      (Opc == X86ISD::ADD ||
9219       Opc == X86ISD::SUB ||
9220       Opc == X86ISD::ADC ||
9221       Opc == X86ISD::SBB ||
9222       Opc == X86ISD::SMUL ||
9223       Opc == X86ISD::UMUL ||
9224       Opc == X86ISD::INC ||
9225       Opc == X86ISD::DEC ||
9226       Opc == X86ISD::OR ||
9227       Opc == X86ISD::XOR ||
9228       Opc == X86ISD::AND))
9229    return true;
9230
9231  if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
9232    return true;
9233
9234  return false;
9235}
9236
9237static bool isZero(SDValue V) {
9238  ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
9239  return C && C->isNullValue();
9240}
9241
9242static bool isAllOnes(SDValue V) {
9243  ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
9244  return C && C->isAllOnesValue();
9245}
9246
9247static bool isTruncWithZeroHighBitsInput(SDValue V, SelectionDAG &DAG) {
9248  if (V.getOpcode() != ISD::TRUNCATE)
9249    return false;
9250
9251  SDValue VOp0 = V.getOperand(0);
9252  unsigned InBits = VOp0.getValueSizeInBits();
9253  unsigned Bits = V.getValueSizeInBits();
9254  return DAG.MaskedValueIsZero(VOp0, APInt::getHighBitsSet(InBits,InBits-Bits));
9255}
9256
9257SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
9258  bool addTest = true;
9259  SDValue Cond  = Op.getOperand(0);
9260  SDValue Op1 = Op.getOperand(1);
9261  SDValue Op2 = Op.getOperand(2);
9262  DebugLoc DL = Op.getDebugLoc();
9263  SDValue CC;
9264
9265  if (Cond.getOpcode() == ISD::SETCC) {
9266    SDValue NewCond = LowerSETCC(Cond, DAG);
9267    if (NewCond.getNode())
9268      Cond = NewCond;
9269  }
9270
9271  // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
9272  // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
9273  // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
9274  // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
9275  if (Cond.getOpcode() == X86ISD::SETCC &&
9276      Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
9277      isZero(Cond.getOperand(1).getOperand(1))) {
9278    SDValue Cmp = Cond.getOperand(1);
9279
9280    unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
9281
9282    if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
9283        (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
9284      SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
9285
9286      SDValue CmpOp0 = Cmp.getOperand(0);
9287      // Apply further optimizations for special cases
9288      // (select (x != 0), -1, 0) -> neg & sbb
9289      // (select (x == 0), 0, -1) -> neg & sbb
9290      if (ConstantSDNode *YC = dyn_cast<ConstantSDNode>(Y))
9291        if (YC->isNullValue() &&
9292            (isAllOnes(Op1) == (CondCode == X86::COND_NE))) {
9293          SDVTList VTs = DAG.getVTList(CmpOp0.getValueType(), MVT::i32);
9294          SDValue Neg = DAG.getNode(X86ISD::SUB, DL, VTs,
9295                                    DAG.getConstant(0, CmpOp0.getValueType()),
9296                                    CmpOp0);
9297          SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
9298                                    DAG.getConstant(X86::COND_B, MVT::i8),
9299                                    SDValue(Neg.getNode(), 1));
9300          return Res;
9301        }
9302
9303      Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
9304                        CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
9305      Cmp = ConvertCmpIfNecessary(Cmp, DAG);
9306
9307      SDValue Res =   // Res = 0 or -1.
9308        DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
9309                    DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
9310
9311      if (isAllOnes(Op1) != (CondCode == X86::COND_E))
9312        Res = DAG.getNOT(DL, Res, Res.getValueType());
9313
9314      ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
9315      if (N2C == 0 || !N2C->isNullValue())
9316        Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
9317      return Res;
9318    }
9319  }
9320
9321  // Look past (and (setcc_carry (cmp ...)), 1).
9322  if (Cond.getOpcode() == ISD::AND &&
9323      Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
9324    ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
9325    if (C && C->getAPIntValue() == 1)
9326      Cond = Cond.getOperand(0);
9327  }
9328
9329  // If condition flag is set by a X86ISD::CMP, then use it as the condition
9330  // setting operand in place of the X86ISD::SETCC.
9331  unsigned CondOpcode = Cond.getOpcode();
9332  if (CondOpcode == X86ISD::SETCC ||
9333      CondOpcode == X86ISD::SETCC_CARRY) {
9334    CC = Cond.getOperand(0);
9335
9336    SDValue Cmp = Cond.getOperand(1);
9337    unsigned Opc = Cmp.getOpcode();
9338    EVT VT = Op.getValueType();
9339
9340    bool IllegalFPCMov = false;
9341    if (VT.isFloatingPoint() && !VT.isVector() &&
9342        !isScalarFPTypeInSSEReg(VT))  // FPStack?
9343      IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
9344
9345    if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
9346        Opc == X86ISD::BT) { // FIXME
9347      Cond = Cmp;
9348      addTest = false;
9349    }
9350  } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
9351             CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
9352             ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
9353              Cond.getOperand(0).getValueType() != MVT::i8)) {
9354    SDValue LHS = Cond.getOperand(0);
9355    SDValue RHS = Cond.getOperand(1);
9356    unsigned X86Opcode;
9357    unsigned X86Cond;
9358    SDVTList VTs;
9359    switch (CondOpcode) {
9360    case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
9361    case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
9362    case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
9363    case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
9364    case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
9365    case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
9366    default: llvm_unreachable("unexpected overflowing operator");
9367    }
9368    if (CondOpcode == ISD::UMULO)
9369      VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
9370                          MVT::i32);
9371    else
9372      VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
9373
9374    SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS);
9375
9376    if (CondOpcode == ISD::UMULO)
9377      Cond = X86Op.getValue(2);
9378    else
9379      Cond = X86Op.getValue(1);
9380
9381    CC = DAG.getConstant(X86Cond, MVT::i8);
9382    addTest = false;
9383  }
9384
9385  if (addTest) {
9386    // Look pass the truncate if the high bits are known zero.
9387    if (isTruncWithZeroHighBitsInput(Cond, DAG))
9388        Cond = Cond.getOperand(0);
9389
9390    // We know the result of AND is compared against zero. Try to match
9391    // it to BT.
9392    if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
9393      SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
9394      if (NewSetCC.getNode()) {
9395        CC = NewSetCC.getOperand(0);
9396        Cond = NewSetCC.getOperand(1);
9397        addTest = false;
9398      }
9399    }
9400  }
9401
9402  if (addTest) {
9403    CC = DAG.getConstant(X86::COND_NE, MVT::i8);
9404    Cond = EmitTest(Cond, X86::COND_NE, DAG);
9405  }
9406
9407  // a <  b ? -1 :  0 -> RES = ~setcc_carry
9408  // a <  b ?  0 : -1 -> RES = setcc_carry
9409  // a >= b ? -1 :  0 -> RES = setcc_carry
9410  // a >= b ?  0 : -1 -> RES = ~setcc_carry
9411  if (Cond.getOpcode() == X86ISD::SUB) {
9412    Cond = ConvertCmpIfNecessary(Cond, DAG);
9413    unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
9414
9415    if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
9416        (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
9417      SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
9418                                DAG.getConstant(X86::COND_B, MVT::i8), Cond);
9419      if (isAllOnes(Op1) != (CondCode == X86::COND_B))
9420        return DAG.getNOT(DL, Res, Res.getValueType());
9421      return Res;
9422    }
9423  }
9424
9425  // X86 doesn't have an i8 cmov. If both operands are the result of a truncate
9426  // widen the cmov and push the truncate through. This avoids introducing a new
9427  // branch during isel and doesn't add any extensions.
9428  if (Op.getValueType() == MVT::i8 &&
9429      Op1.getOpcode() == ISD::TRUNCATE && Op2.getOpcode() == ISD::TRUNCATE) {
9430    SDValue T1 = Op1.getOperand(0), T2 = Op2.getOperand(0);
9431    if (T1.getValueType() == T2.getValueType() &&
9432        // Blacklist CopyFromReg to avoid partial register stalls.
9433        T1.getOpcode() != ISD::CopyFromReg && T2.getOpcode()!=ISD::CopyFromReg){
9434      SDVTList VTs = DAG.getVTList(T1.getValueType(), MVT::Glue);
9435      SDValue Cmov = DAG.getNode(X86ISD::CMOV, DL, VTs, T2, T1, CC, Cond);
9436      return DAG.getNode(ISD::TRUNCATE, DL, Op.getValueType(), Cmov);
9437    }
9438  }
9439
9440  // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
9441  // condition is true.
9442  SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
9443  SDValue Ops[] = { Op2, Op1, CC, Cond };
9444  return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops, array_lengthof(Ops));
9445}
9446
9447// isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
9448// ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
9449// from the AND / OR.
9450static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
9451  Opc = Op.getOpcode();
9452  if (Opc != ISD::OR && Opc != ISD::AND)
9453    return false;
9454  return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
9455          Op.getOperand(0).hasOneUse() &&
9456          Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
9457          Op.getOperand(1).hasOneUse());
9458}
9459
9460// isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
9461// 1 and that the SETCC node has a single use.
9462static bool isXor1OfSetCC(SDValue Op) {
9463  if (Op.getOpcode() != ISD::XOR)
9464    return false;
9465  ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
9466  if (N1C && N1C->getAPIntValue() == 1) {
9467    return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
9468      Op.getOperand(0).hasOneUse();
9469  }
9470  return false;
9471}
9472
9473SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
9474  bool addTest = true;
9475  SDValue Chain = Op.getOperand(0);
9476  SDValue Cond  = Op.getOperand(1);
9477  SDValue Dest  = Op.getOperand(2);
9478  DebugLoc dl = Op.getDebugLoc();
9479  SDValue CC;
9480  bool Inverted = false;
9481
9482  if (Cond.getOpcode() == ISD::SETCC) {
9483    // Check for setcc([su]{add,sub,mul}o == 0).
9484    if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
9485        isa<ConstantSDNode>(Cond.getOperand(1)) &&
9486        cast<ConstantSDNode>(Cond.getOperand(1))->isNullValue() &&
9487        Cond.getOperand(0).getResNo() == 1 &&
9488        (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
9489         Cond.getOperand(0).getOpcode() == ISD::UADDO ||
9490         Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
9491         Cond.getOperand(0).getOpcode() == ISD::USUBO ||
9492         Cond.getOperand(0).getOpcode() == ISD::SMULO ||
9493         Cond.getOperand(0).getOpcode() == ISD::UMULO)) {
9494      Inverted = true;
9495      Cond = Cond.getOperand(0);
9496    } else {
9497      SDValue NewCond = LowerSETCC(Cond, DAG);
9498      if (NewCond.getNode())
9499        Cond = NewCond;
9500    }
9501  }
9502#if 0
9503  // FIXME: LowerXALUO doesn't handle these!!
9504  else if (Cond.getOpcode() == X86ISD::ADD  ||
9505           Cond.getOpcode() == X86ISD::SUB  ||
9506           Cond.getOpcode() == X86ISD::SMUL ||
9507           Cond.getOpcode() == X86ISD::UMUL)
9508    Cond = LowerXALUO(Cond, DAG);
9509#endif
9510
9511  // Look pass (and (setcc_carry (cmp ...)), 1).
9512  if (Cond.getOpcode() == ISD::AND &&
9513      Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
9514    ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
9515    if (C && C->getAPIntValue() == 1)
9516      Cond = Cond.getOperand(0);
9517  }
9518
9519  // If condition flag is set by a X86ISD::CMP, then use it as the condition
9520  // setting operand in place of the X86ISD::SETCC.
9521  unsigned CondOpcode = Cond.getOpcode();
9522  if (CondOpcode == X86ISD::SETCC ||
9523      CondOpcode == X86ISD::SETCC_CARRY) {
9524    CC = Cond.getOperand(0);
9525
9526    SDValue Cmp = Cond.getOperand(1);
9527    unsigned Opc = Cmp.getOpcode();
9528    // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
9529    if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
9530      Cond = Cmp;
9531      addTest = false;
9532    } else {
9533      switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
9534      default: break;
9535      case X86::COND_O:
9536      case X86::COND_B:
9537        // These can only come from an arithmetic instruction with overflow,
9538        // e.g. SADDO, UADDO.
9539        Cond = Cond.getNode()->getOperand(1);
9540        addTest = false;
9541        break;
9542      }
9543    }
9544  }
9545  CondOpcode = Cond.getOpcode();
9546  if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
9547      CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
9548      ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
9549       Cond.getOperand(0).getValueType() != MVT::i8)) {
9550    SDValue LHS = Cond.getOperand(0);
9551    SDValue RHS = Cond.getOperand(1);
9552    unsigned X86Opcode;
9553    unsigned X86Cond;
9554    SDVTList VTs;
9555    switch (CondOpcode) {
9556    case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
9557    case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
9558    case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
9559    case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
9560    case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
9561    case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
9562    default: llvm_unreachable("unexpected overflowing operator");
9563    }
9564    if (Inverted)
9565      X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond);
9566    if (CondOpcode == ISD::UMULO)
9567      VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
9568                          MVT::i32);
9569    else
9570      VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
9571
9572    SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS);
9573
9574    if (CondOpcode == ISD::UMULO)
9575      Cond = X86Op.getValue(2);
9576    else
9577      Cond = X86Op.getValue(1);
9578
9579    CC = DAG.getConstant(X86Cond, MVT::i8);
9580    addTest = false;
9581  } else {
9582    unsigned CondOpc;
9583    if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
9584      SDValue Cmp = Cond.getOperand(0).getOperand(1);
9585      if (CondOpc == ISD::OR) {
9586        // Also, recognize the pattern generated by an FCMP_UNE. We can emit
9587        // two branches instead of an explicit OR instruction with a
9588        // separate test.
9589        if (Cmp == Cond.getOperand(1).getOperand(1) &&
9590            isX86LogicalCmp(Cmp)) {
9591          CC = Cond.getOperand(0).getOperand(0);
9592          Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9593                              Chain, Dest, CC, Cmp);
9594          CC = Cond.getOperand(1).getOperand(0);
9595          Cond = Cmp;
9596          addTest = false;
9597        }
9598      } else { // ISD::AND
9599        // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
9600        // two branches instead of an explicit AND instruction with a
9601        // separate test. However, we only do this if this block doesn't
9602        // have a fall-through edge, because this requires an explicit
9603        // jmp when the condition is false.
9604        if (Cmp == Cond.getOperand(1).getOperand(1) &&
9605            isX86LogicalCmp(Cmp) &&
9606            Op.getNode()->hasOneUse()) {
9607          X86::CondCode CCode =
9608            (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
9609          CCode = X86::GetOppositeBranchCondition(CCode);
9610          CC = DAG.getConstant(CCode, MVT::i8);
9611          SDNode *User = *Op.getNode()->use_begin();
9612          // Look for an unconditional branch following this conditional branch.
9613          // We need this because we need to reverse the successors in order
9614          // to implement FCMP_OEQ.
9615          if (User->getOpcode() == ISD::BR) {
9616            SDValue FalseBB = User->getOperand(1);
9617            SDNode *NewBR =
9618              DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
9619            assert(NewBR == User);
9620            (void)NewBR;
9621            Dest = FalseBB;
9622
9623            Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9624                                Chain, Dest, CC, Cmp);
9625            X86::CondCode CCode =
9626              (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
9627            CCode = X86::GetOppositeBranchCondition(CCode);
9628            CC = DAG.getConstant(CCode, MVT::i8);
9629            Cond = Cmp;
9630            addTest = false;
9631          }
9632        }
9633      }
9634    } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
9635      // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
9636      // It should be transformed during dag combiner except when the condition
9637      // is set by a arithmetics with overflow node.
9638      X86::CondCode CCode =
9639        (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
9640      CCode = X86::GetOppositeBranchCondition(CCode);
9641      CC = DAG.getConstant(CCode, MVT::i8);
9642      Cond = Cond.getOperand(0).getOperand(1);
9643      addTest = false;
9644    } else if (Cond.getOpcode() == ISD::SETCC &&
9645               cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) {
9646      // For FCMP_OEQ, we can emit
9647      // two branches instead of an explicit AND instruction with a
9648      // separate test. However, we only do this if this block doesn't
9649      // have a fall-through edge, because this requires an explicit
9650      // jmp when the condition is false.
9651      if (Op.getNode()->hasOneUse()) {
9652        SDNode *User = *Op.getNode()->use_begin();
9653        // Look for an unconditional branch following this conditional branch.
9654        // We need this because we need to reverse the successors in order
9655        // to implement FCMP_OEQ.
9656        if (User->getOpcode() == ISD::BR) {
9657          SDValue FalseBB = User->getOperand(1);
9658          SDNode *NewBR =
9659            DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
9660          assert(NewBR == User);
9661          (void)NewBR;
9662          Dest = FalseBB;
9663
9664          SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
9665                                    Cond.getOperand(0), Cond.getOperand(1));
9666          Cmp = ConvertCmpIfNecessary(Cmp, DAG);
9667          CC = DAG.getConstant(X86::COND_NE, MVT::i8);
9668          Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9669                              Chain, Dest, CC, Cmp);
9670          CC = DAG.getConstant(X86::COND_P, MVT::i8);
9671          Cond = Cmp;
9672          addTest = false;
9673        }
9674      }
9675    } else if (Cond.getOpcode() == ISD::SETCC &&
9676               cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) {
9677      // For FCMP_UNE, we can emit
9678      // two branches instead of an explicit AND instruction with a
9679      // separate test. However, we only do this if this block doesn't
9680      // have a fall-through edge, because this requires an explicit
9681      // jmp when the condition is false.
9682      if (Op.getNode()->hasOneUse()) {
9683        SDNode *User = *Op.getNode()->use_begin();
9684        // Look for an unconditional branch following this conditional branch.
9685        // We need this because we need to reverse the successors in order
9686        // to implement FCMP_UNE.
9687        if (User->getOpcode() == ISD::BR) {
9688          SDValue FalseBB = User->getOperand(1);
9689          SDNode *NewBR =
9690            DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
9691          assert(NewBR == User);
9692          (void)NewBR;
9693
9694          SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
9695                                    Cond.getOperand(0), Cond.getOperand(1));
9696          Cmp = ConvertCmpIfNecessary(Cmp, DAG);
9697          CC = DAG.getConstant(X86::COND_NE, MVT::i8);
9698          Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9699                              Chain, Dest, CC, Cmp);
9700          CC = DAG.getConstant(X86::COND_NP, MVT::i8);
9701          Cond = Cmp;
9702          addTest = false;
9703          Dest = FalseBB;
9704        }
9705      }
9706    }
9707  }
9708
9709  if (addTest) {
9710    // Look pass the truncate if the high bits are known zero.
9711    if (isTruncWithZeroHighBitsInput(Cond, DAG))
9712        Cond = Cond.getOperand(0);
9713
9714    // We know the result of AND is compared against zero. Try to match
9715    // it to BT.
9716    if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
9717      SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
9718      if (NewSetCC.getNode()) {
9719        CC = NewSetCC.getOperand(0);
9720        Cond = NewSetCC.getOperand(1);
9721        addTest = false;
9722      }
9723    }
9724  }
9725
9726  if (addTest) {
9727    CC = DAG.getConstant(X86::COND_NE, MVT::i8);
9728    Cond = EmitTest(Cond, X86::COND_NE, DAG);
9729  }
9730  Cond = ConvertCmpIfNecessary(Cond, DAG);
9731  return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9732                     Chain, Dest, CC, Cond);
9733}
9734
9735
9736// Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
9737// Calls to _alloca is needed to probe the stack when allocating more than 4k
9738// bytes in one go. Touching the stack at 4K increments is necessary to ensure
9739// that the guard pages used by the OS virtual memory manager are allocated in
9740// correct sequence.
9741SDValue
9742X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
9743                                           SelectionDAG &DAG) const {
9744  assert((Subtarget->isTargetCygMing() || Subtarget->isTargetWindows() ||
9745          getTargetMachine().Options.EnableSegmentedStacks) &&
9746         "This should be used only on Windows targets or when segmented stacks "
9747         "are being used");
9748  assert(!Subtarget->isTargetEnvMacho() && "Not implemented");
9749  DebugLoc dl = Op.getDebugLoc();
9750
9751  // Get the inputs.
9752  SDValue Chain = Op.getOperand(0);
9753  SDValue Size  = Op.getOperand(1);
9754  // FIXME: Ensure alignment here
9755
9756  bool Is64Bit = Subtarget->is64Bit();
9757  EVT SPTy = Is64Bit ? MVT::i64 : MVT::i32;
9758
9759  if (getTargetMachine().Options.EnableSegmentedStacks) {
9760    MachineFunction &MF = DAG.getMachineFunction();
9761    MachineRegisterInfo &MRI = MF.getRegInfo();
9762
9763    if (Is64Bit) {
9764      // The 64 bit implementation of segmented stacks needs to clobber both r10
9765      // r11. This makes it impossible to use it along with nested parameters.
9766      const Function *F = MF.getFunction();
9767
9768      for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
9769           I != E; ++I)
9770        if (I->hasNestAttr())
9771          report_fatal_error("Cannot use segmented stacks with functions that "
9772                             "have nested arguments.");
9773    }
9774
9775    const TargetRegisterClass *AddrRegClass =
9776      getRegClassFor(Subtarget->is64Bit() ? MVT::i64:MVT::i32);
9777    unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
9778    Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
9779    SDValue Value = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
9780                                DAG.getRegister(Vreg, SPTy));
9781    SDValue Ops1[2] = { Value, Chain };
9782    return DAG.getMergeValues(Ops1, 2, dl);
9783  } else {
9784    SDValue Flag;
9785    unsigned Reg = (Subtarget->is64Bit() ? X86::RAX : X86::EAX);
9786
9787    Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
9788    Flag = Chain.getValue(1);
9789    SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
9790
9791    Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
9792    Flag = Chain.getValue(1);
9793
9794    Chain = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
9795                               SPTy).getValue(1);
9796
9797    SDValue Ops1[2] = { Chain.getValue(0), Chain };
9798    return DAG.getMergeValues(Ops1, 2, dl);
9799  }
9800}
9801
9802SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
9803  MachineFunction &MF = DAG.getMachineFunction();
9804  X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
9805
9806  const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
9807  DebugLoc DL = Op.getDebugLoc();
9808
9809  if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
9810    // vastart just stores the address of the VarArgsFrameIndex slot into the
9811    // memory location argument.
9812    SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
9813                                   getPointerTy());
9814    return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
9815                        MachinePointerInfo(SV), false, false, 0);
9816  }
9817
9818  // __va_list_tag:
9819  //   gp_offset         (0 - 6 * 8)
9820  //   fp_offset         (48 - 48 + 8 * 16)
9821  //   overflow_arg_area (point to parameters coming in memory).
9822  //   reg_save_area
9823  SmallVector<SDValue, 8> MemOps;
9824  SDValue FIN = Op.getOperand(1);
9825  // Store gp_offset
9826  SDValue Store = DAG.getStore(Op.getOperand(0), DL,
9827                               DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
9828                                               MVT::i32),
9829                               FIN, MachinePointerInfo(SV), false, false, 0);
9830  MemOps.push_back(Store);
9831
9832  // Store fp_offset
9833  FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
9834                    FIN, DAG.getIntPtrConstant(4));
9835  Store = DAG.getStore(Op.getOperand(0), DL,
9836                       DAG.getConstant(FuncInfo->getVarArgsFPOffset(),
9837                                       MVT::i32),
9838                       FIN, MachinePointerInfo(SV, 4), false, false, 0);
9839  MemOps.push_back(Store);
9840
9841  // Store ptr to overflow_arg_area
9842  FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
9843                    FIN, DAG.getIntPtrConstant(4));
9844  SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
9845                                    getPointerTy());
9846  Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
9847                       MachinePointerInfo(SV, 8),
9848                       false, false, 0);
9849  MemOps.push_back(Store);
9850
9851  // Store ptr to reg_save_area.
9852  FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
9853                    FIN, DAG.getIntPtrConstant(8));
9854  SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
9855                                    getPointerTy());
9856  Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
9857                       MachinePointerInfo(SV, 16), false, false, 0);
9858  MemOps.push_back(Store);
9859  return DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
9860                     &MemOps[0], MemOps.size());
9861}
9862
9863SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
9864  assert(Subtarget->is64Bit() &&
9865         "LowerVAARG only handles 64-bit va_arg!");
9866  assert((Subtarget->isTargetLinux() ||
9867          Subtarget->isTargetDarwin()) &&
9868          "Unhandled target in LowerVAARG");
9869  assert(Op.getNode()->getNumOperands() == 4);
9870  SDValue Chain = Op.getOperand(0);
9871  SDValue SrcPtr = Op.getOperand(1);
9872  const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
9873  unsigned Align = Op.getConstantOperandVal(3);
9874  DebugLoc dl = Op.getDebugLoc();
9875
9876  EVT ArgVT = Op.getNode()->getValueType(0);
9877  Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
9878  uint32_t ArgSize = getDataLayout()->getTypeAllocSize(ArgTy);
9879  uint8_t ArgMode;
9880
9881  // Decide which area this value should be read from.
9882  // TODO: Implement the AMD64 ABI in its entirety. This simple
9883  // selection mechanism works only for the basic types.
9884  if (ArgVT == MVT::f80) {
9885    llvm_unreachable("va_arg for f80 not yet implemented");
9886  } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
9887    ArgMode = 2;  // Argument passed in XMM register. Use fp_offset.
9888  } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
9889    ArgMode = 1;  // Argument passed in GPR64 register(s). Use gp_offset.
9890  } else {
9891    llvm_unreachable("Unhandled argument type in LowerVAARG");
9892  }
9893
9894  if (ArgMode == 2) {
9895    // Sanity Check: Make sure using fp_offset makes sense.
9896    assert(!getTargetMachine().Options.UseSoftFloat &&
9897           !(DAG.getMachineFunction()
9898                .getFunction()->getFnAttributes()
9899                .hasAttribute(Attributes::NoImplicitFloat)) &&
9900           Subtarget->hasSSE1());
9901  }
9902
9903  // Insert VAARG_64 node into the DAG
9904  // VAARG_64 returns two values: Variable Argument Address, Chain
9905  SmallVector<SDValue, 11> InstOps;
9906  InstOps.push_back(Chain);
9907  InstOps.push_back(SrcPtr);
9908  InstOps.push_back(DAG.getConstant(ArgSize, MVT::i32));
9909  InstOps.push_back(DAG.getConstant(ArgMode, MVT::i8));
9910  InstOps.push_back(DAG.getConstant(Align, MVT::i32));
9911  SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other);
9912  SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
9913                                          VTs, &InstOps[0], InstOps.size(),
9914                                          MVT::i64,
9915                                          MachinePointerInfo(SV),
9916                                          /*Align=*/0,
9917                                          /*Volatile=*/false,
9918                                          /*ReadMem=*/true,
9919                                          /*WriteMem=*/true);
9920  Chain = VAARG.getValue(1);
9921
9922  // Load the next argument and return it
9923  return DAG.getLoad(ArgVT, dl,
9924                     Chain,
9925                     VAARG,
9926                     MachinePointerInfo(),
9927                     false, false, false, 0);
9928}
9929
9930static SDValue LowerVACOPY(SDValue Op, const X86Subtarget *Subtarget,
9931                           SelectionDAG &DAG) {
9932  // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
9933  assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
9934  SDValue Chain = Op.getOperand(0);
9935  SDValue DstPtr = Op.getOperand(1);
9936  SDValue SrcPtr = Op.getOperand(2);
9937  const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
9938  const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
9939  DebugLoc DL = Op.getDebugLoc();
9940
9941  return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
9942                       DAG.getIntPtrConstant(24), 8, /*isVolatile*/false,
9943                       false,
9944                       MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
9945}
9946
9947// getTargetVShiftNOde - Handle vector element shifts where the shift amount
9948// may or may not be a constant. Takes immediate version of shift as input.
9949static SDValue getTargetVShiftNode(unsigned Opc, DebugLoc dl, EVT VT,
9950                                   SDValue SrcOp, SDValue ShAmt,
9951                                   SelectionDAG &DAG) {
9952  assert(ShAmt.getValueType() == MVT::i32 && "ShAmt is not i32");
9953
9954  if (isa<ConstantSDNode>(ShAmt)) {
9955    // Constant may be a TargetConstant. Use a regular constant.
9956    uint32_t ShiftAmt = cast<ConstantSDNode>(ShAmt)->getZExtValue();
9957    switch (Opc) {
9958      default: llvm_unreachable("Unknown target vector shift node");
9959      case X86ISD::VSHLI:
9960      case X86ISD::VSRLI:
9961      case X86ISD::VSRAI:
9962        return DAG.getNode(Opc, dl, VT, SrcOp,
9963                           DAG.getConstant(ShiftAmt, MVT::i32));
9964    }
9965  }
9966
9967  // Change opcode to non-immediate version
9968  switch (Opc) {
9969    default: llvm_unreachable("Unknown target vector shift node");
9970    case X86ISD::VSHLI: Opc = X86ISD::VSHL; break;
9971    case X86ISD::VSRLI: Opc = X86ISD::VSRL; break;
9972    case X86ISD::VSRAI: Opc = X86ISD::VSRA; break;
9973  }
9974
9975  // Need to build a vector containing shift amount
9976  // Shift amount is 32-bits, but SSE instructions read 64-bit, so fill with 0
9977  SDValue ShOps[4];
9978  ShOps[0] = ShAmt;
9979  ShOps[1] = DAG.getConstant(0, MVT::i32);
9980  ShOps[2] = ShOps[3] = DAG.getUNDEF(MVT::i32);
9981  ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, &ShOps[0], 4);
9982
9983  // The return type has to be a 128-bit type with the same element
9984  // type as the input type.
9985  MVT EltVT = VT.getVectorElementType().getSimpleVT();
9986  EVT ShVT = MVT::getVectorVT(EltVT, 128/EltVT.getSizeInBits());
9987
9988  ShAmt = DAG.getNode(ISD::BITCAST, dl, ShVT, ShAmt);
9989  return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
9990}
9991
9992static SDValue LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) {
9993  DebugLoc dl = Op.getDebugLoc();
9994  unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9995  switch (IntNo) {
9996  default: return SDValue();    // Don't custom lower most intrinsics.
9997  // Comparison intrinsics.
9998  case Intrinsic::x86_sse_comieq_ss:
9999  case Intrinsic::x86_sse_comilt_ss:
10000  case Intrinsic::x86_sse_comile_ss:
10001  case Intrinsic::x86_sse_comigt_ss:
10002  case Intrinsic::x86_sse_comige_ss:
10003  case Intrinsic::x86_sse_comineq_ss:
10004  case Intrinsic::x86_sse_ucomieq_ss:
10005  case Intrinsic::x86_sse_ucomilt_ss:
10006  case Intrinsic::x86_sse_ucomile_ss:
10007  case Intrinsic::x86_sse_ucomigt_ss:
10008  case Intrinsic::x86_sse_ucomige_ss:
10009  case Intrinsic::x86_sse_ucomineq_ss:
10010  case Intrinsic::x86_sse2_comieq_sd:
10011  case Intrinsic::x86_sse2_comilt_sd:
10012  case Intrinsic::x86_sse2_comile_sd:
10013  case Intrinsic::x86_sse2_comigt_sd:
10014  case Intrinsic::x86_sse2_comige_sd:
10015  case Intrinsic::x86_sse2_comineq_sd:
10016  case Intrinsic::x86_sse2_ucomieq_sd:
10017  case Intrinsic::x86_sse2_ucomilt_sd:
10018  case Intrinsic::x86_sse2_ucomile_sd:
10019  case Intrinsic::x86_sse2_ucomigt_sd:
10020  case Intrinsic::x86_sse2_ucomige_sd:
10021  case Intrinsic::x86_sse2_ucomineq_sd: {
10022    unsigned Opc;
10023    ISD::CondCode CC;
10024    switch (IntNo) {
10025    default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
10026    case Intrinsic::x86_sse_comieq_ss:
10027    case Intrinsic::x86_sse2_comieq_sd:
10028      Opc = X86ISD::COMI;
10029      CC = ISD::SETEQ;
10030      break;
10031    case Intrinsic::x86_sse_comilt_ss:
10032    case Intrinsic::x86_sse2_comilt_sd:
10033      Opc = X86ISD::COMI;
10034      CC = ISD::SETLT;
10035      break;
10036    case Intrinsic::x86_sse_comile_ss:
10037    case Intrinsic::x86_sse2_comile_sd:
10038      Opc = X86ISD::COMI;
10039      CC = ISD::SETLE;
10040      break;
10041    case Intrinsic::x86_sse_comigt_ss:
10042    case Intrinsic::x86_sse2_comigt_sd:
10043      Opc = X86ISD::COMI;
10044      CC = ISD::SETGT;
10045      break;
10046    case Intrinsic::x86_sse_comige_ss:
10047    case Intrinsic::x86_sse2_comige_sd:
10048      Opc = X86ISD::COMI;
10049      CC = ISD::SETGE;
10050      break;
10051    case Intrinsic::x86_sse_comineq_ss:
10052    case Intrinsic::x86_sse2_comineq_sd:
10053      Opc = X86ISD::COMI;
10054      CC = ISD::SETNE;
10055      break;
10056    case Intrinsic::x86_sse_ucomieq_ss:
10057    case Intrinsic::x86_sse2_ucomieq_sd:
10058      Opc = X86ISD::UCOMI;
10059      CC = ISD::SETEQ;
10060      break;
10061    case Intrinsic::x86_sse_ucomilt_ss:
10062    case Intrinsic::x86_sse2_ucomilt_sd:
10063      Opc = X86ISD::UCOMI;
10064      CC = ISD::SETLT;
10065      break;
10066    case Intrinsic::x86_sse_ucomile_ss:
10067    case Intrinsic::x86_sse2_ucomile_sd:
10068      Opc = X86ISD::UCOMI;
10069      CC = ISD::SETLE;
10070      break;
10071    case Intrinsic::x86_sse_ucomigt_ss:
10072    case Intrinsic::x86_sse2_ucomigt_sd:
10073      Opc = X86ISD::UCOMI;
10074      CC = ISD::SETGT;
10075      break;
10076    case Intrinsic::x86_sse_ucomige_ss:
10077    case Intrinsic::x86_sse2_ucomige_sd:
10078      Opc = X86ISD::UCOMI;
10079      CC = ISD::SETGE;
10080      break;
10081    case Intrinsic::x86_sse_ucomineq_ss:
10082    case Intrinsic::x86_sse2_ucomineq_sd:
10083      Opc = X86ISD::UCOMI;
10084      CC = ISD::SETNE;
10085      break;
10086    }
10087
10088    SDValue LHS = Op.getOperand(1);
10089    SDValue RHS = Op.getOperand(2);
10090    unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
10091    assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
10092    SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS);
10093    SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
10094                                DAG.getConstant(X86CC, MVT::i8), Cond);
10095    return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
10096  }
10097
10098  // Arithmetic intrinsics.
10099  case Intrinsic::x86_sse2_pmulu_dq:
10100  case Intrinsic::x86_avx2_pmulu_dq:
10101    return DAG.getNode(X86ISD::PMULUDQ, dl, Op.getValueType(),
10102                       Op.getOperand(1), Op.getOperand(2));
10103
10104  // SSE3/AVX horizontal add/sub intrinsics
10105  case Intrinsic::x86_sse3_hadd_ps:
10106  case Intrinsic::x86_sse3_hadd_pd:
10107  case Intrinsic::x86_avx_hadd_ps_256:
10108  case Intrinsic::x86_avx_hadd_pd_256:
10109  case Intrinsic::x86_sse3_hsub_ps:
10110  case Intrinsic::x86_sse3_hsub_pd:
10111  case Intrinsic::x86_avx_hsub_ps_256:
10112  case Intrinsic::x86_avx_hsub_pd_256:
10113  case Intrinsic::x86_ssse3_phadd_w_128:
10114  case Intrinsic::x86_ssse3_phadd_d_128:
10115  case Intrinsic::x86_avx2_phadd_w:
10116  case Intrinsic::x86_avx2_phadd_d:
10117  case Intrinsic::x86_ssse3_phsub_w_128:
10118  case Intrinsic::x86_ssse3_phsub_d_128:
10119  case Intrinsic::x86_avx2_phsub_w:
10120  case Intrinsic::x86_avx2_phsub_d: {
10121    unsigned Opcode;
10122    switch (IntNo) {
10123    default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
10124    case Intrinsic::x86_sse3_hadd_ps:
10125    case Intrinsic::x86_sse3_hadd_pd:
10126    case Intrinsic::x86_avx_hadd_ps_256:
10127    case Intrinsic::x86_avx_hadd_pd_256:
10128      Opcode = X86ISD::FHADD;
10129      break;
10130    case Intrinsic::x86_sse3_hsub_ps:
10131    case Intrinsic::x86_sse3_hsub_pd:
10132    case Intrinsic::x86_avx_hsub_ps_256:
10133    case Intrinsic::x86_avx_hsub_pd_256:
10134      Opcode = X86ISD::FHSUB;
10135      break;
10136    case Intrinsic::x86_ssse3_phadd_w_128:
10137    case Intrinsic::x86_ssse3_phadd_d_128:
10138    case Intrinsic::x86_avx2_phadd_w:
10139    case Intrinsic::x86_avx2_phadd_d:
10140      Opcode = X86ISD::HADD;
10141      break;
10142    case Intrinsic::x86_ssse3_phsub_w_128:
10143    case Intrinsic::x86_ssse3_phsub_d_128:
10144    case Intrinsic::x86_avx2_phsub_w:
10145    case Intrinsic::x86_avx2_phsub_d:
10146      Opcode = X86ISD::HSUB;
10147      break;
10148    }
10149    return DAG.getNode(Opcode, dl, Op.getValueType(),
10150                       Op.getOperand(1), Op.getOperand(2));
10151  }
10152
10153  // AVX2 variable shift intrinsics
10154  case Intrinsic::x86_avx2_psllv_d:
10155  case Intrinsic::x86_avx2_psllv_q:
10156  case Intrinsic::x86_avx2_psllv_d_256:
10157  case Intrinsic::x86_avx2_psllv_q_256:
10158  case Intrinsic::x86_avx2_psrlv_d:
10159  case Intrinsic::x86_avx2_psrlv_q:
10160  case Intrinsic::x86_avx2_psrlv_d_256:
10161  case Intrinsic::x86_avx2_psrlv_q_256:
10162  case Intrinsic::x86_avx2_psrav_d:
10163  case Intrinsic::x86_avx2_psrav_d_256: {
10164    unsigned Opcode;
10165    switch (IntNo) {
10166    default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
10167    case Intrinsic::x86_avx2_psllv_d:
10168    case Intrinsic::x86_avx2_psllv_q:
10169    case Intrinsic::x86_avx2_psllv_d_256:
10170    case Intrinsic::x86_avx2_psllv_q_256:
10171      Opcode = ISD::SHL;
10172      break;
10173    case Intrinsic::x86_avx2_psrlv_d:
10174    case Intrinsic::x86_avx2_psrlv_q:
10175    case Intrinsic::x86_avx2_psrlv_d_256:
10176    case Intrinsic::x86_avx2_psrlv_q_256:
10177      Opcode = ISD::SRL;
10178      break;
10179    case Intrinsic::x86_avx2_psrav_d:
10180    case Intrinsic::x86_avx2_psrav_d_256:
10181      Opcode = ISD::SRA;
10182      break;
10183    }
10184    return DAG.getNode(Opcode, dl, Op.getValueType(),
10185                       Op.getOperand(1), Op.getOperand(2));
10186  }
10187
10188  case Intrinsic::x86_ssse3_pshuf_b_128:
10189  case Intrinsic::x86_avx2_pshuf_b:
10190    return DAG.getNode(X86ISD::PSHUFB, dl, Op.getValueType(),
10191                       Op.getOperand(1), Op.getOperand(2));
10192
10193  case Intrinsic::x86_ssse3_psign_b_128:
10194  case Intrinsic::x86_ssse3_psign_w_128:
10195  case Intrinsic::x86_ssse3_psign_d_128:
10196  case Intrinsic::x86_avx2_psign_b:
10197  case Intrinsic::x86_avx2_psign_w:
10198  case Intrinsic::x86_avx2_psign_d:
10199    return DAG.getNode(X86ISD::PSIGN, dl, Op.getValueType(),
10200                       Op.getOperand(1), Op.getOperand(2));
10201
10202  case Intrinsic::x86_sse41_insertps:
10203    return DAG.getNode(X86ISD::INSERTPS, dl, Op.getValueType(),
10204                       Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
10205
10206  case Intrinsic::x86_avx_vperm2f128_ps_256:
10207  case Intrinsic::x86_avx_vperm2f128_pd_256:
10208  case Intrinsic::x86_avx_vperm2f128_si_256:
10209  case Intrinsic::x86_avx2_vperm2i128:
10210    return DAG.getNode(X86ISD::VPERM2X128, dl, Op.getValueType(),
10211                       Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
10212
10213  case Intrinsic::x86_avx2_permd:
10214  case Intrinsic::x86_avx2_permps:
10215    // Operands intentionally swapped. Mask is last operand to intrinsic,
10216    // but second operand for node/intruction.
10217    return DAG.getNode(X86ISD::VPERMV, dl, Op.getValueType(),
10218                       Op.getOperand(2), Op.getOperand(1));
10219
10220  // ptest and testp intrinsics. The intrinsic these come from are designed to
10221  // return an integer value, not just an instruction so lower it to the ptest
10222  // or testp pattern and a setcc for the result.
10223  case Intrinsic::x86_sse41_ptestz:
10224  case Intrinsic::x86_sse41_ptestc:
10225  case Intrinsic::x86_sse41_ptestnzc:
10226  case Intrinsic::x86_avx_ptestz_256:
10227  case Intrinsic::x86_avx_ptestc_256:
10228  case Intrinsic::x86_avx_ptestnzc_256:
10229  case Intrinsic::x86_avx_vtestz_ps:
10230  case Intrinsic::x86_avx_vtestc_ps:
10231  case Intrinsic::x86_avx_vtestnzc_ps:
10232  case Intrinsic::x86_avx_vtestz_pd:
10233  case Intrinsic::x86_avx_vtestc_pd:
10234  case Intrinsic::x86_avx_vtestnzc_pd:
10235  case Intrinsic::x86_avx_vtestz_ps_256:
10236  case Intrinsic::x86_avx_vtestc_ps_256:
10237  case Intrinsic::x86_avx_vtestnzc_ps_256:
10238  case Intrinsic::x86_avx_vtestz_pd_256:
10239  case Intrinsic::x86_avx_vtestc_pd_256:
10240  case Intrinsic::x86_avx_vtestnzc_pd_256: {
10241    bool IsTestPacked = false;
10242    unsigned X86CC;
10243    switch (IntNo) {
10244    default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
10245    case Intrinsic::x86_avx_vtestz_ps:
10246    case Intrinsic::x86_avx_vtestz_pd:
10247    case Intrinsic::x86_avx_vtestz_ps_256:
10248    case Intrinsic::x86_avx_vtestz_pd_256:
10249      IsTestPacked = true; // Fallthrough
10250    case Intrinsic::x86_sse41_ptestz:
10251    case Intrinsic::x86_avx_ptestz_256:
10252      // ZF = 1
10253      X86CC = X86::COND_E;
10254      break;
10255    case Intrinsic::x86_avx_vtestc_ps:
10256    case Intrinsic::x86_avx_vtestc_pd:
10257    case Intrinsic::x86_avx_vtestc_ps_256:
10258    case Intrinsic::x86_avx_vtestc_pd_256:
10259      IsTestPacked = true; // Fallthrough
10260    case Intrinsic::x86_sse41_ptestc:
10261    case Intrinsic::x86_avx_ptestc_256:
10262      // CF = 1
10263      X86CC = X86::COND_B;
10264      break;
10265    case Intrinsic::x86_avx_vtestnzc_ps:
10266    case Intrinsic::x86_avx_vtestnzc_pd:
10267    case Intrinsic::x86_avx_vtestnzc_ps_256:
10268    case Intrinsic::x86_avx_vtestnzc_pd_256:
10269      IsTestPacked = true; // Fallthrough
10270    case Intrinsic::x86_sse41_ptestnzc:
10271    case Intrinsic::x86_avx_ptestnzc_256:
10272      // ZF and CF = 0
10273      X86CC = X86::COND_A;
10274      break;
10275    }
10276
10277    SDValue LHS = Op.getOperand(1);
10278    SDValue RHS = Op.getOperand(2);
10279    unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
10280    SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
10281    SDValue CC = DAG.getConstant(X86CC, MVT::i8);
10282    SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
10283    return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
10284  }
10285
10286  // SSE/AVX shift intrinsics
10287  case Intrinsic::x86_sse2_psll_w:
10288  case Intrinsic::x86_sse2_psll_d:
10289  case Intrinsic::x86_sse2_psll_q:
10290  case Intrinsic::x86_avx2_psll_w:
10291  case Intrinsic::x86_avx2_psll_d:
10292  case Intrinsic::x86_avx2_psll_q:
10293  case Intrinsic::x86_sse2_psrl_w:
10294  case Intrinsic::x86_sse2_psrl_d:
10295  case Intrinsic::x86_sse2_psrl_q:
10296  case Intrinsic::x86_avx2_psrl_w:
10297  case Intrinsic::x86_avx2_psrl_d:
10298  case Intrinsic::x86_avx2_psrl_q:
10299  case Intrinsic::x86_sse2_psra_w:
10300  case Intrinsic::x86_sse2_psra_d:
10301  case Intrinsic::x86_avx2_psra_w:
10302  case Intrinsic::x86_avx2_psra_d: {
10303    unsigned Opcode;
10304    switch (IntNo) {
10305    default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
10306    case Intrinsic::x86_sse2_psll_w:
10307    case Intrinsic::x86_sse2_psll_d:
10308    case Intrinsic::x86_sse2_psll_q:
10309    case Intrinsic::x86_avx2_psll_w:
10310    case Intrinsic::x86_avx2_psll_d:
10311    case Intrinsic::x86_avx2_psll_q:
10312      Opcode = X86ISD::VSHL;
10313      break;
10314    case Intrinsic::x86_sse2_psrl_w:
10315    case Intrinsic::x86_sse2_psrl_d:
10316    case Intrinsic::x86_sse2_psrl_q:
10317    case Intrinsic::x86_avx2_psrl_w:
10318    case Intrinsic::x86_avx2_psrl_d:
10319    case Intrinsic::x86_avx2_psrl_q:
10320      Opcode = X86ISD::VSRL;
10321      break;
10322    case Intrinsic::x86_sse2_psra_w:
10323    case Intrinsic::x86_sse2_psra_d:
10324    case Intrinsic::x86_avx2_psra_w:
10325    case Intrinsic::x86_avx2_psra_d:
10326      Opcode = X86ISD::VSRA;
10327      break;
10328    }
10329    return DAG.getNode(Opcode, dl, Op.getValueType(),
10330                       Op.getOperand(1), Op.getOperand(2));
10331  }
10332
10333  // SSE/AVX immediate shift intrinsics
10334  case Intrinsic::x86_sse2_pslli_w:
10335  case Intrinsic::x86_sse2_pslli_d:
10336  case Intrinsic::x86_sse2_pslli_q:
10337  case Intrinsic::x86_avx2_pslli_w:
10338  case Intrinsic::x86_avx2_pslli_d:
10339  case Intrinsic::x86_avx2_pslli_q:
10340  case Intrinsic::x86_sse2_psrli_w:
10341  case Intrinsic::x86_sse2_psrli_d:
10342  case Intrinsic::x86_sse2_psrli_q:
10343  case Intrinsic::x86_avx2_psrli_w:
10344  case Intrinsic::x86_avx2_psrli_d:
10345  case Intrinsic::x86_avx2_psrli_q:
10346  case Intrinsic::x86_sse2_psrai_w:
10347  case Intrinsic::x86_sse2_psrai_d:
10348  case Intrinsic::x86_avx2_psrai_w:
10349  case Intrinsic::x86_avx2_psrai_d: {
10350    unsigned Opcode;
10351    switch (IntNo) {
10352    default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
10353    case Intrinsic::x86_sse2_pslli_w:
10354    case Intrinsic::x86_sse2_pslli_d:
10355    case Intrinsic::x86_sse2_pslli_q:
10356    case Intrinsic::x86_avx2_pslli_w:
10357    case Intrinsic::x86_avx2_pslli_d:
10358    case Intrinsic::x86_avx2_pslli_q:
10359      Opcode = X86ISD::VSHLI;
10360      break;
10361    case Intrinsic::x86_sse2_psrli_w:
10362    case Intrinsic::x86_sse2_psrli_d:
10363    case Intrinsic::x86_sse2_psrli_q:
10364    case Intrinsic::x86_avx2_psrli_w:
10365    case Intrinsic::x86_avx2_psrli_d:
10366    case Intrinsic::x86_avx2_psrli_q:
10367      Opcode = X86ISD::VSRLI;
10368      break;
10369    case Intrinsic::x86_sse2_psrai_w:
10370    case Intrinsic::x86_sse2_psrai_d:
10371    case Intrinsic::x86_avx2_psrai_w:
10372    case Intrinsic::x86_avx2_psrai_d:
10373      Opcode = X86ISD::VSRAI;
10374      break;
10375    }
10376    return getTargetVShiftNode(Opcode, dl, Op.getValueType(),
10377                               Op.getOperand(1), Op.getOperand(2), DAG);
10378  }
10379
10380  case Intrinsic::x86_sse42_pcmpistria128:
10381  case Intrinsic::x86_sse42_pcmpestria128:
10382  case Intrinsic::x86_sse42_pcmpistric128:
10383  case Intrinsic::x86_sse42_pcmpestric128:
10384  case Intrinsic::x86_sse42_pcmpistrio128:
10385  case Intrinsic::x86_sse42_pcmpestrio128:
10386  case Intrinsic::x86_sse42_pcmpistris128:
10387  case Intrinsic::x86_sse42_pcmpestris128:
10388  case Intrinsic::x86_sse42_pcmpistriz128:
10389  case Intrinsic::x86_sse42_pcmpestriz128: {
10390    unsigned Opcode;
10391    unsigned X86CC;
10392    switch (IntNo) {
10393    default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
10394    case Intrinsic::x86_sse42_pcmpistria128:
10395      Opcode = X86ISD::PCMPISTRI;
10396      X86CC = X86::COND_A;
10397      break;
10398    case Intrinsic::x86_sse42_pcmpestria128:
10399      Opcode = X86ISD::PCMPESTRI;
10400      X86CC = X86::COND_A;
10401      break;
10402    case Intrinsic::x86_sse42_pcmpistric128:
10403      Opcode = X86ISD::PCMPISTRI;
10404      X86CC = X86::COND_B;
10405      break;
10406    case Intrinsic::x86_sse42_pcmpestric128:
10407      Opcode = X86ISD::PCMPESTRI;
10408      X86CC = X86::COND_B;
10409      break;
10410    case Intrinsic::x86_sse42_pcmpistrio128:
10411      Opcode = X86ISD::PCMPISTRI;
10412      X86CC = X86::COND_O;
10413      break;
10414    case Intrinsic::x86_sse42_pcmpestrio128:
10415      Opcode = X86ISD::PCMPESTRI;
10416      X86CC = X86::COND_O;
10417      break;
10418    case Intrinsic::x86_sse42_pcmpistris128:
10419      Opcode = X86ISD::PCMPISTRI;
10420      X86CC = X86::COND_S;
10421      break;
10422    case Intrinsic::x86_sse42_pcmpestris128:
10423      Opcode = X86ISD::PCMPESTRI;
10424      X86CC = X86::COND_S;
10425      break;
10426    case Intrinsic::x86_sse42_pcmpistriz128:
10427      Opcode = X86ISD::PCMPISTRI;
10428      X86CC = X86::COND_E;
10429      break;
10430    case Intrinsic::x86_sse42_pcmpestriz128:
10431      Opcode = X86ISD::PCMPESTRI;
10432      X86CC = X86::COND_E;
10433      break;
10434    }
10435    SmallVector<SDValue, 5> NewOps;
10436    NewOps.append(Op->op_begin()+1, Op->op_end());
10437    SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
10438    SDValue PCMP = DAG.getNode(Opcode, dl, VTs, NewOps.data(), NewOps.size());
10439    SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
10440                                DAG.getConstant(X86CC, MVT::i8),
10441                                SDValue(PCMP.getNode(), 1));
10442    return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
10443  }
10444
10445  case Intrinsic::x86_sse42_pcmpistri128:
10446  case Intrinsic::x86_sse42_pcmpestri128: {
10447    unsigned Opcode;
10448    if (IntNo == Intrinsic::x86_sse42_pcmpistri128)
10449      Opcode = X86ISD::PCMPISTRI;
10450    else
10451      Opcode = X86ISD::PCMPESTRI;
10452
10453    SmallVector<SDValue, 5> NewOps;
10454    NewOps.append(Op->op_begin()+1, Op->op_end());
10455    SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
10456    return DAG.getNode(Opcode, dl, VTs, NewOps.data(), NewOps.size());
10457  }
10458  case Intrinsic::x86_fma_vfmadd_ps:
10459  case Intrinsic::x86_fma_vfmadd_pd:
10460  case Intrinsic::x86_fma_vfmsub_ps:
10461  case Intrinsic::x86_fma_vfmsub_pd:
10462  case Intrinsic::x86_fma_vfnmadd_ps:
10463  case Intrinsic::x86_fma_vfnmadd_pd:
10464  case Intrinsic::x86_fma_vfnmsub_ps:
10465  case Intrinsic::x86_fma_vfnmsub_pd:
10466  case Intrinsic::x86_fma_vfmaddsub_ps:
10467  case Intrinsic::x86_fma_vfmaddsub_pd:
10468  case Intrinsic::x86_fma_vfmsubadd_ps:
10469  case Intrinsic::x86_fma_vfmsubadd_pd:
10470  case Intrinsic::x86_fma_vfmadd_ps_256:
10471  case Intrinsic::x86_fma_vfmadd_pd_256:
10472  case Intrinsic::x86_fma_vfmsub_ps_256:
10473  case Intrinsic::x86_fma_vfmsub_pd_256:
10474  case Intrinsic::x86_fma_vfnmadd_ps_256:
10475  case Intrinsic::x86_fma_vfnmadd_pd_256:
10476  case Intrinsic::x86_fma_vfnmsub_ps_256:
10477  case Intrinsic::x86_fma_vfnmsub_pd_256:
10478  case Intrinsic::x86_fma_vfmaddsub_ps_256:
10479  case Intrinsic::x86_fma_vfmaddsub_pd_256:
10480  case Intrinsic::x86_fma_vfmsubadd_ps_256:
10481  case Intrinsic::x86_fma_vfmsubadd_pd_256: {
10482    unsigned Opc;
10483    switch (IntNo) {
10484    default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
10485    case Intrinsic::x86_fma_vfmadd_ps:
10486    case Intrinsic::x86_fma_vfmadd_pd:
10487    case Intrinsic::x86_fma_vfmadd_ps_256:
10488    case Intrinsic::x86_fma_vfmadd_pd_256:
10489      Opc = X86ISD::FMADD;
10490      break;
10491    case Intrinsic::x86_fma_vfmsub_ps:
10492    case Intrinsic::x86_fma_vfmsub_pd:
10493    case Intrinsic::x86_fma_vfmsub_ps_256:
10494    case Intrinsic::x86_fma_vfmsub_pd_256:
10495      Opc = X86ISD::FMSUB;
10496      break;
10497    case Intrinsic::x86_fma_vfnmadd_ps:
10498    case Intrinsic::x86_fma_vfnmadd_pd:
10499    case Intrinsic::x86_fma_vfnmadd_ps_256:
10500    case Intrinsic::x86_fma_vfnmadd_pd_256:
10501      Opc = X86ISD::FNMADD;
10502      break;
10503    case Intrinsic::x86_fma_vfnmsub_ps:
10504    case Intrinsic::x86_fma_vfnmsub_pd:
10505    case Intrinsic::x86_fma_vfnmsub_ps_256:
10506    case Intrinsic::x86_fma_vfnmsub_pd_256:
10507      Opc = X86ISD::FNMSUB;
10508      break;
10509    case Intrinsic::x86_fma_vfmaddsub_ps:
10510    case Intrinsic::x86_fma_vfmaddsub_pd:
10511    case Intrinsic::x86_fma_vfmaddsub_ps_256:
10512    case Intrinsic::x86_fma_vfmaddsub_pd_256:
10513      Opc = X86ISD::FMADDSUB;
10514      break;
10515    case Intrinsic::x86_fma_vfmsubadd_ps:
10516    case Intrinsic::x86_fma_vfmsubadd_pd:
10517    case Intrinsic::x86_fma_vfmsubadd_ps_256:
10518    case Intrinsic::x86_fma_vfmsubadd_pd_256:
10519      Opc = X86ISD::FMSUBADD;
10520      break;
10521    }
10522
10523    return DAG.getNode(Opc, dl, Op.getValueType(), Op.getOperand(1),
10524                       Op.getOperand(2), Op.getOperand(3));
10525  }
10526  }
10527}
10528
10529static SDValue LowerINTRINSIC_W_CHAIN(SDValue Op, SelectionDAG &DAG) {
10530  DebugLoc dl = Op.getDebugLoc();
10531  unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10532  switch (IntNo) {
10533  default: return SDValue();    // Don't custom lower most intrinsics.
10534
10535  // RDRAND intrinsics.
10536  case Intrinsic::x86_rdrand_16:
10537  case Intrinsic::x86_rdrand_32:
10538  case Intrinsic::x86_rdrand_64: {
10539    // Emit the node with the right value type.
10540    SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Glue, MVT::Other);
10541    SDValue Result = DAG.getNode(X86ISD::RDRAND, dl, VTs, Op.getOperand(0));
10542
10543    // If the value returned by RDRAND was valid (CF=1), return 1. Otherwise
10544    // return the value from Rand, which is always 0, casted to i32.
10545    SDValue Ops[] = { DAG.getZExtOrTrunc(Result, dl, Op->getValueType(1)),
10546                      DAG.getConstant(1, Op->getValueType(1)),
10547                      DAG.getConstant(X86::COND_B, MVT::i32),
10548                      SDValue(Result.getNode(), 1) };
10549    SDValue isValid = DAG.getNode(X86ISD::CMOV, dl,
10550                                  DAG.getVTList(Op->getValueType(1), MVT::Glue),
10551                                  Ops, 4);
10552
10553    // Return { result, isValid, chain }.
10554    return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), Result, isValid,
10555                       SDValue(Result.getNode(), 2));
10556  }
10557  }
10558}
10559
10560SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
10561                                           SelectionDAG &DAG) const {
10562  MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
10563  MFI->setReturnAddressIsTaken(true);
10564
10565  unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
10566  DebugLoc dl = Op.getDebugLoc();
10567  EVT PtrVT = getPointerTy();
10568
10569  if (Depth > 0) {
10570    SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
10571    SDValue Offset =
10572      DAG.getConstant(RegInfo->getSlotSize(), PtrVT);
10573    return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
10574                       DAG.getNode(ISD::ADD, dl, PtrVT,
10575                                   FrameAddr, Offset),
10576                       MachinePointerInfo(), false, false, false, 0);
10577  }
10578
10579  // Just load the return address.
10580  SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
10581  return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
10582                     RetAddrFI, MachinePointerInfo(), false, false, false, 0);
10583}
10584
10585SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
10586  MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
10587  MFI->setFrameAddressIsTaken(true);
10588
10589  EVT VT = Op.getValueType();
10590  DebugLoc dl = Op.getDebugLoc();  // FIXME probably not meaningful
10591  unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
10592  unsigned FrameReg = Subtarget->is64Bit() ? X86::RBP : X86::EBP;
10593  SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
10594  while (Depth--)
10595    FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
10596                            MachinePointerInfo(),
10597                            false, false, false, 0);
10598  return FrameAddr;
10599}
10600
10601SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
10602                                                     SelectionDAG &DAG) const {
10603  return DAG.getIntPtrConstant(2 * RegInfo->getSlotSize());
10604}
10605
10606SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
10607  SDValue Chain     = Op.getOperand(0);
10608  SDValue Offset    = Op.getOperand(1);
10609  SDValue Handler   = Op.getOperand(2);
10610  DebugLoc dl       = Op.getDebugLoc();
10611
10612  SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl,
10613                                     Subtarget->is64Bit() ? X86::RBP : X86::EBP,
10614                                     getPointerTy());
10615  unsigned StoreAddrReg = (Subtarget->is64Bit() ? X86::RCX : X86::ECX);
10616
10617  SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), Frame,
10618                                  DAG.getIntPtrConstant(RegInfo->getSlotSize()));
10619  StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), StoreAddr, Offset);
10620  Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
10621                       false, false, 0);
10622  Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
10623
10624  return DAG.getNode(X86ISD::EH_RETURN, dl,
10625                     MVT::Other,
10626                     Chain, DAG.getRegister(StoreAddrReg, getPointerTy()));
10627}
10628
10629SDValue X86TargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
10630                                               SelectionDAG &DAG) const {
10631  DebugLoc DL = Op.getDebugLoc();
10632  return DAG.getNode(X86ISD::EH_SJLJ_SETJMP, DL,
10633                     DAG.getVTList(MVT::i32, MVT::Other),
10634                     Op.getOperand(0), Op.getOperand(1));
10635}
10636
10637SDValue X86TargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
10638                                                SelectionDAG &DAG) const {
10639  DebugLoc DL = Op.getDebugLoc();
10640  return DAG.getNode(X86ISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
10641                     Op.getOperand(0), Op.getOperand(1));
10642}
10643
10644static SDValue LowerADJUST_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) {
10645  return Op.getOperand(0);
10646}
10647
10648SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
10649                                                SelectionDAG &DAG) const {
10650  SDValue Root = Op.getOperand(0);
10651  SDValue Trmp = Op.getOperand(1); // trampoline
10652  SDValue FPtr = Op.getOperand(2); // nested function
10653  SDValue Nest = Op.getOperand(3); // 'nest' parameter value
10654  DebugLoc dl  = Op.getDebugLoc();
10655
10656  const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
10657  const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
10658
10659  if (Subtarget->is64Bit()) {
10660    SDValue OutChains[6];
10661
10662    // Large code-model.
10663    const unsigned char JMP64r  = 0xFF; // 64-bit jmp through register opcode.
10664    const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
10665
10666    const unsigned char N86R10 = TRI->getEncodingValue(X86::R10) & 0x7;
10667    const unsigned char N86R11 = TRI->getEncodingValue(X86::R11) & 0x7;
10668
10669    const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
10670
10671    // Load the pointer to the nested function into R11.
10672    unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
10673    SDValue Addr = Trmp;
10674    OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
10675                                Addr, MachinePointerInfo(TrmpAddr),
10676                                false, false, 0);
10677
10678    Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
10679                       DAG.getConstant(2, MVT::i64));
10680    OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
10681                                MachinePointerInfo(TrmpAddr, 2),
10682                                false, false, 2);
10683
10684    // Load the 'nest' parameter value into R10.
10685    // R10 is specified in X86CallingConv.td
10686    OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
10687    Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
10688                       DAG.getConstant(10, MVT::i64));
10689    OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
10690                                Addr, MachinePointerInfo(TrmpAddr, 10),
10691                                false, false, 0);
10692
10693    Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
10694                       DAG.getConstant(12, MVT::i64));
10695    OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
10696                                MachinePointerInfo(TrmpAddr, 12),
10697                                false, false, 2);
10698
10699    // Jump to the nested function.
10700    OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
10701    Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
10702                       DAG.getConstant(20, MVT::i64));
10703    OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
10704                                Addr, MachinePointerInfo(TrmpAddr, 20),
10705                                false, false, 0);
10706
10707    unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
10708    Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
10709                       DAG.getConstant(22, MVT::i64));
10710    OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
10711                                MachinePointerInfo(TrmpAddr, 22),
10712                                false, false, 0);
10713
10714    return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 6);
10715  } else {
10716    const Function *Func =
10717      cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
10718    CallingConv::ID CC = Func->getCallingConv();
10719    unsigned NestReg;
10720
10721    switch (CC) {
10722    default:
10723      llvm_unreachable("Unsupported calling convention");
10724    case CallingConv::C:
10725    case CallingConv::X86_StdCall: {
10726      // Pass 'nest' parameter in ECX.
10727      // Must be kept in sync with X86CallingConv.td
10728      NestReg = X86::ECX;
10729
10730      // Check that ECX wasn't needed by an 'inreg' parameter.
10731      FunctionType *FTy = Func->getFunctionType();
10732      const AttrListPtr &Attrs = Func->getAttributes();
10733
10734      if (!Attrs.isEmpty() && !Func->isVarArg()) {
10735        unsigned InRegCount = 0;
10736        unsigned Idx = 1;
10737
10738        for (FunctionType::param_iterator I = FTy->param_begin(),
10739             E = FTy->param_end(); I != E; ++I, ++Idx)
10740          if (Attrs.getParamAttributes(Idx).hasAttribute(Attributes::InReg))
10741            // FIXME: should only count parameters that are lowered to integers.
10742            InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
10743
10744        if (InRegCount > 2) {
10745          report_fatal_error("Nest register in use - reduce number of inreg"
10746                             " parameters!");
10747        }
10748      }
10749      break;
10750    }
10751    case CallingConv::X86_FastCall:
10752    case CallingConv::X86_ThisCall:
10753    case CallingConv::Fast:
10754      // Pass 'nest' parameter in EAX.
10755      // Must be kept in sync with X86CallingConv.td
10756      NestReg = X86::EAX;
10757      break;
10758    }
10759
10760    SDValue OutChains[4];
10761    SDValue Addr, Disp;
10762
10763    Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
10764                       DAG.getConstant(10, MVT::i32));
10765    Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
10766
10767    // This is storing the opcode for MOV32ri.
10768    const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
10769    const unsigned char N86Reg = TRI->getEncodingValue(NestReg) & 0x7;
10770    OutChains[0] = DAG.getStore(Root, dl,
10771                                DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
10772                                Trmp, MachinePointerInfo(TrmpAddr),
10773                                false, false, 0);
10774
10775    Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
10776                       DAG.getConstant(1, MVT::i32));
10777    OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
10778                                MachinePointerInfo(TrmpAddr, 1),
10779                                false, false, 1);
10780
10781    const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
10782    Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
10783                       DAG.getConstant(5, MVT::i32));
10784    OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
10785                                MachinePointerInfo(TrmpAddr, 5),
10786                                false, false, 1);
10787
10788    Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
10789                       DAG.getConstant(6, MVT::i32));
10790    OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
10791                                MachinePointerInfo(TrmpAddr, 6),
10792                                false, false, 1);
10793
10794    return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 4);
10795  }
10796}
10797
10798SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
10799                                            SelectionDAG &DAG) const {
10800  /*
10801   The rounding mode is in bits 11:10 of FPSR, and has the following
10802   settings:
10803     00 Round to nearest
10804     01 Round to -inf
10805     10 Round to +inf
10806     11 Round to 0
10807
10808  FLT_ROUNDS, on the other hand, expects the following:
10809    -1 Undefined
10810     0 Round to 0
10811     1 Round to nearest
10812     2 Round to +inf
10813     3 Round to -inf
10814
10815  To perform the conversion, we do:
10816    (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
10817  */
10818
10819  MachineFunction &MF = DAG.getMachineFunction();
10820  const TargetMachine &TM = MF.getTarget();
10821  const TargetFrameLowering &TFI = *TM.getFrameLowering();
10822  unsigned StackAlignment = TFI.getStackAlignment();
10823  EVT VT = Op.getValueType();
10824  DebugLoc DL = Op.getDebugLoc();
10825
10826  // Save FP Control Word to stack slot
10827  int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
10828  SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
10829
10830
10831  MachineMemOperand *MMO =
10832   MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
10833                           MachineMemOperand::MOStore, 2, 2);
10834
10835  SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
10836  SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
10837                                          DAG.getVTList(MVT::Other),
10838                                          Ops, 2, MVT::i16, MMO);
10839
10840  // Load FP Control Word from stack slot
10841  SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
10842                            MachinePointerInfo(), false, false, false, 0);
10843
10844  // Transform as necessary
10845  SDValue CWD1 =
10846    DAG.getNode(ISD::SRL, DL, MVT::i16,
10847                DAG.getNode(ISD::AND, DL, MVT::i16,
10848                            CWD, DAG.getConstant(0x800, MVT::i16)),
10849                DAG.getConstant(11, MVT::i8));
10850  SDValue CWD2 =
10851    DAG.getNode(ISD::SRL, DL, MVT::i16,
10852                DAG.getNode(ISD::AND, DL, MVT::i16,
10853                            CWD, DAG.getConstant(0x400, MVT::i16)),
10854                DAG.getConstant(9, MVT::i8));
10855
10856  SDValue RetVal =
10857    DAG.getNode(ISD::AND, DL, MVT::i16,
10858                DAG.getNode(ISD::ADD, DL, MVT::i16,
10859                            DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
10860                            DAG.getConstant(1, MVT::i16)),
10861                DAG.getConstant(3, MVT::i16));
10862
10863
10864  return DAG.getNode((VT.getSizeInBits() < 16 ?
10865                      ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
10866}
10867
10868static SDValue LowerCTLZ(SDValue Op, SelectionDAG &DAG) {
10869  EVT VT = Op.getValueType();
10870  EVT OpVT = VT;
10871  unsigned NumBits = VT.getSizeInBits();
10872  DebugLoc dl = Op.getDebugLoc();
10873
10874  Op = Op.getOperand(0);
10875  if (VT == MVT::i8) {
10876    // Zero extend to i32 since there is not an i8 bsr.
10877    OpVT = MVT::i32;
10878    Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
10879  }
10880
10881  // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
10882  SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
10883  Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
10884
10885  // If src is zero (i.e. bsr sets ZF), returns NumBits.
10886  SDValue Ops[] = {
10887    Op,
10888    DAG.getConstant(NumBits+NumBits-1, OpVT),
10889    DAG.getConstant(X86::COND_E, MVT::i8),
10890    Op.getValue(1)
10891  };
10892  Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
10893
10894  // Finally xor with NumBits-1.
10895  Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
10896
10897  if (VT == MVT::i8)
10898    Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
10899  return Op;
10900}
10901
10902static SDValue LowerCTLZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) {
10903  EVT VT = Op.getValueType();
10904  EVT OpVT = VT;
10905  unsigned NumBits = VT.getSizeInBits();
10906  DebugLoc dl = Op.getDebugLoc();
10907
10908  Op = Op.getOperand(0);
10909  if (VT == MVT::i8) {
10910    // Zero extend to i32 since there is not an i8 bsr.
10911    OpVT = MVT::i32;
10912    Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
10913  }
10914
10915  // Issue a bsr (scan bits in reverse).
10916  SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
10917  Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
10918
10919  // And xor with NumBits-1.
10920  Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
10921
10922  if (VT == MVT::i8)
10923    Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
10924  return Op;
10925}
10926
10927static SDValue LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
10928  EVT VT = Op.getValueType();
10929  unsigned NumBits = VT.getSizeInBits();
10930  DebugLoc dl = Op.getDebugLoc();
10931  Op = Op.getOperand(0);
10932
10933  // Issue a bsf (scan bits forward) which also sets EFLAGS.
10934  SDVTList VTs = DAG.getVTList(VT, MVT::i32);
10935  Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
10936
10937  // If src is zero (i.e. bsf sets ZF), returns NumBits.
10938  SDValue Ops[] = {
10939    Op,
10940    DAG.getConstant(NumBits, VT),
10941    DAG.getConstant(X86::COND_E, MVT::i8),
10942    Op.getValue(1)
10943  };
10944  return DAG.getNode(X86ISD::CMOV, dl, VT, Ops, array_lengthof(Ops));
10945}
10946
10947// Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
10948// ones, and then concatenate the result back.
10949static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
10950  EVT VT = Op.getValueType();
10951
10952  assert(VT.is256BitVector() && VT.isInteger() &&
10953         "Unsupported value type for operation");
10954
10955  unsigned NumElems = VT.getVectorNumElements();
10956  DebugLoc dl = Op.getDebugLoc();
10957
10958  // Extract the LHS vectors
10959  SDValue LHS = Op.getOperand(0);
10960  SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
10961  SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
10962
10963  // Extract the RHS vectors
10964  SDValue RHS = Op.getOperand(1);
10965  SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
10966  SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
10967
10968  MVT EltVT = VT.getVectorElementType().getSimpleVT();
10969  EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
10970
10971  return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
10972                     DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
10973                     DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
10974}
10975
10976static SDValue LowerADD(SDValue Op, SelectionDAG &DAG) {
10977  assert(Op.getValueType().is256BitVector() &&
10978         Op.getValueType().isInteger() &&
10979         "Only handle AVX 256-bit vector integer operation");
10980  return Lower256IntArith(Op, DAG);
10981}
10982
10983static SDValue LowerSUB(SDValue Op, SelectionDAG &DAG) {
10984  assert(Op.getValueType().is256BitVector() &&
10985         Op.getValueType().isInteger() &&
10986         "Only handle AVX 256-bit vector integer operation");
10987  return Lower256IntArith(Op, DAG);
10988}
10989
10990static SDValue LowerMUL(SDValue Op, const X86Subtarget *Subtarget,
10991                        SelectionDAG &DAG) {
10992  EVT VT = Op.getValueType();
10993
10994  // Decompose 256-bit ops into smaller 128-bit ops.
10995  if (VT.is256BitVector() && !Subtarget->hasAVX2())
10996    return Lower256IntArith(Op, DAG);
10997
10998  assert((VT == MVT::v2i64 || VT == MVT::v4i64) &&
10999         "Only know how to lower V2I64/V4I64 multiply");
11000
11001  DebugLoc dl = Op.getDebugLoc();
11002
11003  //  Ahi = psrlqi(a, 32);
11004  //  Bhi = psrlqi(b, 32);
11005  //
11006  //  AloBlo = pmuludq(a, b);
11007  //  AloBhi = pmuludq(a, Bhi);
11008  //  AhiBlo = pmuludq(Ahi, b);
11009
11010  //  AloBhi = psllqi(AloBhi, 32);
11011  //  AhiBlo = psllqi(AhiBlo, 32);
11012  //  return AloBlo + AloBhi + AhiBlo;
11013
11014  SDValue A = Op.getOperand(0);
11015  SDValue B = Op.getOperand(1);
11016
11017  SDValue ShAmt = DAG.getConstant(32, MVT::i32);
11018
11019  SDValue Ahi = DAG.getNode(X86ISD::VSRLI, dl, VT, A, ShAmt);
11020  SDValue Bhi = DAG.getNode(X86ISD::VSRLI, dl, VT, B, ShAmt);
11021
11022  // Bit cast to 32-bit vectors for MULUDQ
11023  EVT MulVT = (VT == MVT::v2i64) ? MVT::v4i32 : MVT::v8i32;
11024  A = DAG.getNode(ISD::BITCAST, dl, MulVT, A);
11025  B = DAG.getNode(ISD::BITCAST, dl, MulVT, B);
11026  Ahi = DAG.getNode(ISD::BITCAST, dl, MulVT, Ahi);
11027  Bhi = DAG.getNode(ISD::BITCAST, dl, MulVT, Bhi);
11028
11029  SDValue AloBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, B);
11030  SDValue AloBhi = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, Bhi);
11031  SDValue AhiBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, Ahi, B);
11032
11033  AloBhi = DAG.getNode(X86ISD::VSHLI, dl, VT, AloBhi, ShAmt);
11034  AhiBlo = DAG.getNode(X86ISD::VSHLI, dl, VT, AhiBlo, ShAmt);
11035
11036  SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
11037  return DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
11038}
11039
11040SDValue X86TargetLowering::LowerShift(SDValue Op, SelectionDAG &DAG) const {
11041
11042  EVT VT = Op.getValueType();
11043  DebugLoc dl = Op.getDebugLoc();
11044  SDValue R = Op.getOperand(0);
11045  SDValue Amt = Op.getOperand(1);
11046  LLVMContext *Context = DAG.getContext();
11047
11048  if (!Subtarget->hasSSE2())
11049    return SDValue();
11050
11051  // Optimize shl/srl/sra with constant shift amount.
11052  if (isSplatVector(Amt.getNode())) {
11053    SDValue SclrAmt = Amt->getOperand(0);
11054    if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt)) {
11055      uint64_t ShiftAmt = C->getZExtValue();
11056
11057      if (VT == MVT::v2i64 || VT == MVT::v4i32 || VT == MVT::v8i16 ||
11058          (Subtarget->hasAVX2() &&
11059           (VT == MVT::v4i64 || VT == MVT::v8i32 || VT == MVT::v16i16))) {
11060        if (Op.getOpcode() == ISD::SHL)
11061          return DAG.getNode(X86ISD::VSHLI, dl, VT, R,
11062                             DAG.getConstant(ShiftAmt, MVT::i32));
11063        if (Op.getOpcode() == ISD::SRL)
11064          return DAG.getNode(X86ISD::VSRLI, dl, VT, R,
11065                             DAG.getConstant(ShiftAmt, MVT::i32));
11066        if (Op.getOpcode() == ISD::SRA && VT != MVT::v2i64 && VT != MVT::v4i64)
11067          return DAG.getNode(X86ISD::VSRAI, dl, VT, R,
11068                             DAG.getConstant(ShiftAmt, MVT::i32));
11069      }
11070
11071      if (VT == MVT::v16i8) {
11072        if (Op.getOpcode() == ISD::SHL) {
11073          // Make a large shift.
11074          SDValue SHL = DAG.getNode(X86ISD::VSHLI, dl, MVT::v8i16, R,
11075                                    DAG.getConstant(ShiftAmt, MVT::i32));
11076          SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
11077          // Zero out the rightmost bits.
11078          SmallVector<SDValue, 16> V(16,
11079                                     DAG.getConstant(uint8_t(-1U << ShiftAmt),
11080                                                     MVT::i8));
11081          return DAG.getNode(ISD::AND, dl, VT, SHL,
11082                             DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16));
11083        }
11084        if (Op.getOpcode() == ISD::SRL) {
11085          // Make a large shift.
11086          SDValue SRL = DAG.getNode(X86ISD::VSRLI, dl, MVT::v8i16, R,
11087                                    DAG.getConstant(ShiftAmt, MVT::i32));
11088          SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
11089          // Zero out the leftmost bits.
11090          SmallVector<SDValue, 16> V(16,
11091                                     DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
11092                                                     MVT::i8));
11093          return DAG.getNode(ISD::AND, dl, VT, SRL,
11094                             DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16));
11095        }
11096        if (Op.getOpcode() == ISD::SRA) {
11097          if (ShiftAmt == 7) {
11098            // R s>> 7  ===  R s< 0
11099            SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
11100            return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
11101          }
11102
11103          // R s>> a === ((R u>> a) ^ m) - m
11104          SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
11105          SmallVector<SDValue, 16> V(16, DAG.getConstant(128 >> ShiftAmt,
11106                                                         MVT::i8));
11107          SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16);
11108          Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
11109          Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
11110          return Res;
11111        }
11112        llvm_unreachable("Unknown shift opcode.");
11113      }
11114
11115      if (Subtarget->hasAVX2() && VT == MVT::v32i8) {
11116        if (Op.getOpcode() == ISD::SHL) {
11117          // Make a large shift.
11118          SDValue SHL = DAG.getNode(X86ISD::VSHLI, dl, MVT::v16i16, R,
11119                                    DAG.getConstant(ShiftAmt, MVT::i32));
11120          SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
11121          // Zero out the rightmost bits.
11122          SmallVector<SDValue, 32> V(32,
11123                                     DAG.getConstant(uint8_t(-1U << ShiftAmt),
11124                                                     MVT::i8));
11125          return DAG.getNode(ISD::AND, dl, VT, SHL,
11126                             DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32));
11127        }
11128        if (Op.getOpcode() == ISD::SRL) {
11129          // Make a large shift.
11130          SDValue SRL = DAG.getNode(X86ISD::VSRLI, dl, MVT::v16i16, R,
11131                                    DAG.getConstant(ShiftAmt, MVT::i32));
11132          SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
11133          // Zero out the leftmost bits.
11134          SmallVector<SDValue, 32> V(32,
11135                                     DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
11136                                                     MVT::i8));
11137          return DAG.getNode(ISD::AND, dl, VT, SRL,
11138                             DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32));
11139        }
11140        if (Op.getOpcode() == ISD::SRA) {
11141          if (ShiftAmt == 7) {
11142            // R s>> 7  ===  R s< 0
11143            SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
11144            return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
11145          }
11146
11147          // R s>> a === ((R u>> a) ^ m) - m
11148          SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
11149          SmallVector<SDValue, 32> V(32, DAG.getConstant(128 >> ShiftAmt,
11150                                                         MVT::i8));
11151          SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32);
11152          Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
11153          Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
11154          return Res;
11155        }
11156        llvm_unreachable("Unknown shift opcode.");
11157      }
11158    }
11159  }
11160
11161  // Lower SHL with variable shift amount.
11162  if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
11163    Op = DAG.getNode(X86ISD::VSHLI, dl, VT, Op.getOperand(1),
11164                     DAG.getConstant(23, MVT::i32));
11165
11166    const uint32_t CV[] = { 0x3f800000U, 0x3f800000U, 0x3f800000U, 0x3f800000U};
11167    Constant *C = ConstantDataVector::get(*Context, CV);
11168    SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
11169    SDValue Addend = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
11170                                 MachinePointerInfo::getConstantPool(),
11171                                 false, false, false, 16);
11172
11173    Op = DAG.getNode(ISD::ADD, dl, VT, Op, Addend);
11174    Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, Op);
11175    Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
11176    return DAG.getNode(ISD::MUL, dl, VT, Op, R);
11177  }
11178  if (VT == MVT::v16i8 && Op->getOpcode() == ISD::SHL) {
11179    assert(Subtarget->hasSSE2() && "Need SSE2 for pslli/pcmpeq.");
11180
11181    // a = a << 5;
11182    Op = DAG.getNode(X86ISD::VSHLI, dl, MVT::v8i16, Op.getOperand(1),
11183                     DAG.getConstant(5, MVT::i32));
11184    Op = DAG.getNode(ISD::BITCAST, dl, VT, Op);
11185
11186    // Turn 'a' into a mask suitable for VSELECT
11187    SDValue VSelM = DAG.getConstant(0x80, VT);
11188    SDValue OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
11189    OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
11190
11191    SDValue CM1 = DAG.getConstant(0x0f, VT);
11192    SDValue CM2 = DAG.getConstant(0x3f, VT);
11193
11194    // r = VSELECT(r, psllw(r & (char16)15, 4), a);
11195    SDValue M = DAG.getNode(ISD::AND, dl, VT, R, CM1);
11196    M = getTargetVShiftNode(X86ISD::VSHLI, dl, MVT::v8i16, M,
11197                            DAG.getConstant(4, MVT::i32), DAG);
11198    M = DAG.getNode(ISD::BITCAST, dl, VT, M);
11199    R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
11200
11201    // a += a
11202    Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
11203    OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
11204    OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
11205
11206    // r = VSELECT(r, psllw(r & (char16)63, 2), a);
11207    M = DAG.getNode(ISD::AND, dl, VT, R, CM2);
11208    M = getTargetVShiftNode(X86ISD::VSHLI, dl, MVT::v8i16, M,
11209                            DAG.getConstant(2, MVT::i32), DAG);
11210    M = DAG.getNode(ISD::BITCAST, dl, VT, M);
11211    R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
11212
11213    // a += a
11214    Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
11215    OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
11216    OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
11217
11218    // return VSELECT(r, r+r, a);
11219    R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel,
11220                    DAG.getNode(ISD::ADD, dl, VT, R, R), R);
11221    return R;
11222  }
11223
11224  // Decompose 256-bit shifts into smaller 128-bit shifts.
11225  if (VT.is256BitVector()) {
11226    unsigned NumElems = VT.getVectorNumElements();
11227    MVT EltVT = VT.getVectorElementType().getSimpleVT();
11228    EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
11229
11230    // Extract the two vectors
11231    SDValue V1 = Extract128BitVector(R, 0, DAG, dl);
11232    SDValue V2 = Extract128BitVector(R, NumElems/2, DAG, dl);
11233
11234    // Recreate the shift amount vectors
11235    SDValue Amt1, Amt2;
11236    if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
11237      // Constant shift amount
11238      SmallVector<SDValue, 4> Amt1Csts;
11239      SmallVector<SDValue, 4> Amt2Csts;
11240      for (unsigned i = 0; i != NumElems/2; ++i)
11241        Amt1Csts.push_back(Amt->getOperand(i));
11242      for (unsigned i = NumElems/2; i != NumElems; ++i)
11243        Amt2Csts.push_back(Amt->getOperand(i));
11244
11245      Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT,
11246                                 &Amt1Csts[0], NumElems/2);
11247      Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT,
11248                                 &Amt2Csts[0], NumElems/2);
11249    } else {
11250      // Variable shift amount
11251      Amt1 = Extract128BitVector(Amt, 0, DAG, dl);
11252      Amt2 = Extract128BitVector(Amt, NumElems/2, DAG, dl);
11253    }
11254
11255    // Issue new vector shifts for the smaller types
11256    V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
11257    V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
11258
11259    // Concatenate the result back
11260    return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
11261  }
11262
11263  return SDValue();
11264}
11265
11266static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
11267  // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
11268  // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
11269  // looks for this combo and may remove the "setcc" instruction if the "setcc"
11270  // has only one use.
11271  SDNode *N = Op.getNode();
11272  SDValue LHS = N->getOperand(0);
11273  SDValue RHS = N->getOperand(1);
11274  unsigned BaseOp = 0;
11275  unsigned Cond = 0;
11276  DebugLoc DL = Op.getDebugLoc();
11277  switch (Op.getOpcode()) {
11278  default: llvm_unreachable("Unknown ovf instruction!");
11279  case ISD::SADDO:
11280    // A subtract of one will be selected as a INC. Note that INC doesn't
11281    // set CF, so we can't do this for UADDO.
11282    if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
11283      if (C->isOne()) {
11284        BaseOp = X86ISD::INC;
11285        Cond = X86::COND_O;
11286        break;
11287      }
11288    BaseOp = X86ISD::ADD;
11289    Cond = X86::COND_O;
11290    break;
11291  case ISD::UADDO:
11292    BaseOp = X86ISD::ADD;
11293    Cond = X86::COND_B;
11294    break;
11295  case ISD::SSUBO:
11296    // A subtract of one will be selected as a DEC. Note that DEC doesn't
11297    // set CF, so we can't do this for USUBO.
11298    if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
11299      if (C->isOne()) {
11300        BaseOp = X86ISD::DEC;
11301        Cond = X86::COND_O;
11302        break;
11303      }
11304    BaseOp = X86ISD::SUB;
11305    Cond = X86::COND_O;
11306    break;
11307  case ISD::USUBO:
11308    BaseOp = X86ISD::SUB;
11309    Cond = X86::COND_B;
11310    break;
11311  case ISD::SMULO:
11312    BaseOp = X86ISD::SMUL;
11313    Cond = X86::COND_O;
11314    break;
11315  case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
11316    SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
11317                                 MVT::i32);
11318    SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
11319
11320    SDValue SetCC =
11321      DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
11322                  DAG.getConstant(X86::COND_O, MVT::i32),
11323                  SDValue(Sum.getNode(), 2));
11324
11325    return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
11326  }
11327  }
11328
11329  // Also sets EFLAGS.
11330  SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
11331  SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
11332
11333  SDValue SetCC =
11334    DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
11335                DAG.getConstant(Cond, MVT::i32),
11336                SDValue(Sum.getNode(), 1));
11337
11338  return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
11339}
11340
11341SDValue X86TargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op,
11342                                                  SelectionDAG &DAG) const {
11343  DebugLoc dl = Op.getDebugLoc();
11344  EVT ExtraVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
11345  EVT VT = Op.getValueType();
11346
11347  if (!Subtarget->hasSSE2() || !VT.isVector())
11348    return SDValue();
11349
11350  unsigned BitsDiff = VT.getScalarType().getSizeInBits() -
11351                      ExtraVT.getScalarType().getSizeInBits();
11352  SDValue ShAmt = DAG.getConstant(BitsDiff, MVT::i32);
11353
11354  switch (VT.getSimpleVT().SimpleTy) {
11355    default: return SDValue();
11356    case MVT::v8i32:
11357    case MVT::v16i16:
11358      if (!Subtarget->hasAVX())
11359        return SDValue();
11360      if (!Subtarget->hasAVX2()) {
11361        // needs to be split
11362        unsigned NumElems = VT.getVectorNumElements();
11363
11364        // Extract the LHS vectors
11365        SDValue LHS = Op.getOperand(0);
11366        SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
11367        SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
11368
11369        MVT EltVT = VT.getVectorElementType().getSimpleVT();
11370        EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
11371
11372        EVT ExtraEltVT = ExtraVT.getVectorElementType();
11373        unsigned ExtraNumElems = ExtraVT.getVectorNumElements();
11374        ExtraVT = EVT::getVectorVT(*DAG.getContext(), ExtraEltVT,
11375                                   ExtraNumElems/2);
11376        SDValue Extra = DAG.getValueType(ExtraVT);
11377
11378        LHS1 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, Extra);
11379        LHS2 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, Extra);
11380
11381        return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, LHS1, LHS2);
11382      }
11383      // fall through
11384    case MVT::v4i32:
11385    case MVT::v8i16: {
11386      SDValue Tmp1 = getTargetVShiftNode(X86ISD::VSHLI, dl, VT,
11387                                         Op.getOperand(0), ShAmt, DAG);
11388      return getTargetVShiftNode(X86ISD::VSRAI, dl, VT, Tmp1, ShAmt, DAG);
11389    }
11390  }
11391}
11392
11393
11394static SDValue LowerMEMBARRIER(SDValue Op, const X86Subtarget *Subtarget,
11395                              SelectionDAG &DAG) {
11396  DebugLoc dl = Op.getDebugLoc();
11397
11398  // Go ahead and emit the fence on x86-64 even if we asked for no-sse2.
11399  // There isn't any reason to disable it if the target processor supports it.
11400  if (!Subtarget->hasSSE2() && !Subtarget->is64Bit()) {
11401    SDValue Chain = Op.getOperand(0);
11402    SDValue Zero = DAG.getConstant(0, MVT::i32);
11403    SDValue Ops[] = {
11404      DAG.getRegister(X86::ESP, MVT::i32), // Base
11405      DAG.getTargetConstant(1, MVT::i8),   // Scale
11406      DAG.getRegister(0, MVT::i32),        // Index
11407      DAG.getTargetConstant(0, MVT::i32),  // Disp
11408      DAG.getRegister(0, MVT::i32),        // Segment.
11409      Zero,
11410      Chain
11411    };
11412    SDNode *Res =
11413      DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops,
11414                          array_lengthof(Ops));
11415    return SDValue(Res, 0);
11416  }
11417
11418  unsigned isDev = cast<ConstantSDNode>(Op.getOperand(5))->getZExtValue();
11419  if (!isDev)
11420    return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
11421
11422  unsigned Op1 = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
11423  unsigned Op2 = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
11424  unsigned Op3 = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue();
11425  unsigned Op4 = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
11426
11427  // def : Pat<(membarrier (i8 0), (i8 0), (i8 0), (i8 1), (i8 1)), (SFENCE)>;
11428  if (!Op1 && !Op2 && !Op3 && Op4)
11429    return DAG.getNode(X86ISD::SFENCE, dl, MVT::Other, Op.getOperand(0));
11430
11431  // def : Pat<(membarrier (i8 1), (i8 0), (i8 0), (i8 0), (i8 1)), (LFENCE)>;
11432  if (Op1 && !Op2 && !Op3 && !Op4)
11433    return DAG.getNode(X86ISD::LFENCE, dl, MVT::Other, Op.getOperand(0));
11434
11435  // def : Pat<(membarrier (i8 imm), (i8 imm), (i8 imm), (i8 imm), (i8 1)),
11436  //           (MFENCE)>;
11437  return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
11438}
11439
11440static SDValue LowerATOMIC_FENCE(SDValue Op, const X86Subtarget *Subtarget,
11441                                 SelectionDAG &DAG) {
11442  DebugLoc dl = Op.getDebugLoc();
11443  AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
11444    cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
11445  SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
11446    cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
11447
11448  // The only fence that needs an instruction is a sequentially-consistent
11449  // cross-thread fence.
11450  if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
11451    // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
11452    // no-sse2). There isn't any reason to disable it if the target processor
11453    // supports it.
11454    if (Subtarget->hasSSE2() || Subtarget->is64Bit())
11455      return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
11456
11457    SDValue Chain = Op.getOperand(0);
11458    SDValue Zero = DAG.getConstant(0, MVT::i32);
11459    SDValue Ops[] = {
11460      DAG.getRegister(X86::ESP, MVT::i32), // Base
11461      DAG.getTargetConstant(1, MVT::i8),   // Scale
11462      DAG.getRegister(0, MVT::i32),        // Index
11463      DAG.getTargetConstant(0, MVT::i32),  // Disp
11464      DAG.getRegister(0, MVT::i32),        // Segment.
11465      Zero,
11466      Chain
11467    };
11468    SDNode *Res =
11469      DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops,
11470                         array_lengthof(Ops));
11471    return SDValue(Res, 0);
11472  }
11473
11474  // MEMBARRIER is a compiler barrier; it codegens to a no-op.
11475  return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
11476}
11477
11478
11479static SDValue LowerCMP_SWAP(SDValue Op, const X86Subtarget *Subtarget,
11480                             SelectionDAG &DAG) {
11481  EVT T = Op.getValueType();
11482  DebugLoc DL = Op.getDebugLoc();
11483  unsigned Reg = 0;
11484  unsigned size = 0;
11485  switch(T.getSimpleVT().SimpleTy) {
11486  default: llvm_unreachable("Invalid value type!");
11487  case MVT::i8:  Reg = X86::AL;  size = 1; break;
11488  case MVT::i16: Reg = X86::AX;  size = 2; break;
11489  case MVT::i32: Reg = X86::EAX; size = 4; break;
11490  case MVT::i64:
11491    assert(Subtarget->is64Bit() && "Node not type legal!");
11492    Reg = X86::RAX; size = 8;
11493    break;
11494  }
11495  SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
11496                                    Op.getOperand(2), SDValue());
11497  SDValue Ops[] = { cpIn.getValue(0),
11498                    Op.getOperand(1),
11499                    Op.getOperand(3),
11500                    DAG.getTargetConstant(size, MVT::i8),
11501                    cpIn.getValue(1) };
11502  SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
11503  MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
11504  SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
11505                                           Ops, 5, T, MMO);
11506  SDValue cpOut =
11507    DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
11508  return cpOut;
11509}
11510
11511static SDValue LowerREADCYCLECOUNTER(SDValue Op, const X86Subtarget *Subtarget,
11512                                     SelectionDAG &DAG) {
11513  assert(Subtarget->is64Bit() && "Result not type legalized?");
11514  SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
11515  SDValue TheChain = Op.getOperand(0);
11516  DebugLoc dl = Op.getDebugLoc();
11517  SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
11518  SDValue rax = DAG.getCopyFromReg(rd, dl, X86::RAX, MVT::i64, rd.getValue(1));
11519  SDValue rdx = DAG.getCopyFromReg(rax.getValue(1), dl, X86::RDX, MVT::i64,
11520                                   rax.getValue(2));
11521  SDValue Tmp = DAG.getNode(ISD::SHL, dl, MVT::i64, rdx,
11522                            DAG.getConstant(32, MVT::i8));
11523  SDValue Ops[] = {
11524    DAG.getNode(ISD::OR, dl, MVT::i64, rax, Tmp),
11525    rdx.getValue(1)
11526  };
11527  return DAG.getMergeValues(Ops, 2, dl);
11528}
11529
11530SDValue X86TargetLowering::LowerBITCAST(SDValue Op, SelectionDAG &DAG) const {
11531  EVT SrcVT = Op.getOperand(0).getValueType();
11532  EVT DstVT = Op.getValueType();
11533  assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
11534         Subtarget->hasMMX() && "Unexpected custom BITCAST");
11535  assert((DstVT == MVT::i64 ||
11536          (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
11537         "Unexpected custom BITCAST");
11538  // i64 <=> MMX conversions are Legal.
11539  if (SrcVT==MVT::i64 && DstVT.isVector())
11540    return Op;
11541  if (DstVT==MVT::i64 && SrcVT.isVector())
11542    return Op;
11543  // MMX <=> MMX conversions are Legal.
11544  if (SrcVT.isVector() && DstVT.isVector())
11545    return Op;
11546  // All other conversions need to be expanded.
11547  return SDValue();
11548}
11549
11550static SDValue LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) {
11551  SDNode *Node = Op.getNode();
11552  DebugLoc dl = Node->getDebugLoc();
11553  EVT T = Node->getValueType(0);
11554  SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
11555                              DAG.getConstant(0, T), Node->getOperand(2));
11556  return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
11557                       cast<AtomicSDNode>(Node)->getMemoryVT(),
11558                       Node->getOperand(0),
11559                       Node->getOperand(1), negOp,
11560                       cast<AtomicSDNode>(Node)->getSrcValue(),
11561                       cast<AtomicSDNode>(Node)->getAlignment(),
11562                       cast<AtomicSDNode>(Node)->getOrdering(),
11563                       cast<AtomicSDNode>(Node)->getSynchScope());
11564}
11565
11566static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
11567  SDNode *Node = Op.getNode();
11568  DebugLoc dl = Node->getDebugLoc();
11569  EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
11570
11571  // Convert seq_cst store -> xchg
11572  // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
11573  // FIXME: On 32-bit, store -> fist or movq would be more efficient
11574  //        (The only way to get a 16-byte store is cmpxchg16b)
11575  // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
11576  if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
11577      !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
11578    SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
11579                                 cast<AtomicSDNode>(Node)->getMemoryVT(),
11580                                 Node->getOperand(0),
11581                                 Node->getOperand(1), Node->getOperand(2),
11582                                 cast<AtomicSDNode>(Node)->getMemOperand(),
11583                                 cast<AtomicSDNode>(Node)->getOrdering(),
11584                                 cast<AtomicSDNode>(Node)->getSynchScope());
11585    return Swap.getValue(1);
11586  }
11587  // Other atomic stores have a simple pattern.
11588  return Op;
11589}
11590
11591static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
11592  EVT VT = Op.getNode()->getValueType(0);
11593
11594  // Let legalize expand this if it isn't a legal type yet.
11595  if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
11596    return SDValue();
11597
11598  SDVTList VTs = DAG.getVTList(VT, MVT::i32);
11599
11600  unsigned Opc;
11601  bool ExtraOp = false;
11602  switch (Op.getOpcode()) {
11603  default: llvm_unreachable("Invalid code");
11604  case ISD::ADDC: Opc = X86ISD::ADD; break;
11605  case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
11606  case ISD::SUBC: Opc = X86ISD::SUB; break;
11607  case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
11608  }
11609
11610  if (!ExtraOp)
11611    return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
11612                       Op.getOperand(1));
11613  return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
11614                     Op.getOperand(1), Op.getOperand(2));
11615}
11616
11617/// LowerOperation - Provide custom lowering hooks for some operations.
11618///
11619SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
11620  switch (Op.getOpcode()) {
11621  default: llvm_unreachable("Should not custom lower this!");
11622  case ISD::SIGN_EXTEND_INREG:  return LowerSIGN_EXTEND_INREG(Op,DAG);
11623  case ISD::MEMBARRIER:         return LowerMEMBARRIER(Op, Subtarget, DAG);
11624  case ISD::ATOMIC_FENCE:       return LowerATOMIC_FENCE(Op, Subtarget, DAG);
11625  case ISD::ATOMIC_CMP_SWAP:    return LowerCMP_SWAP(Op, Subtarget, DAG);
11626  case ISD::ATOMIC_LOAD_SUB:    return LowerLOAD_SUB(Op,DAG);
11627  case ISD::ATOMIC_STORE:       return LowerATOMIC_STORE(Op,DAG);
11628  case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
11629  case ISD::CONCAT_VECTORS:     return LowerCONCAT_VECTORS(Op, DAG);
11630  case ISD::VECTOR_SHUFFLE:     return LowerVECTOR_SHUFFLE(Op, DAG);
11631  case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
11632  case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
11633  case ISD::EXTRACT_SUBVECTOR:  return LowerEXTRACT_SUBVECTOR(Op,Subtarget,DAG);
11634  case ISD::INSERT_SUBVECTOR:   return LowerINSERT_SUBVECTOR(Op, Subtarget,DAG);
11635  case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
11636  case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
11637  case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
11638  case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
11639  case ISD::ExternalSymbol:     return LowerExternalSymbol(Op, DAG);
11640  case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
11641  case ISD::SHL_PARTS:
11642  case ISD::SRA_PARTS:
11643  case ISD::SRL_PARTS:          return LowerShiftParts(Op, DAG);
11644  case ISD::SINT_TO_FP:         return LowerSINT_TO_FP(Op, DAG);
11645  case ISD::UINT_TO_FP:         return LowerUINT_TO_FP(Op, DAG);
11646  case ISD::TRUNCATE:           return lowerTRUNCATE(Op, DAG);
11647  case ISD::ZERO_EXTEND:        return lowerZERO_EXTEND(Op, DAG);
11648  case ISD::FP_TO_SINT:         return LowerFP_TO_SINT(Op, DAG);
11649  case ISD::FP_TO_UINT:         return LowerFP_TO_UINT(Op, DAG);
11650  case ISD::FP_EXTEND:          return lowerFP_EXTEND(Op, DAG);
11651  case ISD::FABS:               return LowerFABS(Op, DAG);
11652  case ISD::FNEG:               return LowerFNEG(Op, DAG);
11653  case ISD::FCOPYSIGN:          return LowerFCOPYSIGN(Op, DAG);
11654  case ISD::FGETSIGN:           return LowerFGETSIGN(Op, DAG);
11655  case ISD::SETCC:              return LowerSETCC(Op, DAG);
11656  case ISD::SELECT:             return LowerSELECT(Op, DAG);
11657  case ISD::BRCOND:             return LowerBRCOND(Op, DAG);
11658  case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
11659  case ISD::VASTART:            return LowerVASTART(Op, DAG);
11660  case ISD::VAARG:              return LowerVAARG(Op, DAG);
11661  case ISD::VACOPY:             return LowerVACOPY(Op, Subtarget, DAG);
11662  case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
11663  case ISD::INTRINSIC_W_CHAIN:  return LowerINTRINSIC_W_CHAIN(Op, DAG);
11664  case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
11665  case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
11666  case ISD::FRAME_TO_ARGS_OFFSET:
11667                                return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
11668  case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
11669  case ISD::EH_RETURN:          return LowerEH_RETURN(Op, DAG);
11670  case ISD::EH_SJLJ_SETJMP:     return lowerEH_SJLJ_SETJMP(Op, DAG);
11671  case ISD::EH_SJLJ_LONGJMP:    return lowerEH_SJLJ_LONGJMP(Op, DAG);
11672  case ISD::INIT_TRAMPOLINE:    return LowerINIT_TRAMPOLINE(Op, DAG);
11673  case ISD::ADJUST_TRAMPOLINE:  return LowerADJUST_TRAMPOLINE(Op, DAG);
11674  case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
11675  case ISD::CTLZ:               return LowerCTLZ(Op, DAG);
11676  case ISD::CTLZ_ZERO_UNDEF:    return LowerCTLZ_ZERO_UNDEF(Op, DAG);
11677  case ISD::CTTZ:               return LowerCTTZ(Op, DAG);
11678  case ISD::MUL:                return LowerMUL(Op, Subtarget, DAG);
11679  case ISD::SRA:
11680  case ISD::SRL:
11681  case ISD::SHL:                return LowerShift(Op, DAG);
11682  case ISD::SADDO:
11683  case ISD::UADDO:
11684  case ISD::SSUBO:
11685  case ISD::USUBO:
11686  case ISD::SMULO:
11687  case ISD::UMULO:              return LowerXALUO(Op, DAG);
11688  case ISD::READCYCLECOUNTER:   return LowerREADCYCLECOUNTER(Op, Subtarget,DAG);
11689  case ISD::BITCAST:            return LowerBITCAST(Op, DAG);
11690  case ISD::ADDC:
11691  case ISD::ADDE:
11692  case ISD::SUBC:
11693  case ISD::SUBE:               return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
11694  case ISD::ADD:                return LowerADD(Op, DAG);
11695  case ISD::SUB:                return LowerSUB(Op, DAG);
11696  }
11697}
11698
11699static void ReplaceATOMIC_LOAD(SDNode *Node,
11700                                  SmallVectorImpl<SDValue> &Results,
11701                                  SelectionDAG &DAG) {
11702  DebugLoc dl = Node->getDebugLoc();
11703  EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
11704
11705  // Convert wide load -> cmpxchg8b/cmpxchg16b
11706  // FIXME: On 32-bit, load -> fild or movq would be more efficient
11707  //        (The only way to get a 16-byte load is cmpxchg16b)
11708  // FIXME: 16-byte ATOMIC_CMP_SWAP isn't actually hooked up at the moment.
11709  SDValue Zero = DAG.getConstant(0, VT);
11710  SDValue Swap = DAG.getAtomic(ISD::ATOMIC_CMP_SWAP, dl, VT,
11711                               Node->getOperand(0),
11712                               Node->getOperand(1), Zero, Zero,
11713                               cast<AtomicSDNode>(Node)->getMemOperand(),
11714                               cast<AtomicSDNode>(Node)->getOrdering(),
11715                               cast<AtomicSDNode>(Node)->getSynchScope());
11716  Results.push_back(Swap.getValue(0));
11717  Results.push_back(Swap.getValue(1));
11718}
11719
11720static void
11721ReplaceATOMIC_BINARY_64(SDNode *Node, SmallVectorImpl<SDValue>&Results,
11722                        SelectionDAG &DAG, unsigned NewOp) {
11723  DebugLoc dl = Node->getDebugLoc();
11724  assert (Node->getValueType(0) == MVT::i64 &&
11725          "Only know how to expand i64 atomics");
11726
11727  SDValue Chain = Node->getOperand(0);
11728  SDValue In1 = Node->getOperand(1);
11729  SDValue In2L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
11730                             Node->getOperand(2), DAG.getIntPtrConstant(0));
11731  SDValue In2H = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
11732                             Node->getOperand(2), DAG.getIntPtrConstant(1));
11733  SDValue Ops[] = { Chain, In1, In2L, In2H };
11734  SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
11735  SDValue Result =
11736    DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops, 4, MVT::i64,
11737                            cast<MemSDNode>(Node)->getMemOperand());
11738  SDValue OpsF[] = { Result.getValue(0), Result.getValue(1)};
11739  Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
11740  Results.push_back(Result.getValue(2));
11741}
11742
11743/// ReplaceNodeResults - Replace a node with an illegal result type
11744/// with a new node built out of custom code.
11745void X86TargetLowering::ReplaceNodeResults(SDNode *N,
11746                                           SmallVectorImpl<SDValue>&Results,
11747                                           SelectionDAG &DAG) const {
11748  DebugLoc dl = N->getDebugLoc();
11749  switch (N->getOpcode()) {
11750  default:
11751    llvm_unreachable("Do not know how to custom type legalize this operation!");
11752  case ISD::SIGN_EXTEND_INREG:
11753  case ISD::ADDC:
11754  case ISD::ADDE:
11755  case ISD::SUBC:
11756  case ISD::SUBE:
11757    // We don't want to expand or promote these.
11758    return;
11759  case ISD::FP_TO_SINT:
11760  case ISD::FP_TO_UINT: {
11761    bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
11762
11763    if (!IsSigned && !isIntegerTypeFTOL(SDValue(N, 0).getValueType()))
11764      return;
11765
11766    std::pair<SDValue,SDValue> Vals =
11767        FP_TO_INTHelper(SDValue(N, 0), DAG, IsSigned, /*IsReplace=*/ true);
11768    SDValue FIST = Vals.first, StackSlot = Vals.second;
11769    if (FIST.getNode() != 0) {
11770      EVT VT = N->getValueType(0);
11771      // Return a load from the stack slot.
11772      if (StackSlot.getNode() != 0)
11773        Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
11774                                      MachinePointerInfo(),
11775                                      false, false, false, 0));
11776      else
11777        Results.push_back(FIST);
11778    }
11779    return;
11780  }
11781  case ISD::UINT_TO_FP: {
11782    if (N->getOperand(0).getValueType() != MVT::v2i32 &&
11783        N->getValueType(0) != MVT::v2f32)
11784      return;
11785    SDValue ZExtIn = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v2i64,
11786                                 N->getOperand(0));
11787    SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
11788                                     MVT::f64);
11789    SDValue VBias = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2f64, Bias, Bias);
11790    SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64, ZExtIn,
11791                             DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, VBias));
11792    Or = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or);
11793    SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, Or, VBias);
11794    Results.push_back(DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, Sub));
11795    return;
11796  }
11797  case ISD::FP_ROUND: {
11798    SDValue V = DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, N->getOperand(0));
11799    Results.push_back(V);
11800    return;
11801  }
11802  case ISD::READCYCLECOUNTER: {
11803    SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
11804    SDValue TheChain = N->getOperand(0);
11805    SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
11806    SDValue eax = DAG.getCopyFromReg(rd, dl, X86::EAX, MVT::i32,
11807                                     rd.getValue(1));
11808    SDValue edx = DAG.getCopyFromReg(eax.getValue(1), dl, X86::EDX, MVT::i32,
11809                                     eax.getValue(2));
11810    // Use a buildpair to merge the two 32-bit values into a 64-bit one.
11811    SDValue Ops[] = { eax, edx };
11812    Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Ops, 2));
11813    Results.push_back(edx.getValue(1));
11814    return;
11815  }
11816  case ISD::ATOMIC_CMP_SWAP: {
11817    EVT T = N->getValueType(0);
11818    assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
11819    bool Regs64bit = T == MVT::i128;
11820    EVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
11821    SDValue cpInL, cpInH;
11822    cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
11823                        DAG.getConstant(0, HalfT));
11824    cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
11825                        DAG.getConstant(1, HalfT));
11826    cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
11827                             Regs64bit ? X86::RAX : X86::EAX,
11828                             cpInL, SDValue());
11829    cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
11830                             Regs64bit ? X86::RDX : X86::EDX,
11831                             cpInH, cpInL.getValue(1));
11832    SDValue swapInL, swapInH;
11833    swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
11834                          DAG.getConstant(0, HalfT));
11835    swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
11836                          DAG.getConstant(1, HalfT));
11837    swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
11838                               Regs64bit ? X86::RBX : X86::EBX,
11839                               swapInL, cpInH.getValue(1));
11840    swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
11841                               Regs64bit ? X86::RCX : X86::ECX,
11842                               swapInH, swapInL.getValue(1));
11843    SDValue Ops[] = { swapInH.getValue(0),
11844                      N->getOperand(1),
11845                      swapInH.getValue(1) };
11846    SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
11847    MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
11848    unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
11849                                  X86ISD::LCMPXCHG8_DAG;
11850    SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys,
11851                                             Ops, 3, T, MMO);
11852    SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
11853                                        Regs64bit ? X86::RAX : X86::EAX,
11854                                        HalfT, Result.getValue(1));
11855    SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
11856                                        Regs64bit ? X86::RDX : X86::EDX,
11857                                        HalfT, cpOutL.getValue(2));
11858    SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
11859    Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF, 2));
11860    Results.push_back(cpOutH.getValue(1));
11861    return;
11862  }
11863  case ISD::ATOMIC_LOAD_ADD:
11864  case ISD::ATOMIC_LOAD_AND:
11865  case ISD::ATOMIC_LOAD_NAND:
11866  case ISD::ATOMIC_LOAD_OR:
11867  case ISD::ATOMIC_LOAD_SUB:
11868  case ISD::ATOMIC_LOAD_XOR:
11869  case ISD::ATOMIC_LOAD_MAX:
11870  case ISD::ATOMIC_LOAD_MIN:
11871  case ISD::ATOMIC_LOAD_UMAX:
11872  case ISD::ATOMIC_LOAD_UMIN:
11873  case ISD::ATOMIC_SWAP: {
11874    unsigned Opc;
11875    switch (N->getOpcode()) {
11876    default: llvm_unreachable("Unexpected opcode");
11877    case ISD::ATOMIC_LOAD_ADD:
11878      Opc = X86ISD::ATOMADD64_DAG;
11879      break;
11880    case ISD::ATOMIC_LOAD_AND:
11881      Opc = X86ISD::ATOMAND64_DAG;
11882      break;
11883    case ISD::ATOMIC_LOAD_NAND:
11884      Opc = X86ISD::ATOMNAND64_DAG;
11885      break;
11886    case ISD::ATOMIC_LOAD_OR:
11887      Opc = X86ISD::ATOMOR64_DAG;
11888      break;
11889    case ISD::ATOMIC_LOAD_SUB:
11890      Opc = X86ISD::ATOMSUB64_DAG;
11891      break;
11892    case ISD::ATOMIC_LOAD_XOR:
11893      Opc = X86ISD::ATOMXOR64_DAG;
11894      break;
11895    case ISD::ATOMIC_LOAD_MAX:
11896      Opc = X86ISD::ATOMMAX64_DAG;
11897      break;
11898    case ISD::ATOMIC_LOAD_MIN:
11899      Opc = X86ISD::ATOMMIN64_DAG;
11900      break;
11901    case ISD::ATOMIC_LOAD_UMAX:
11902      Opc = X86ISD::ATOMUMAX64_DAG;
11903      break;
11904    case ISD::ATOMIC_LOAD_UMIN:
11905      Opc = X86ISD::ATOMUMIN64_DAG;
11906      break;
11907    case ISD::ATOMIC_SWAP:
11908      Opc = X86ISD::ATOMSWAP64_DAG;
11909      break;
11910    }
11911    ReplaceATOMIC_BINARY_64(N, Results, DAG, Opc);
11912    return;
11913  }
11914  case ISD::ATOMIC_LOAD:
11915    ReplaceATOMIC_LOAD(N, Results, DAG);
11916  }
11917}
11918
11919const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
11920  switch (Opcode) {
11921  default: return NULL;
11922  case X86ISD::BSF:                return "X86ISD::BSF";
11923  case X86ISD::BSR:                return "X86ISD::BSR";
11924  case X86ISD::SHLD:               return "X86ISD::SHLD";
11925  case X86ISD::SHRD:               return "X86ISD::SHRD";
11926  case X86ISD::FAND:               return "X86ISD::FAND";
11927  case X86ISD::FOR:                return "X86ISD::FOR";
11928  case X86ISD::FXOR:               return "X86ISD::FXOR";
11929  case X86ISD::FSRL:               return "X86ISD::FSRL";
11930  case X86ISD::FILD:               return "X86ISD::FILD";
11931  case X86ISD::FILD_FLAG:          return "X86ISD::FILD_FLAG";
11932  case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
11933  case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
11934  case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
11935  case X86ISD::FLD:                return "X86ISD::FLD";
11936  case X86ISD::FST:                return "X86ISD::FST";
11937  case X86ISD::CALL:               return "X86ISD::CALL";
11938  case X86ISD::RDTSC_DAG:          return "X86ISD::RDTSC_DAG";
11939  case X86ISD::BT:                 return "X86ISD::BT";
11940  case X86ISD::CMP:                return "X86ISD::CMP";
11941  case X86ISD::COMI:               return "X86ISD::COMI";
11942  case X86ISD::UCOMI:              return "X86ISD::UCOMI";
11943  case X86ISD::SETCC:              return "X86ISD::SETCC";
11944  case X86ISD::SETCC_CARRY:        return "X86ISD::SETCC_CARRY";
11945  case X86ISD::FSETCCsd:           return "X86ISD::FSETCCsd";
11946  case X86ISD::FSETCCss:           return "X86ISD::FSETCCss";
11947  case X86ISD::CMOV:               return "X86ISD::CMOV";
11948  case X86ISD::BRCOND:             return "X86ISD::BRCOND";
11949  case X86ISD::RET_FLAG:           return "X86ISD::RET_FLAG";
11950  case X86ISD::REP_STOS:           return "X86ISD::REP_STOS";
11951  case X86ISD::REP_MOVS:           return "X86ISD::REP_MOVS";
11952  case X86ISD::GlobalBaseReg:      return "X86ISD::GlobalBaseReg";
11953  case X86ISD::Wrapper:            return "X86ISD::Wrapper";
11954  case X86ISD::WrapperRIP:         return "X86ISD::WrapperRIP";
11955  case X86ISD::PEXTRB:             return "X86ISD::PEXTRB";
11956  case X86ISD::PEXTRW:             return "X86ISD::PEXTRW";
11957  case X86ISD::INSERTPS:           return "X86ISD::INSERTPS";
11958  case X86ISD::PINSRB:             return "X86ISD::PINSRB";
11959  case X86ISD::PINSRW:             return "X86ISD::PINSRW";
11960  case X86ISD::PSHUFB:             return "X86ISD::PSHUFB";
11961  case X86ISD::ANDNP:              return "X86ISD::ANDNP";
11962  case X86ISD::PSIGN:              return "X86ISD::PSIGN";
11963  case X86ISD::BLENDV:             return "X86ISD::BLENDV";
11964  case X86ISD::BLENDPW:            return "X86ISD::BLENDPW";
11965  case X86ISD::BLENDPS:            return "X86ISD::BLENDPS";
11966  case X86ISD::BLENDPD:            return "X86ISD::BLENDPD";
11967  case X86ISD::HADD:               return "X86ISD::HADD";
11968  case X86ISD::HSUB:               return "X86ISD::HSUB";
11969  case X86ISD::FHADD:              return "X86ISD::FHADD";
11970  case X86ISD::FHSUB:              return "X86ISD::FHSUB";
11971  case X86ISD::FMAX:               return "X86ISD::FMAX";
11972  case X86ISD::FMIN:               return "X86ISD::FMIN";
11973  case X86ISD::FMAXC:              return "X86ISD::FMAXC";
11974  case X86ISD::FMINC:              return "X86ISD::FMINC";
11975  case X86ISD::FRSQRT:             return "X86ISD::FRSQRT";
11976  case X86ISD::FRCP:               return "X86ISD::FRCP";
11977  case X86ISD::TLSADDR:            return "X86ISD::TLSADDR";
11978  case X86ISD::TLSBASEADDR:        return "X86ISD::TLSBASEADDR";
11979  case X86ISD::TLSCALL:            return "X86ISD::TLSCALL";
11980  case X86ISD::EH_SJLJ_SETJMP:     return "X86ISD::EH_SJLJ_SETJMP";
11981  case X86ISD::EH_SJLJ_LONGJMP:    return "X86ISD::EH_SJLJ_LONGJMP";
11982  case X86ISD::EH_RETURN:          return "X86ISD::EH_RETURN";
11983  case X86ISD::TC_RETURN:          return "X86ISD::TC_RETURN";
11984  case X86ISD::FNSTCW16m:          return "X86ISD::FNSTCW16m";
11985  case X86ISD::FNSTSW16r:          return "X86ISD::FNSTSW16r";
11986  case X86ISD::LCMPXCHG_DAG:       return "X86ISD::LCMPXCHG_DAG";
11987  case X86ISD::LCMPXCHG8_DAG:      return "X86ISD::LCMPXCHG8_DAG";
11988  case X86ISD::ATOMADD64_DAG:      return "X86ISD::ATOMADD64_DAG";
11989  case X86ISD::ATOMSUB64_DAG:      return "X86ISD::ATOMSUB64_DAG";
11990  case X86ISD::ATOMOR64_DAG:       return "X86ISD::ATOMOR64_DAG";
11991  case X86ISD::ATOMXOR64_DAG:      return "X86ISD::ATOMXOR64_DAG";
11992  case X86ISD::ATOMAND64_DAG:      return "X86ISD::ATOMAND64_DAG";
11993  case X86ISD::ATOMNAND64_DAG:     return "X86ISD::ATOMNAND64_DAG";
11994  case X86ISD::VZEXT_MOVL:         return "X86ISD::VZEXT_MOVL";
11995  case X86ISD::VSEXT_MOVL:         return "X86ISD::VSEXT_MOVL";
11996  case X86ISD::VZEXT_LOAD:         return "X86ISD::VZEXT_LOAD";
11997  case X86ISD::VZEXT:              return "X86ISD::VZEXT";
11998  case X86ISD::VSEXT:              return "X86ISD::VSEXT";
11999  case X86ISD::VFPEXT:             return "X86ISD::VFPEXT";
12000  case X86ISD::VFPROUND:           return "X86ISD::VFPROUND";
12001  case X86ISD::VSHLDQ:             return "X86ISD::VSHLDQ";
12002  case X86ISD::VSRLDQ:             return "X86ISD::VSRLDQ";
12003  case X86ISD::VSHL:               return "X86ISD::VSHL";
12004  case X86ISD::VSRL:               return "X86ISD::VSRL";
12005  case X86ISD::VSRA:               return "X86ISD::VSRA";
12006  case X86ISD::VSHLI:              return "X86ISD::VSHLI";
12007  case X86ISD::VSRLI:              return "X86ISD::VSRLI";
12008  case X86ISD::VSRAI:              return "X86ISD::VSRAI";
12009  case X86ISD::CMPP:               return "X86ISD::CMPP";
12010  case X86ISD::PCMPEQ:             return "X86ISD::PCMPEQ";
12011  case X86ISD::PCMPGT:             return "X86ISD::PCMPGT";
12012  case X86ISD::ADD:                return "X86ISD::ADD";
12013  case X86ISD::SUB:                return "X86ISD::SUB";
12014  case X86ISD::ADC:                return "X86ISD::ADC";
12015  case X86ISD::SBB:                return "X86ISD::SBB";
12016  case X86ISD::SMUL:               return "X86ISD::SMUL";
12017  case X86ISD::UMUL:               return "X86ISD::UMUL";
12018  case X86ISD::INC:                return "X86ISD::INC";
12019  case X86ISD::DEC:                return "X86ISD::DEC";
12020  case X86ISD::OR:                 return "X86ISD::OR";
12021  case X86ISD::XOR:                return "X86ISD::XOR";
12022  case X86ISD::AND:                return "X86ISD::AND";
12023  case X86ISD::ANDN:               return "X86ISD::ANDN";
12024  case X86ISD::BLSI:               return "X86ISD::BLSI";
12025  case X86ISD::BLSMSK:             return "X86ISD::BLSMSK";
12026  case X86ISD::BLSR:               return "X86ISD::BLSR";
12027  case X86ISD::MUL_IMM:            return "X86ISD::MUL_IMM";
12028  case X86ISD::PTEST:              return "X86ISD::PTEST";
12029  case X86ISD::TESTP:              return "X86ISD::TESTP";
12030  case X86ISD::PALIGN:             return "X86ISD::PALIGN";
12031  case X86ISD::PSHUFD:             return "X86ISD::PSHUFD";
12032  case X86ISD::PSHUFHW:            return "X86ISD::PSHUFHW";
12033  case X86ISD::PSHUFLW:            return "X86ISD::PSHUFLW";
12034  case X86ISD::SHUFP:              return "X86ISD::SHUFP";
12035  case X86ISD::MOVLHPS:            return "X86ISD::MOVLHPS";
12036  case X86ISD::MOVLHPD:            return "X86ISD::MOVLHPD";
12037  case X86ISD::MOVHLPS:            return "X86ISD::MOVHLPS";
12038  case X86ISD::MOVLPS:             return "X86ISD::MOVLPS";
12039  case X86ISD::MOVLPD:             return "X86ISD::MOVLPD";
12040  case X86ISD::MOVDDUP:            return "X86ISD::MOVDDUP";
12041  case X86ISD::MOVSHDUP:           return "X86ISD::MOVSHDUP";
12042  case X86ISD::MOVSLDUP:           return "X86ISD::MOVSLDUP";
12043  case X86ISD::MOVSD:              return "X86ISD::MOVSD";
12044  case X86ISD::MOVSS:              return "X86ISD::MOVSS";
12045  case X86ISD::UNPCKL:             return "X86ISD::UNPCKL";
12046  case X86ISD::UNPCKH:             return "X86ISD::UNPCKH";
12047  case X86ISD::VBROADCAST:         return "X86ISD::VBROADCAST";
12048  case X86ISD::VPERMILP:           return "X86ISD::VPERMILP";
12049  case X86ISD::VPERM2X128:         return "X86ISD::VPERM2X128";
12050  case X86ISD::VPERMV:             return "X86ISD::VPERMV";
12051  case X86ISD::VPERMI:             return "X86ISD::VPERMI";
12052  case X86ISD::PMULUDQ:            return "X86ISD::PMULUDQ";
12053  case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
12054  case X86ISD::VAARG_64:           return "X86ISD::VAARG_64";
12055  case X86ISD::WIN_ALLOCA:         return "X86ISD::WIN_ALLOCA";
12056  case X86ISD::MEMBARRIER:         return "X86ISD::MEMBARRIER";
12057  case X86ISD::SEG_ALLOCA:         return "X86ISD::SEG_ALLOCA";
12058  case X86ISD::WIN_FTOL:           return "X86ISD::WIN_FTOL";
12059  case X86ISD::SAHF:               return "X86ISD::SAHF";
12060  case X86ISD::RDRAND:             return "X86ISD::RDRAND";
12061  case X86ISD::FMADD:              return "X86ISD::FMADD";
12062  case X86ISD::FMSUB:              return "X86ISD::FMSUB";
12063  case X86ISD::FNMADD:             return "X86ISD::FNMADD";
12064  case X86ISD::FNMSUB:             return "X86ISD::FNMSUB";
12065  case X86ISD::FMADDSUB:           return "X86ISD::FMADDSUB";
12066  case X86ISD::FMSUBADD:           return "X86ISD::FMSUBADD";
12067  case X86ISD::PCMPESTRI:          return "X86ISD::PCMPESTRI";
12068  case X86ISD::PCMPISTRI:          return "X86ISD::PCMPISTRI";
12069  }
12070}
12071
12072// isLegalAddressingMode - Return true if the addressing mode represented
12073// by AM is legal for this target, for a load/store of the specified type.
12074bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
12075                                              Type *Ty) const {
12076  // X86 supports extremely general addressing modes.
12077  CodeModel::Model M = getTargetMachine().getCodeModel();
12078  Reloc::Model R = getTargetMachine().getRelocationModel();
12079
12080  // X86 allows a sign-extended 32-bit immediate field as a displacement.
12081  if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != NULL))
12082    return false;
12083
12084  if (AM.BaseGV) {
12085    unsigned GVFlags =
12086      Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
12087
12088    // If a reference to this global requires an extra load, we can't fold it.
12089    if (isGlobalStubReference(GVFlags))
12090      return false;
12091
12092    // If BaseGV requires a register for the PIC base, we cannot also have a
12093    // BaseReg specified.
12094    if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
12095      return false;
12096
12097    // If lower 4G is not available, then we must use rip-relative addressing.
12098    if ((M != CodeModel::Small || R != Reloc::Static) &&
12099        Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
12100      return false;
12101  }
12102
12103  switch (AM.Scale) {
12104  case 0:
12105  case 1:
12106  case 2:
12107  case 4:
12108  case 8:
12109    // These scales always work.
12110    break;
12111  case 3:
12112  case 5:
12113  case 9:
12114    // These scales are formed with basereg+scalereg.  Only accept if there is
12115    // no basereg yet.
12116    if (AM.HasBaseReg)
12117      return false;
12118    break;
12119  default:  // Other stuff never works.
12120    return false;
12121  }
12122
12123  return true;
12124}
12125
12126
12127bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
12128  if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
12129    return false;
12130  unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
12131  unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
12132  if (NumBits1 <= NumBits2)
12133    return false;
12134  return true;
12135}
12136
12137bool X86TargetLowering::isLegalICmpImmediate(int64_t Imm) const {
12138  return Imm == (int32_t)Imm;
12139}
12140
12141bool X86TargetLowering::isLegalAddImmediate(int64_t Imm) const {
12142  // Can also use sub to handle negated immediates.
12143  return Imm == (int32_t)Imm;
12144}
12145
12146bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
12147  if (!VT1.isInteger() || !VT2.isInteger())
12148    return false;
12149  unsigned NumBits1 = VT1.getSizeInBits();
12150  unsigned NumBits2 = VT2.getSizeInBits();
12151  if (NumBits1 <= NumBits2)
12152    return false;
12153  return true;
12154}
12155
12156bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
12157  // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
12158  return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
12159}
12160
12161bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
12162  // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
12163  return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
12164}
12165
12166bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
12167  // i16 instructions are longer (0x66 prefix) and potentially slower.
12168  return !(VT1 == MVT::i32 && VT2 == MVT::i16);
12169}
12170
12171/// isShuffleMaskLegal - Targets can use this to indicate that they only
12172/// support *some* VECTOR_SHUFFLE operations, those with specific masks.
12173/// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
12174/// are assumed to be legal.
12175bool
12176X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
12177                                      EVT VT) const {
12178  // Very little shuffling can be done for 64-bit vectors right now.
12179  if (VT.getSizeInBits() == 64)
12180    return false;
12181
12182  // FIXME: pshufb, blends, shifts.
12183  return (VT.getVectorNumElements() == 2 ||
12184          ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
12185          isMOVLMask(M, VT) ||
12186          isSHUFPMask(M, VT, Subtarget->hasAVX()) ||
12187          isPSHUFDMask(M, VT) ||
12188          isPSHUFHWMask(M, VT, Subtarget->hasAVX2()) ||
12189          isPSHUFLWMask(M, VT, Subtarget->hasAVX2()) ||
12190          isPALIGNRMask(M, VT, Subtarget) ||
12191          isUNPCKLMask(M, VT, Subtarget->hasAVX2()) ||
12192          isUNPCKHMask(M, VT, Subtarget->hasAVX2()) ||
12193          isUNPCKL_v_undef_Mask(M, VT, Subtarget->hasAVX2()) ||
12194          isUNPCKH_v_undef_Mask(M, VT, Subtarget->hasAVX2()));
12195}
12196
12197bool
12198X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
12199                                          EVT VT) const {
12200  unsigned NumElts = VT.getVectorNumElements();
12201  // FIXME: This collection of masks seems suspect.
12202  if (NumElts == 2)
12203    return true;
12204  if (NumElts == 4 && VT.is128BitVector()) {
12205    return (isMOVLMask(Mask, VT)  ||
12206            isCommutedMOVLMask(Mask, VT, true) ||
12207            isSHUFPMask(Mask, VT, Subtarget->hasAVX()) ||
12208            isSHUFPMask(Mask, VT, Subtarget->hasAVX(), /* Commuted */ true));
12209  }
12210  return false;
12211}
12212
12213//===----------------------------------------------------------------------===//
12214//                           X86 Scheduler Hooks
12215//===----------------------------------------------------------------------===//
12216
12217/// Utility function to emit xbegin specifying the start of an RTM region.
12218static MachineBasicBlock *EmitXBegin(MachineInstr *MI, MachineBasicBlock *MBB,
12219                                     const TargetInstrInfo *TII) {
12220  DebugLoc DL = MI->getDebugLoc();
12221
12222  const BasicBlock *BB = MBB->getBasicBlock();
12223  MachineFunction::iterator I = MBB;
12224  ++I;
12225
12226  // For the v = xbegin(), we generate
12227  //
12228  // thisMBB:
12229  //  xbegin sinkMBB
12230  //
12231  // mainMBB:
12232  //  eax = -1
12233  //
12234  // sinkMBB:
12235  //  v = eax
12236
12237  MachineBasicBlock *thisMBB = MBB;
12238  MachineFunction *MF = MBB->getParent();
12239  MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
12240  MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
12241  MF->insert(I, mainMBB);
12242  MF->insert(I, sinkMBB);
12243
12244  // Transfer the remainder of BB and its successor edges to sinkMBB.
12245  sinkMBB->splice(sinkMBB->begin(), MBB,
12246                  llvm::next(MachineBasicBlock::iterator(MI)), MBB->end());
12247  sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
12248
12249  // thisMBB:
12250  //  xbegin sinkMBB
12251  //  # fallthrough to mainMBB
12252  //  # abortion to sinkMBB
12253  BuildMI(thisMBB, DL, TII->get(X86::XBEGIN_4)).addMBB(sinkMBB);
12254  thisMBB->addSuccessor(mainMBB);
12255  thisMBB->addSuccessor(sinkMBB);
12256
12257  // mainMBB:
12258  //  EAX = -1
12259  BuildMI(mainMBB, DL, TII->get(X86::MOV32ri), X86::EAX).addImm(-1);
12260  mainMBB->addSuccessor(sinkMBB);
12261
12262  // sinkMBB:
12263  // EAX is live into the sinkMBB
12264  sinkMBB->addLiveIn(X86::EAX);
12265  BuildMI(*sinkMBB, sinkMBB->begin(), DL,
12266          TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
12267    .addReg(X86::EAX);
12268
12269  MI->eraseFromParent();
12270  return sinkMBB;
12271}
12272
12273// Get CMPXCHG opcode for the specified data type.
12274static unsigned getCmpXChgOpcode(EVT VT) {
12275  switch (VT.getSimpleVT().SimpleTy) {
12276  case MVT::i8:  return X86::LCMPXCHG8;
12277  case MVT::i16: return X86::LCMPXCHG16;
12278  case MVT::i32: return X86::LCMPXCHG32;
12279  case MVT::i64: return X86::LCMPXCHG64;
12280  default:
12281    break;
12282  }
12283  llvm_unreachable("Invalid operand size!");
12284}
12285
12286// Get LOAD opcode for the specified data type.
12287static unsigned getLoadOpcode(EVT VT) {
12288  switch (VT.getSimpleVT().SimpleTy) {
12289  case MVT::i8:  return X86::MOV8rm;
12290  case MVT::i16: return X86::MOV16rm;
12291  case MVT::i32: return X86::MOV32rm;
12292  case MVT::i64: return X86::MOV64rm;
12293  default:
12294    break;
12295  }
12296  llvm_unreachable("Invalid operand size!");
12297}
12298
12299// Get opcode of the non-atomic one from the specified atomic instruction.
12300static unsigned getNonAtomicOpcode(unsigned Opc) {
12301  switch (Opc) {
12302  case X86::ATOMAND8:  return X86::AND8rr;
12303  case X86::ATOMAND16: return X86::AND16rr;
12304  case X86::ATOMAND32: return X86::AND32rr;
12305  case X86::ATOMAND64: return X86::AND64rr;
12306  case X86::ATOMOR8:   return X86::OR8rr;
12307  case X86::ATOMOR16:  return X86::OR16rr;
12308  case X86::ATOMOR32:  return X86::OR32rr;
12309  case X86::ATOMOR64:  return X86::OR64rr;
12310  case X86::ATOMXOR8:  return X86::XOR8rr;
12311  case X86::ATOMXOR16: return X86::XOR16rr;
12312  case X86::ATOMXOR32: return X86::XOR32rr;
12313  case X86::ATOMXOR64: return X86::XOR64rr;
12314  }
12315  llvm_unreachable("Unhandled atomic-load-op opcode!");
12316}
12317
12318// Get opcode of the non-atomic one from the specified atomic instruction with
12319// extra opcode.
12320static unsigned getNonAtomicOpcodeWithExtraOpc(unsigned Opc,
12321                                               unsigned &ExtraOpc) {
12322  switch (Opc) {
12323  case X86::ATOMNAND8:  ExtraOpc = X86::NOT8r;   return X86::AND8rr;
12324  case X86::ATOMNAND16: ExtraOpc = X86::NOT16r;  return X86::AND16rr;
12325  case X86::ATOMNAND32: ExtraOpc = X86::NOT32r;  return X86::AND32rr;
12326  case X86::ATOMNAND64: ExtraOpc = X86::NOT64r;  return X86::AND64rr;
12327  case X86::ATOMMAX8:   ExtraOpc = X86::CMP8rr;  return X86::CMOVL32rr;
12328  case X86::ATOMMAX16:  ExtraOpc = X86::CMP16rr; return X86::CMOVL16rr;
12329  case X86::ATOMMAX32:  ExtraOpc = X86::CMP32rr; return X86::CMOVL32rr;
12330  case X86::ATOMMAX64:  ExtraOpc = X86::CMP64rr; return X86::CMOVL64rr;
12331  case X86::ATOMMIN8:   ExtraOpc = X86::CMP8rr;  return X86::CMOVG32rr;
12332  case X86::ATOMMIN16:  ExtraOpc = X86::CMP16rr; return X86::CMOVG16rr;
12333  case X86::ATOMMIN32:  ExtraOpc = X86::CMP32rr; return X86::CMOVG32rr;
12334  case X86::ATOMMIN64:  ExtraOpc = X86::CMP64rr; return X86::CMOVG64rr;
12335  case X86::ATOMUMAX8:  ExtraOpc = X86::CMP8rr;  return X86::CMOVB32rr;
12336  case X86::ATOMUMAX16: ExtraOpc = X86::CMP16rr; return X86::CMOVB16rr;
12337  case X86::ATOMUMAX32: ExtraOpc = X86::CMP32rr; return X86::CMOVB32rr;
12338  case X86::ATOMUMAX64: ExtraOpc = X86::CMP64rr; return X86::CMOVB64rr;
12339  case X86::ATOMUMIN8:  ExtraOpc = X86::CMP8rr;  return X86::CMOVA32rr;
12340  case X86::ATOMUMIN16: ExtraOpc = X86::CMP16rr; return X86::CMOVA16rr;
12341  case X86::ATOMUMIN32: ExtraOpc = X86::CMP32rr; return X86::CMOVA32rr;
12342  case X86::ATOMUMIN64: ExtraOpc = X86::CMP64rr; return X86::CMOVA64rr;
12343  }
12344  llvm_unreachable("Unhandled atomic-load-op opcode!");
12345}
12346
12347// Get opcode of the non-atomic one from the specified atomic instruction for
12348// 64-bit data type on 32-bit target.
12349static unsigned getNonAtomic6432Opcode(unsigned Opc, unsigned &HiOpc) {
12350  switch (Opc) {
12351  case X86::ATOMAND6432:  HiOpc = X86::AND32rr; return X86::AND32rr;
12352  case X86::ATOMOR6432:   HiOpc = X86::OR32rr;  return X86::OR32rr;
12353  case X86::ATOMXOR6432:  HiOpc = X86::XOR32rr; return X86::XOR32rr;
12354  case X86::ATOMADD6432:  HiOpc = X86::ADC32rr; return X86::ADD32rr;
12355  case X86::ATOMSUB6432:  HiOpc = X86::SBB32rr; return X86::SUB32rr;
12356  case X86::ATOMSWAP6432: HiOpc = X86::MOV32rr; return X86::MOV32rr;
12357  case X86::ATOMMAX6432:  HiOpc = X86::SETLr;   return X86::SETLr;
12358  case X86::ATOMMIN6432:  HiOpc = X86::SETGr;   return X86::SETGr;
12359  case X86::ATOMUMAX6432: HiOpc = X86::SETBr;   return X86::SETBr;
12360  case X86::ATOMUMIN6432: HiOpc = X86::SETAr;   return X86::SETAr;
12361  }
12362  llvm_unreachable("Unhandled atomic-load-op opcode!");
12363}
12364
12365// Get opcode of the non-atomic one from the specified atomic instruction for
12366// 64-bit data type on 32-bit target with extra opcode.
12367static unsigned getNonAtomic6432OpcodeWithExtraOpc(unsigned Opc,
12368                                                   unsigned &HiOpc,
12369                                                   unsigned &ExtraOpc) {
12370  switch (Opc) {
12371  case X86::ATOMNAND6432:
12372    ExtraOpc = X86::NOT32r;
12373    HiOpc = X86::AND32rr;
12374    return X86::AND32rr;
12375  }
12376  llvm_unreachable("Unhandled atomic-load-op opcode!");
12377}
12378
12379// Get pseudo CMOV opcode from the specified data type.
12380static unsigned getPseudoCMOVOpc(EVT VT) {
12381  switch (VT.getSimpleVT().SimpleTy) {
12382  case MVT::i8:  return X86::CMOV_GR8;
12383  case MVT::i16: return X86::CMOV_GR16;
12384  case MVT::i32: return X86::CMOV_GR32;
12385  default:
12386    break;
12387  }
12388  llvm_unreachable("Unknown CMOV opcode!");
12389}
12390
12391// EmitAtomicLoadArith - emit the code sequence for pseudo atomic instructions.
12392// They will be translated into a spin-loop or compare-exchange loop from
12393//
12394//    ...
12395//    dst = atomic-fetch-op MI.addr, MI.val
12396//    ...
12397//
12398// to
12399//
12400//    ...
12401//    EAX = LOAD MI.addr
12402// loop:
12403//    t1 = OP MI.val, EAX
12404//    LCMPXCHG [MI.addr], t1, [EAX is implicitly used & defined]
12405//    JNE loop
12406// sink:
12407//    dst = EAX
12408//    ...
12409MachineBasicBlock *
12410X86TargetLowering::EmitAtomicLoadArith(MachineInstr *MI,
12411                                       MachineBasicBlock *MBB) const {
12412  const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12413  DebugLoc DL = MI->getDebugLoc();
12414
12415  MachineFunction *MF = MBB->getParent();
12416  MachineRegisterInfo &MRI = MF->getRegInfo();
12417
12418  const BasicBlock *BB = MBB->getBasicBlock();
12419  MachineFunction::iterator I = MBB;
12420  ++I;
12421
12422  assert(MI->getNumOperands() <= X86::AddrNumOperands + 2 &&
12423         "Unexpected number of operands");
12424
12425  assert(MI->hasOneMemOperand() &&
12426         "Expected atomic-load-op to have one memoperand");
12427
12428  // Memory Reference
12429  MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
12430  MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
12431
12432  unsigned DstReg, SrcReg;
12433  unsigned MemOpndSlot;
12434
12435  unsigned CurOp = 0;
12436
12437  DstReg = MI->getOperand(CurOp++).getReg();
12438  MemOpndSlot = CurOp;
12439  CurOp += X86::AddrNumOperands;
12440  SrcReg = MI->getOperand(CurOp++).getReg();
12441
12442  const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
12443  MVT::SimpleValueType VT = *RC->vt_begin();
12444  unsigned AccPhyReg = getX86SubSuperRegister(X86::EAX, VT);
12445
12446  unsigned LCMPXCHGOpc = getCmpXChgOpcode(VT);
12447  unsigned LOADOpc = getLoadOpcode(VT);
12448
12449  // For the atomic load-arith operator, we generate
12450  //
12451  //  thisMBB:
12452  //    EAX = LOAD [MI.addr]
12453  //  mainMBB:
12454  //    t1 = OP MI.val, EAX
12455  //    LCMPXCHG [MI.addr], t1, [EAX is implicitly used & defined]
12456  //    JNE mainMBB
12457  //  sinkMBB:
12458
12459  MachineBasicBlock *thisMBB = MBB;
12460  MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
12461  MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
12462  MF->insert(I, mainMBB);
12463  MF->insert(I, sinkMBB);
12464
12465  MachineInstrBuilder MIB;
12466
12467  // Transfer the remainder of BB and its successor edges to sinkMBB.
12468  sinkMBB->splice(sinkMBB->begin(), MBB,
12469                  llvm::next(MachineBasicBlock::iterator(MI)), MBB->end());
12470  sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
12471
12472  // thisMBB:
12473  MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), AccPhyReg);
12474  for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
12475    MIB.addOperand(MI->getOperand(MemOpndSlot + i));
12476  MIB.setMemRefs(MMOBegin, MMOEnd);
12477
12478  thisMBB->addSuccessor(mainMBB);
12479
12480  // mainMBB:
12481  MachineBasicBlock *origMainMBB = mainMBB;
12482  mainMBB->addLiveIn(AccPhyReg);
12483
12484  // Copy AccPhyReg as it is used more than once.
12485  unsigned AccReg = MRI.createVirtualRegister(RC);
12486  BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), AccReg)
12487    .addReg(AccPhyReg);
12488
12489  unsigned t1 = MRI.createVirtualRegister(RC);
12490  unsigned Opc = MI->getOpcode();
12491  switch (Opc) {
12492  default:
12493    llvm_unreachable("Unhandled atomic-load-op opcode!");
12494  case X86::ATOMAND8:
12495  case X86::ATOMAND16:
12496  case X86::ATOMAND32:
12497  case X86::ATOMAND64:
12498  case X86::ATOMOR8:
12499  case X86::ATOMOR16:
12500  case X86::ATOMOR32:
12501  case X86::ATOMOR64:
12502  case X86::ATOMXOR8:
12503  case X86::ATOMXOR16:
12504  case X86::ATOMXOR32:
12505  case X86::ATOMXOR64: {
12506    unsigned ARITHOpc = getNonAtomicOpcode(Opc);
12507    BuildMI(mainMBB, DL, TII->get(ARITHOpc), t1).addReg(SrcReg)
12508      .addReg(AccReg);
12509    break;
12510  }
12511  case X86::ATOMNAND8:
12512  case X86::ATOMNAND16:
12513  case X86::ATOMNAND32:
12514  case X86::ATOMNAND64: {
12515    unsigned t2 = MRI.createVirtualRegister(RC);
12516    unsigned NOTOpc;
12517    unsigned ANDOpc = getNonAtomicOpcodeWithExtraOpc(Opc, NOTOpc);
12518    BuildMI(mainMBB, DL, TII->get(ANDOpc), t2).addReg(SrcReg)
12519      .addReg(AccReg);
12520    BuildMI(mainMBB, DL, TII->get(NOTOpc), t1).addReg(t2);
12521    break;
12522  }
12523  case X86::ATOMMAX8:
12524  case X86::ATOMMAX16:
12525  case X86::ATOMMAX32:
12526  case X86::ATOMMAX64:
12527  case X86::ATOMMIN8:
12528  case X86::ATOMMIN16:
12529  case X86::ATOMMIN32:
12530  case X86::ATOMMIN64:
12531  case X86::ATOMUMAX8:
12532  case X86::ATOMUMAX16:
12533  case X86::ATOMUMAX32:
12534  case X86::ATOMUMAX64:
12535  case X86::ATOMUMIN8:
12536  case X86::ATOMUMIN16:
12537  case X86::ATOMUMIN32:
12538  case X86::ATOMUMIN64: {
12539    unsigned CMPOpc;
12540    unsigned CMOVOpc = getNonAtomicOpcodeWithExtraOpc(Opc, CMPOpc);
12541
12542    BuildMI(mainMBB, DL, TII->get(CMPOpc))
12543      .addReg(SrcReg)
12544      .addReg(AccReg);
12545
12546    if (Subtarget->hasCMov()) {
12547      if (VT != MVT::i8) {
12548        // Native support
12549        BuildMI(mainMBB, DL, TII->get(CMOVOpc), t1)
12550          .addReg(SrcReg)
12551          .addReg(AccReg);
12552      } else {
12553        // Promote i8 to i32 to use CMOV32
12554        const TargetRegisterClass *RC32 = getRegClassFor(MVT::i32);
12555        unsigned SrcReg32 = MRI.createVirtualRegister(RC32);
12556        unsigned AccReg32 = MRI.createVirtualRegister(RC32);
12557        unsigned t2 = MRI.createVirtualRegister(RC32);
12558
12559        unsigned Undef = MRI.createVirtualRegister(RC32);
12560        BuildMI(mainMBB, DL, TII->get(TargetOpcode::IMPLICIT_DEF), Undef);
12561
12562        BuildMI(mainMBB, DL, TII->get(TargetOpcode::INSERT_SUBREG), SrcReg32)
12563          .addReg(Undef)
12564          .addReg(SrcReg)
12565          .addImm(X86::sub_8bit);
12566        BuildMI(mainMBB, DL, TII->get(TargetOpcode::INSERT_SUBREG), AccReg32)
12567          .addReg(Undef)
12568          .addReg(AccReg)
12569          .addImm(X86::sub_8bit);
12570
12571        BuildMI(mainMBB, DL, TII->get(CMOVOpc), t2)
12572          .addReg(SrcReg32)
12573          .addReg(AccReg32);
12574
12575        BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t1)
12576          .addReg(t2, 0, X86::sub_8bit);
12577      }
12578    } else {
12579      // Use pseudo select and lower them.
12580      assert((VT == MVT::i8 || VT == MVT::i16 || VT == MVT::i32) &&
12581             "Invalid atomic-load-op transformation!");
12582      unsigned SelOpc = getPseudoCMOVOpc(VT);
12583      X86::CondCode CC = X86::getCondFromCMovOpc(CMOVOpc);
12584      assert(CC != X86::COND_INVALID && "Invalid atomic-load-op transformation!");
12585      MIB = BuildMI(mainMBB, DL, TII->get(SelOpc), t1)
12586              .addReg(SrcReg).addReg(AccReg)
12587              .addImm(CC);
12588      mainMBB = EmitLoweredSelect(MIB, mainMBB);
12589    }
12590    break;
12591  }
12592  }
12593
12594  // Copy AccPhyReg back from virtual register.
12595  BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), AccPhyReg)
12596    .addReg(AccReg);
12597
12598  MIB = BuildMI(mainMBB, DL, TII->get(LCMPXCHGOpc));
12599  for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
12600    MIB.addOperand(MI->getOperand(MemOpndSlot + i));
12601  MIB.addReg(t1);
12602  MIB.setMemRefs(MMOBegin, MMOEnd);
12603
12604  BuildMI(mainMBB, DL, TII->get(X86::JNE_4)).addMBB(origMainMBB);
12605
12606  mainMBB->addSuccessor(origMainMBB);
12607  mainMBB->addSuccessor(sinkMBB);
12608
12609  // sinkMBB:
12610  sinkMBB->addLiveIn(AccPhyReg);
12611
12612  BuildMI(*sinkMBB, sinkMBB->begin(), DL,
12613          TII->get(TargetOpcode::COPY), DstReg)
12614    .addReg(AccPhyReg);
12615
12616  MI->eraseFromParent();
12617  return sinkMBB;
12618}
12619
12620// EmitAtomicLoadArith6432 - emit the code sequence for pseudo atomic
12621// instructions. They will be translated into a spin-loop or compare-exchange
12622// loop from
12623//
12624//    ...
12625//    dst = atomic-fetch-op MI.addr, MI.val
12626//    ...
12627//
12628// to
12629//
12630//    ...
12631//    EAX = LOAD [MI.addr + 0]
12632//    EDX = LOAD [MI.addr + 4]
12633// loop:
12634//    EBX = OP MI.val.lo, EAX
12635//    ECX = OP MI.val.hi, EDX
12636//    LCMPXCHG8B [MI.addr], [ECX:EBX & EDX:EAX are implicitly used and EDX:EAX is implicitly defined]
12637//    JNE loop
12638// sink:
12639//    dst = EDX:EAX
12640//    ...
12641MachineBasicBlock *
12642X86TargetLowering::EmitAtomicLoadArith6432(MachineInstr *MI,
12643                                           MachineBasicBlock *MBB) const {
12644  const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12645  DebugLoc DL = MI->getDebugLoc();
12646
12647  MachineFunction *MF = MBB->getParent();
12648  MachineRegisterInfo &MRI = MF->getRegInfo();
12649
12650  const BasicBlock *BB = MBB->getBasicBlock();
12651  MachineFunction::iterator I = MBB;
12652  ++I;
12653
12654  assert(MI->getNumOperands() <= X86::AddrNumOperands + 4 &&
12655         "Unexpected number of operands");
12656
12657  assert(MI->hasOneMemOperand() &&
12658         "Expected atomic-load-op32 to have one memoperand");
12659
12660  // Memory Reference
12661  MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
12662  MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
12663
12664  unsigned DstLoReg, DstHiReg;
12665  unsigned SrcLoReg, SrcHiReg;
12666  unsigned MemOpndSlot;
12667
12668  unsigned CurOp = 0;
12669
12670  DstLoReg = MI->getOperand(CurOp++).getReg();
12671  DstHiReg = MI->getOperand(CurOp++).getReg();
12672  MemOpndSlot = CurOp;
12673  CurOp += X86::AddrNumOperands;
12674  SrcLoReg = MI->getOperand(CurOp++).getReg();
12675  SrcHiReg = MI->getOperand(CurOp++).getReg();
12676
12677  const TargetRegisterClass *RC = &X86::GR32RegClass;
12678  const TargetRegisterClass *RC8 = &X86::GR8RegClass;
12679
12680  unsigned LCMPXCHGOpc = X86::LCMPXCHG8B;
12681  unsigned LOADOpc = X86::MOV32rm;
12682
12683  // For the atomic load-arith operator, we generate
12684  //
12685  //  thisMBB:
12686  //    EAX = LOAD [MI.addr + 0]
12687  //    EDX = LOAD [MI.addr + 4]
12688  //  mainMBB:
12689  //    EBX = OP MI.vallo, EAX
12690  //    ECX = OP MI.valhi, EDX
12691  //    LCMPXCHG8B [MI.addr], [ECX:EBX & EDX:EAX are implicitly used and EDX:EAX is implicitly defined]
12692  //    JNE mainMBB
12693  //  sinkMBB:
12694
12695  MachineBasicBlock *thisMBB = MBB;
12696  MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
12697  MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
12698  MF->insert(I, mainMBB);
12699  MF->insert(I, sinkMBB);
12700
12701  MachineInstrBuilder MIB;
12702
12703  // Transfer the remainder of BB and its successor edges to sinkMBB.
12704  sinkMBB->splice(sinkMBB->begin(), MBB,
12705                  llvm::next(MachineBasicBlock::iterator(MI)), MBB->end());
12706  sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
12707
12708  // thisMBB:
12709  // Lo
12710  MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), X86::EAX);
12711  for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
12712    MIB.addOperand(MI->getOperand(MemOpndSlot + i));
12713  MIB.setMemRefs(MMOBegin, MMOEnd);
12714  // Hi
12715  MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), X86::EDX);
12716  for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
12717    if (i == X86::AddrDisp)
12718      MIB.addDisp(MI->getOperand(MemOpndSlot + i), 4); // 4 == sizeof(i32)
12719    else
12720      MIB.addOperand(MI->getOperand(MemOpndSlot + i));
12721  }
12722  MIB.setMemRefs(MMOBegin, MMOEnd);
12723
12724  thisMBB->addSuccessor(mainMBB);
12725
12726  // mainMBB:
12727  MachineBasicBlock *origMainMBB = mainMBB;
12728  mainMBB->addLiveIn(X86::EAX);
12729  mainMBB->addLiveIn(X86::EDX);
12730
12731  // Copy EDX:EAX as they are used more than once.
12732  unsigned LoReg = MRI.createVirtualRegister(RC);
12733  unsigned HiReg = MRI.createVirtualRegister(RC);
12734  BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), LoReg).addReg(X86::EAX);
12735  BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), HiReg).addReg(X86::EDX);
12736
12737  unsigned t1L = MRI.createVirtualRegister(RC);
12738  unsigned t1H = MRI.createVirtualRegister(RC);
12739
12740  unsigned Opc = MI->getOpcode();
12741  switch (Opc) {
12742  default:
12743    llvm_unreachable("Unhandled atomic-load-op6432 opcode!");
12744  case X86::ATOMAND6432:
12745  case X86::ATOMOR6432:
12746  case X86::ATOMXOR6432:
12747  case X86::ATOMADD6432:
12748  case X86::ATOMSUB6432: {
12749    unsigned HiOpc;
12750    unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
12751    BuildMI(mainMBB, DL, TII->get(LoOpc), t1L).addReg(LoReg).addReg(SrcLoReg);
12752    BuildMI(mainMBB, DL, TII->get(HiOpc), t1H).addReg(HiReg).addReg(SrcHiReg);
12753    break;
12754  }
12755  case X86::ATOMNAND6432: {
12756    unsigned HiOpc, NOTOpc;
12757    unsigned LoOpc = getNonAtomic6432OpcodeWithExtraOpc(Opc, HiOpc, NOTOpc);
12758    unsigned t2L = MRI.createVirtualRegister(RC);
12759    unsigned t2H = MRI.createVirtualRegister(RC);
12760    BuildMI(mainMBB, DL, TII->get(LoOpc), t2L).addReg(SrcLoReg).addReg(LoReg);
12761    BuildMI(mainMBB, DL, TII->get(HiOpc), t2H).addReg(SrcHiReg).addReg(HiReg);
12762    BuildMI(mainMBB, DL, TII->get(NOTOpc), t1L).addReg(t2L);
12763    BuildMI(mainMBB, DL, TII->get(NOTOpc), t1H).addReg(t2H);
12764    break;
12765  }
12766  case X86::ATOMMAX6432:
12767  case X86::ATOMMIN6432:
12768  case X86::ATOMUMAX6432:
12769  case X86::ATOMUMIN6432: {
12770    unsigned HiOpc;
12771    unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
12772    unsigned cL = MRI.createVirtualRegister(RC8);
12773    unsigned cH = MRI.createVirtualRegister(RC8);
12774    unsigned cL32 = MRI.createVirtualRegister(RC);
12775    unsigned cH32 = MRI.createVirtualRegister(RC);
12776    unsigned cc = MRI.createVirtualRegister(RC);
12777    // cl := cmp src_lo, lo
12778    BuildMI(mainMBB, DL, TII->get(X86::CMP32rr))
12779      .addReg(SrcLoReg).addReg(LoReg);
12780    BuildMI(mainMBB, DL, TII->get(LoOpc), cL);
12781    BuildMI(mainMBB, DL, TII->get(X86::MOVZX32rr8), cL32).addReg(cL);
12782    // ch := cmp src_hi, hi
12783    BuildMI(mainMBB, DL, TII->get(X86::CMP32rr))
12784      .addReg(SrcHiReg).addReg(HiReg);
12785    BuildMI(mainMBB, DL, TII->get(HiOpc), cH);
12786    BuildMI(mainMBB, DL, TII->get(X86::MOVZX32rr8), cH32).addReg(cH);
12787    // cc := if (src_hi == hi) ? cl : ch;
12788    if (Subtarget->hasCMov()) {
12789      BuildMI(mainMBB, DL, TII->get(X86::CMOVE32rr), cc)
12790        .addReg(cH32).addReg(cL32);
12791    } else {
12792      MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), cc)
12793              .addReg(cH32).addReg(cL32)
12794              .addImm(X86::COND_E);
12795      mainMBB = EmitLoweredSelect(MIB, mainMBB);
12796    }
12797    BuildMI(mainMBB, DL, TII->get(X86::TEST32rr)).addReg(cc).addReg(cc);
12798    if (Subtarget->hasCMov()) {
12799      BuildMI(mainMBB, DL, TII->get(X86::CMOVNE32rr), t1L)
12800        .addReg(SrcLoReg).addReg(LoReg);
12801      BuildMI(mainMBB, DL, TII->get(X86::CMOVNE32rr), t1H)
12802        .addReg(SrcHiReg).addReg(HiReg);
12803    } else {
12804      MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), t1L)
12805              .addReg(SrcLoReg).addReg(LoReg)
12806              .addImm(X86::COND_NE);
12807      mainMBB = EmitLoweredSelect(MIB, mainMBB);
12808      MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), t1H)
12809              .addReg(SrcHiReg).addReg(HiReg)
12810              .addImm(X86::COND_NE);
12811      mainMBB = EmitLoweredSelect(MIB, mainMBB);
12812    }
12813    break;
12814  }
12815  case X86::ATOMSWAP6432: {
12816    unsigned HiOpc;
12817    unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
12818    BuildMI(mainMBB, DL, TII->get(LoOpc), t1L).addReg(SrcLoReg);
12819    BuildMI(mainMBB, DL, TII->get(HiOpc), t1H).addReg(SrcHiReg);
12820    break;
12821  }
12822  }
12823
12824  // Copy EDX:EAX back from HiReg:LoReg
12825  BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EAX).addReg(LoReg);
12826  BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EDX).addReg(HiReg);
12827  // Copy ECX:EBX from t1H:t1L
12828  BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EBX).addReg(t1L);
12829  BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::ECX).addReg(t1H);
12830
12831  MIB = BuildMI(mainMBB, DL, TII->get(LCMPXCHGOpc));
12832  for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
12833    MIB.addOperand(MI->getOperand(MemOpndSlot + i));
12834  MIB.setMemRefs(MMOBegin, MMOEnd);
12835
12836  BuildMI(mainMBB, DL, TII->get(X86::JNE_4)).addMBB(origMainMBB);
12837
12838  mainMBB->addSuccessor(origMainMBB);
12839  mainMBB->addSuccessor(sinkMBB);
12840
12841  // sinkMBB:
12842  sinkMBB->addLiveIn(X86::EAX);
12843  sinkMBB->addLiveIn(X86::EDX);
12844
12845  BuildMI(*sinkMBB, sinkMBB->begin(), DL,
12846          TII->get(TargetOpcode::COPY), DstLoReg)
12847    .addReg(X86::EAX);
12848  BuildMI(*sinkMBB, sinkMBB->begin(), DL,
12849          TII->get(TargetOpcode::COPY), DstHiReg)
12850    .addReg(X86::EDX);
12851
12852  MI->eraseFromParent();
12853  return sinkMBB;
12854}
12855
12856// FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
12857// or XMM0_V32I8 in AVX all of this code can be replaced with that
12858// in the .td file.
12859static MachineBasicBlock *EmitPCMPSTRM(MachineInstr *MI, MachineBasicBlock *BB,
12860                                       const TargetInstrInfo *TII) {
12861  unsigned Opc;
12862  switch (MI->getOpcode()) {
12863  default: llvm_unreachable("illegal opcode!");
12864  case X86::PCMPISTRM128REG:  Opc = X86::PCMPISTRM128rr;  break;
12865  case X86::VPCMPISTRM128REG: Opc = X86::VPCMPISTRM128rr; break;
12866  case X86::PCMPISTRM128MEM:  Opc = X86::PCMPISTRM128rm;  break;
12867  case X86::VPCMPISTRM128MEM: Opc = X86::VPCMPISTRM128rm; break;
12868  case X86::PCMPESTRM128REG:  Opc = X86::PCMPESTRM128rr;  break;
12869  case X86::VPCMPESTRM128REG: Opc = X86::VPCMPESTRM128rr; break;
12870  case X86::PCMPESTRM128MEM:  Opc = X86::PCMPESTRM128rm;  break;
12871  case X86::VPCMPESTRM128MEM: Opc = X86::VPCMPESTRM128rm; break;
12872  }
12873
12874  DebugLoc dl = MI->getDebugLoc();
12875  MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
12876
12877  unsigned NumArgs = MI->getNumOperands();
12878  for (unsigned i = 1; i < NumArgs; ++i) {
12879    MachineOperand &Op = MI->getOperand(i);
12880    if (!(Op.isReg() && Op.isImplicit()))
12881      MIB.addOperand(Op);
12882  }
12883  if (MI->hasOneMemOperand())
12884    MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
12885
12886  BuildMI(*BB, MI, dl,
12887    TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
12888    .addReg(X86::XMM0);
12889
12890  MI->eraseFromParent();
12891  return BB;
12892}
12893
12894// FIXME: Custom handling because TableGen doesn't support multiple implicit
12895// defs in an instruction pattern
12896static MachineBasicBlock *EmitPCMPSTRI(MachineInstr *MI, MachineBasicBlock *BB,
12897                                       const TargetInstrInfo *TII) {
12898  unsigned Opc;
12899  switch (MI->getOpcode()) {
12900  default: llvm_unreachable("illegal opcode!");
12901  case X86::PCMPISTRIREG:  Opc = X86::PCMPISTRIrr;  break;
12902  case X86::VPCMPISTRIREG: Opc = X86::VPCMPISTRIrr; break;
12903  case X86::PCMPISTRIMEM:  Opc = X86::PCMPISTRIrm;  break;
12904  case X86::VPCMPISTRIMEM: Opc = X86::VPCMPISTRIrm; break;
12905  case X86::PCMPESTRIREG:  Opc = X86::PCMPESTRIrr;  break;
12906  case X86::VPCMPESTRIREG: Opc = X86::VPCMPESTRIrr; break;
12907  case X86::PCMPESTRIMEM:  Opc = X86::PCMPESTRIrm;  break;
12908  case X86::VPCMPESTRIMEM: Opc = X86::VPCMPESTRIrm; break;
12909  }
12910
12911  DebugLoc dl = MI->getDebugLoc();
12912  MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
12913
12914  unsigned NumArgs = MI->getNumOperands(); // remove the results
12915  for (unsigned i = 1; i < NumArgs; ++i) {
12916    MachineOperand &Op = MI->getOperand(i);
12917    if (!(Op.isReg() && Op.isImplicit()))
12918      MIB.addOperand(Op);
12919  }
12920  if (MI->hasOneMemOperand())
12921    MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
12922
12923  BuildMI(*BB, MI, dl,
12924    TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
12925    .addReg(X86::ECX);
12926
12927  MI->eraseFromParent();
12928  return BB;
12929}
12930
12931static MachineBasicBlock * EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB,
12932                                       const TargetInstrInfo *TII,
12933                                       const X86Subtarget* Subtarget) {
12934  DebugLoc dl = MI->getDebugLoc();
12935
12936  // Address into RAX/EAX, other two args into ECX, EDX.
12937  unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
12938  unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
12939  MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
12940  for (int i = 0; i < X86::AddrNumOperands; ++i)
12941    MIB.addOperand(MI->getOperand(i));
12942
12943  unsigned ValOps = X86::AddrNumOperands;
12944  BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
12945    .addReg(MI->getOperand(ValOps).getReg());
12946  BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
12947    .addReg(MI->getOperand(ValOps+1).getReg());
12948
12949  // The instruction doesn't actually take any operands though.
12950  BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
12951
12952  MI->eraseFromParent(); // The pseudo is gone now.
12953  return BB;
12954}
12955
12956MachineBasicBlock *
12957X86TargetLowering::EmitVAARG64WithCustomInserter(
12958                   MachineInstr *MI,
12959                   MachineBasicBlock *MBB) const {
12960  // Emit va_arg instruction on X86-64.
12961
12962  // Operands to this pseudo-instruction:
12963  // 0  ) Output        : destination address (reg)
12964  // 1-5) Input         : va_list address (addr, i64mem)
12965  // 6  ) ArgSize       : Size (in bytes) of vararg type
12966  // 7  ) ArgMode       : 0=overflow only, 1=use gp_offset, 2=use fp_offset
12967  // 8  ) Align         : Alignment of type
12968  // 9  ) EFLAGS (implicit-def)
12969
12970  assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
12971  assert(X86::AddrNumOperands == 5 && "VAARG_64 assumes 5 address operands");
12972
12973  unsigned DestReg = MI->getOperand(0).getReg();
12974  MachineOperand &Base = MI->getOperand(1);
12975  MachineOperand &Scale = MI->getOperand(2);
12976  MachineOperand &Index = MI->getOperand(3);
12977  MachineOperand &Disp = MI->getOperand(4);
12978  MachineOperand &Segment = MI->getOperand(5);
12979  unsigned ArgSize = MI->getOperand(6).getImm();
12980  unsigned ArgMode = MI->getOperand(7).getImm();
12981  unsigned Align = MI->getOperand(8).getImm();
12982
12983  // Memory Reference
12984  assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
12985  MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
12986  MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
12987
12988  // Machine Information
12989  const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12990  MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
12991  const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
12992  const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
12993  DebugLoc DL = MI->getDebugLoc();
12994
12995  // struct va_list {
12996  //   i32   gp_offset
12997  //   i32   fp_offset
12998  //   i64   overflow_area (address)
12999  //   i64   reg_save_area (address)
13000  // }
13001  // sizeof(va_list) = 24
13002  // alignment(va_list) = 8
13003
13004  unsigned TotalNumIntRegs = 6;
13005  unsigned TotalNumXMMRegs = 8;
13006  bool UseGPOffset = (ArgMode == 1);
13007  bool UseFPOffset = (ArgMode == 2);
13008  unsigned MaxOffset = TotalNumIntRegs * 8 +
13009                       (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
13010
13011  /* Align ArgSize to a multiple of 8 */
13012  unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
13013  bool NeedsAlign = (Align > 8);
13014
13015  MachineBasicBlock *thisMBB = MBB;
13016  MachineBasicBlock *overflowMBB;
13017  MachineBasicBlock *offsetMBB;
13018  MachineBasicBlock *endMBB;
13019
13020  unsigned OffsetDestReg = 0;    // Argument address computed by offsetMBB
13021  unsigned OverflowDestReg = 0;  // Argument address computed by overflowMBB
13022  unsigned OffsetReg = 0;
13023
13024  if (!UseGPOffset && !UseFPOffset) {
13025    // If we only pull from the overflow region, we don't create a branch.
13026    // We don't need to alter control flow.
13027    OffsetDestReg = 0; // unused
13028    OverflowDestReg = DestReg;
13029
13030    offsetMBB = NULL;
13031    overflowMBB = thisMBB;
13032    endMBB = thisMBB;
13033  } else {
13034    // First emit code to check if gp_offset (or fp_offset) is below the bound.
13035    // If so, pull the argument from reg_save_area. (branch to offsetMBB)
13036    // If not, pull from overflow_area. (branch to overflowMBB)
13037    //
13038    //       thisMBB
13039    //         |     .
13040    //         |        .
13041    //     offsetMBB   overflowMBB
13042    //         |        .
13043    //         |     .
13044    //        endMBB
13045
13046    // Registers for the PHI in endMBB
13047    OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
13048    OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
13049
13050    const BasicBlock *LLVM_BB = MBB->getBasicBlock();
13051    MachineFunction *MF = MBB->getParent();
13052    overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
13053    offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
13054    endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
13055
13056    MachineFunction::iterator MBBIter = MBB;
13057    ++MBBIter;
13058
13059    // Insert the new basic blocks
13060    MF->insert(MBBIter, offsetMBB);
13061    MF->insert(MBBIter, overflowMBB);
13062    MF->insert(MBBIter, endMBB);
13063
13064    // Transfer the remainder of MBB and its successor edges to endMBB.
13065    endMBB->splice(endMBB->begin(), thisMBB,
13066                    llvm::next(MachineBasicBlock::iterator(MI)),
13067                    thisMBB->end());
13068    endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
13069
13070    // Make offsetMBB and overflowMBB successors of thisMBB
13071    thisMBB->addSuccessor(offsetMBB);
13072    thisMBB->addSuccessor(overflowMBB);
13073
13074    // endMBB is a successor of both offsetMBB and overflowMBB
13075    offsetMBB->addSuccessor(endMBB);
13076    overflowMBB->addSuccessor(endMBB);
13077
13078    // Load the offset value into a register
13079    OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
13080    BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
13081      .addOperand(Base)
13082      .addOperand(Scale)
13083      .addOperand(Index)
13084      .addDisp(Disp, UseFPOffset ? 4 : 0)
13085      .addOperand(Segment)
13086      .setMemRefs(MMOBegin, MMOEnd);
13087
13088    // Check if there is enough room left to pull this argument.
13089    BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
13090      .addReg(OffsetReg)
13091      .addImm(MaxOffset + 8 - ArgSizeA8);
13092
13093    // Branch to "overflowMBB" if offset >= max
13094    // Fall through to "offsetMBB" otherwise
13095    BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
13096      .addMBB(overflowMBB);
13097  }
13098
13099  // In offsetMBB, emit code to use the reg_save_area.
13100  if (offsetMBB) {
13101    assert(OffsetReg != 0);
13102
13103    // Read the reg_save_area address.
13104    unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
13105    BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
13106      .addOperand(Base)
13107      .addOperand(Scale)
13108      .addOperand(Index)
13109      .addDisp(Disp, 16)
13110      .addOperand(Segment)
13111      .setMemRefs(MMOBegin, MMOEnd);
13112
13113    // Zero-extend the offset
13114    unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
13115      BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
13116        .addImm(0)
13117        .addReg(OffsetReg)
13118        .addImm(X86::sub_32bit);
13119
13120    // Add the offset to the reg_save_area to get the final address.
13121    BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
13122      .addReg(OffsetReg64)
13123      .addReg(RegSaveReg);
13124
13125    // Compute the offset for the next argument
13126    unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
13127    BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
13128      .addReg(OffsetReg)
13129      .addImm(UseFPOffset ? 16 : 8);
13130
13131    // Store it back into the va_list.
13132    BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
13133      .addOperand(Base)
13134      .addOperand(Scale)
13135      .addOperand(Index)
13136      .addDisp(Disp, UseFPOffset ? 4 : 0)
13137      .addOperand(Segment)
13138      .addReg(NextOffsetReg)
13139      .setMemRefs(MMOBegin, MMOEnd);
13140
13141    // Jump to endMBB
13142    BuildMI(offsetMBB, DL, TII->get(X86::JMP_4))
13143      .addMBB(endMBB);
13144  }
13145
13146  //
13147  // Emit code to use overflow area
13148  //
13149
13150  // Load the overflow_area address into a register.
13151  unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
13152  BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
13153    .addOperand(Base)
13154    .addOperand(Scale)
13155    .addOperand(Index)
13156    .addDisp(Disp, 8)
13157    .addOperand(Segment)
13158    .setMemRefs(MMOBegin, MMOEnd);
13159
13160  // If we need to align it, do so. Otherwise, just copy the address
13161  // to OverflowDestReg.
13162  if (NeedsAlign) {
13163    // Align the overflow address
13164    assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
13165    unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
13166
13167    // aligned_addr = (addr + (align-1)) & ~(align-1)
13168    BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
13169      .addReg(OverflowAddrReg)
13170      .addImm(Align-1);
13171
13172    BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
13173      .addReg(TmpReg)
13174      .addImm(~(uint64_t)(Align-1));
13175  } else {
13176    BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
13177      .addReg(OverflowAddrReg);
13178  }
13179
13180  // Compute the next overflow address after this argument.
13181  // (the overflow address should be kept 8-byte aligned)
13182  unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
13183  BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
13184    .addReg(OverflowDestReg)
13185    .addImm(ArgSizeA8);
13186
13187  // Store the new overflow address.
13188  BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
13189    .addOperand(Base)
13190    .addOperand(Scale)
13191    .addOperand(Index)
13192    .addDisp(Disp, 8)
13193    .addOperand(Segment)
13194    .addReg(NextAddrReg)
13195    .setMemRefs(MMOBegin, MMOEnd);
13196
13197  // If we branched, emit the PHI to the front of endMBB.
13198  if (offsetMBB) {
13199    BuildMI(*endMBB, endMBB->begin(), DL,
13200            TII->get(X86::PHI), DestReg)
13201      .addReg(OffsetDestReg).addMBB(offsetMBB)
13202      .addReg(OverflowDestReg).addMBB(overflowMBB);
13203  }
13204
13205  // Erase the pseudo instruction
13206  MI->eraseFromParent();
13207
13208  return endMBB;
13209}
13210
13211MachineBasicBlock *
13212X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
13213                                                 MachineInstr *MI,
13214                                                 MachineBasicBlock *MBB) const {
13215  // Emit code to save XMM registers to the stack. The ABI says that the
13216  // number of registers to save is given in %al, so it's theoretically
13217  // possible to do an indirect jump trick to avoid saving all of them,
13218  // however this code takes a simpler approach and just executes all
13219  // of the stores if %al is non-zero. It's less code, and it's probably
13220  // easier on the hardware branch predictor, and stores aren't all that
13221  // expensive anyway.
13222
13223  // Create the new basic blocks. One block contains all the XMM stores,
13224  // and one block is the final destination regardless of whether any
13225  // stores were performed.
13226  const BasicBlock *LLVM_BB = MBB->getBasicBlock();
13227  MachineFunction *F = MBB->getParent();
13228  MachineFunction::iterator MBBIter = MBB;
13229  ++MBBIter;
13230  MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
13231  MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
13232  F->insert(MBBIter, XMMSaveMBB);
13233  F->insert(MBBIter, EndMBB);
13234
13235  // Transfer the remainder of MBB and its successor edges to EndMBB.
13236  EndMBB->splice(EndMBB->begin(), MBB,
13237                 llvm::next(MachineBasicBlock::iterator(MI)),
13238                 MBB->end());
13239  EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
13240
13241  // The original block will now fall through to the XMM save block.
13242  MBB->addSuccessor(XMMSaveMBB);
13243  // The XMMSaveMBB will fall through to the end block.
13244  XMMSaveMBB->addSuccessor(EndMBB);
13245
13246  // Now add the instructions.
13247  const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
13248  DebugLoc DL = MI->getDebugLoc();
13249
13250  unsigned CountReg = MI->getOperand(0).getReg();
13251  int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
13252  int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
13253
13254  if (!Subtarget->isTargetWin64()) {
13255    // If %al is 0, branch around the XMM save block.
13256    BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
13257    BuildMI(MBB, DL, TII->get(X86::JE_4)).addMBB(EndMBB);
13258    MBB->addSuccessor(EndMBB);
13259  }
13260
13261  unsigned MOVOpc = Subtarget->hasAVX() ? X86::VMOVAPSmr : X86::MOVAPSmr;
13262  // In the XMM save block, save all the XMM argument registers.
13263  for (int i = 3, e = MI->getNumOperands(); i != e; ++i) {
13264    int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
13265    MachineMemOperand *MMO =
13266      F->getMachineMemOperand(
13267          MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
13268        MachineMemOperand::MOStore,
13269        /*Size=*/16, /*Align=*/16);
13270    BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
13271      .addFrameIndex(RegSaveFrameIndex)
13272      .addImm(/*Scale=*/1)
13273      .addReg(/*IndexReg=*/0)
13274      .addImm(/*Disp=*/Offset)
13275      .addReg(/*Segment=*/0)
13276      .addReg(MI->getOperand(i).getReg())
13277      .addMemOperand(MMO);
13278  }
13279
13280  MI->eraseFromParent();   // The pseudo instruction is gone now.
13281
13282  return EndMBB;
13283}
13284
13285// The EFLAGS operand of SelectItr might be missing a kill marker
13286// because there were multiple uses of EFLAGS, and ISel didn't know
13287// which to mark. Figure out whether SelectItr should have had a
13288// kill marker, and set it if it should. Returns the correct kill
13289// marker value.
13290static bool checkAndUpdateEFLAGSKill(MachineBasicBlock::iterator SelectItr,
13291                                     MachineBasicBlock* BB,
13292                                     const TargetRegisterInfo* TRI) {
13293  // Scan forward through BB for a use/def of EFLAGS.
13294  MachineBasicBlock::iterator miI(llvm::next(SelectItr));
13295  for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
13296    const MachineInstr& mi = *miI;
13297    if (mi.readsRegister(X86::EFLAGS))
13298      return false;
13299    if (mi.definesRegister(X86::EFLAGS))
13300      break; // Should have kill-flag - update below.
13301  }
13302
13303  // If we hit the end of the block, check whether EFLAGS is live into a
13304  // successor.
13305  if (miI == BB->end()) {
13306    for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
13307                                          sEnd = BB->succ_end();
13308         sItr != sEnd; ++sItr) {
13309      MachineBasicBlock* succ = *sItr;
13310      if (succ->isLiveIn(X86::EFLAGS))
13311        return false;
13312    }
13313  }
13314
13315  // We found a def, or hit the end of the basic block and EFLAGS wasn't live
13316  // out. SelectMI should have a kill flag on EFLAGS.
13317  SelectItr->addRegisterKilled(X86::EFLAGS, TRI);
13318  return true;
13319}
13320
13321MachineBasicBlock *
13322X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
13323                                     MachineBasicBlock *BB) const {
13324  const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
13325  DebugLoc DL = MI->getDebugLoc();
13326
13327  // To "insert" a SELECT_CC instruction, we actually have to insert the
13328  // diamond control-flow pattern.  The incoming instruction knows the
13329  // destination vreg to set, the condition code register to branch on, the
13330  // true/false values to select between, and a branch opcode to use.
13331  const BasicBlock *LLVM_BB = BB->getBasicBlock();
13332  MachineFunction::iterator It = BB;
13333  ++It;
13334
13335  //  thisMBB:
13336  //  ...
13337  //   TrueVal = ...
13338  //   cmpTY ccX, r1, r2
13339  //   bCC copy1MBB
13340  //   fallthrough --> copy0MBB
13341  MachineBasicBlock *thisMBB = BB;
13342  MachineFunction *F = BB->getParent();
13343  MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
13344  MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
13345  F->insert(It, copy0MBB);
13346  F->insert(It, sinkMBB);
13347
13348  // If the EFLAGS register isn't dead in the terminator, then claim that it's
13349  // live into the sink and copy blocks.
13350  const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
13351  if (!MI->killsRegister(X86::EFLAGS) &&
13352      !checkAndUpdateEFLAGSKill(MI, BB, TRI)) {
13353    copy0MBB->addLiveIn(X86::EFLAGS);
13354    sinkMBB->addLiveIn(X86::EFLAGS);
13355  }
13356
13357  // Transfer the remainder of BB and its successor edges to sinkMBB.
13358  sinkMBB->splice(sinkMBB->begin(), BB,
13359                  llvm::next(MachineBasicBlock::iterator(MI)),
13360                  BB->end());
13361  sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
13362
13363  // Add the true and fallthrough blocks as its successors.
13364  BB->addSuccessor(copy0MBB);
13365  BB->addSuccessor(sinkMBB);
13366
13367  // Create the conditional branch instruction.
13368  unsigned Opc =
13369    X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
13370  BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
13371
13372  //  copy0MBB:
13373  //   %FalseValue = ...
13374  //   # fallthrough to sinkMBB
13375  copy0MBB->addSuccessor(sinkMBB);
13376
13377  //  sinkMBB:
13378  //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
13379  //  ...
13380  BuildMI(*sinkMBB, sinkMBB->begin(), DL,
13381          TII->get(X86::PHI), MI->getOperand(0).getReg())
13382    .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
13383    .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
13384
13385  MI->eraseFromParent();   // The pseudo instruction is gone now.
13386  return sinkMBB;
13387}
13388
13389MachineBasicBlock *
13390X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI, MachineBasicBlock *BB,
13391                                        bool Is64Bit) const {
13392  const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
13393  DebugLoc DL = MI->getDebugLoc();
13394  MachineFunction *MF = BB->getParent();
13395  const BasicBlock *LLVM_BB = BB->getBasicBlock();
13396
13397  assert(getTargetMachine().Options.EnableSegmentedStacks);
13398
13399  unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
13400  unsigned TlsOffset = Is64Bit ? 0x70 : 0x30;
13401
13402  // BB:
13403  //  ... [Till the alloca]
13404  // If stacklet is not large enough, jump to mallocMBB
13405  //
13406  // bumpMBB:
13407  //  Allocate by subtracting from RSP
13408  //  Jump to continueMBB
13409  //
13410  // mallocMBB:
13411  //  Allocate by call to runtime
13412  //
13413  // continueMBB:
13414  //  ...
13415  //  [rest of original BB]
13416  //
13417
13418  MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
13419  MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
13420  MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
13421
13422  MachineRegisterInfo &MRI = MF->getRegInfo();
13423  const TargetRegisterClass *AddrRegClass =
13424    getRegClassFor(Is64Bit ? MVT::i64:MVT::i32);
13425
13426  unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
13427    bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
13428    tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
13429    SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
13430    sizeVReg = MI->getOperand(1).getReg(),
13431    physSPReg = Is64Bit ? X86::RSP : X86::ESP;
13432
13433  MachineFunction::iterator MBBIter = BB;
13434  ++MBBIter;
13435
13436  MF->insert(MBBIter, bumpMBB);
13437  MF->insert(MBBIter, mallocMBB);
13438  MF->insert(MBBIter, continueMBB);
13439
13440  continueMBB->splice(continueMBB->begin(), BB, llvm::next
13441                      (MachineBasicBlock::iterator(MI)), BB->end());
13442  continueMBB->transferSuccessorsAndUpdatePHIs(BB);
13443
13444  // Add code to the main basic block to check if the stack limit has been hit,
13445  // and if so, jump to mallocMBB otherwise to bumpMBB.
13446  BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
13447  BuildMI(BB, DL, TII->get(Is64Bit ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
13448    .addReg(tmpSPVReg).addReg(sizeVReg);
13449  BuildMI(BB, DL, TII->get(Is64Bit ? X86::CMP64mr:X86::CMP32mr))
13450    .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg)
13451    .addReg(SPLimitVReg);
13452  BuildMI(BB, DL, TII->get(X86::JG_4)).addMBB(mallocMBB);
13453
13454  // bumpMBB simply decreases the stack pointer, since we know the current
13455  // stacklet has enough space.
13456  BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
13457    .addReg(SPLimitVReg);
13458  BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
13459    .addReg(SPLimitVReg);
13460  BuildMI(bumpMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
13461
13462  // Calls into a routine in libgcc to allocate more space from the heap.
13463  const uint32_t *RegMask =
13464    getTargetMachine().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
13465  if (Is64Bit) {
13466    BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
13467      .addReg(sizeVReg);
13468    BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
13469      .addExternalSymbol("__morestack_allocate_stack_space")
13470      .addRegMask(RegMask)
13471      .addReg(X86::RDI, RegState::Implicit)
13472      .addReg(X86::RAX, RegState::ImplicitDefine);
13473  } else {
13474    BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
13475      .addImm(12);
13476    BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
13477    BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
13478      .addExternalSymbol("__morestack_allocate_stack_space")
13479      .addRegMask(RegMask)
13480      .addReg(X86::EAX, RegState::ImplicitDefine);
13481  }
13482
13483  if (!Is64Bit)
13484    BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
13485      .addImm(16);
13486
13487  BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
13488    .addReg(Is64Bit ? X86::RAX : X86::EAX);
13489  BuildMI(mallocMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
13490
13491  // Set up the CFG correctly.
13492  BB->addSuccessor(bumpMBB);
13493  BB->addSuccessor(mallocMBB);
13494  mallocMBB->addSuccessor(continueMBB);
13495  bumpMBB->addSuccessor(continueMBB);
13496
13497  // Take care of the PHI nodes.
13498  BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
13499          MI->getOperand(0).getReg())
13500    .addReg(mallocPtrVReg).addMBB(mallocMBB)
13501    .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
13502
13503  // Delete the original pseudo instruction.
13504  MI->eraseFromParent();
13505
13506  // And we're done.
13507  return continueMBB;
13508}
13509
13510MachineBasicBlock *
13511X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
13512                                          MachineBasicBlock *BB) const {
13513  const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
13514  DebugLoc DL = MI->getDebugLoc();
13515
13516  assert(!Subtarget->isTargetEnvMacho());
13517
13518  // The lowering is pretty easy: we're just emitting the call to _alloca.  The
13519  // non-trivial part is impdef of ESP.
13520
13521  if (Subtarget->isTargetWin64()) {
13522    if (Subtarget->isTargetCygMing()) {
13523      // ___chkstk(Mingw64):
13524      // Clobbers R10, R11, RAX and EFLAGS.
13525      // Updates RSP.
13526      BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
13527        .addExternalSymbol("___chkstk")
13528        .addReg(X86::RAX, RegState::Implicit)
13529        .addReg(X86::RSP, RegState::Implicit)
13530        .addReg(X86::RAX, RegState::Define | RegState::Implicit)
13531        .addReg(X86::RSP, RegState::Define | RegState::Implicit)
13532        .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
13533    } else {
13534      // __chkstk(MSVCRT): does not update stack pointer.
13535      // Clobbers R10, R11 and EFLAGS.
13536      // FIXME: RAX(allocated size) might be reused and not killed.
13537      BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
13538        .addExternalSymbol("__chkstk")
13539        .addReg(X86::RAX, RegState::Implicit)
13540        .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
13541      // RAX has the offset to subtracted from RSP.
13542      BuildMI(*BB, MI, DL, TII->get(X86::SUB64rr), X86::RSP)
13543        .addReg(X86::RSP)
13544        .addReg(X86::RAX);
13545    }
13546  } else {
13547    const char *StackProbeSymbol =
13548      Subtarget->isTargetWindows() ? "_chkstk" : "_alloca";
13549
13550    BuildMI(*BB, MI, DL, TII->get(X86::CALLpcrel32))
13551      .addExternalSymbol(StackProbeSymbol)
13552      .addReg(X86::EAX, RegState::Implicit)
13553      .addReg(X86::ESP, RegState::Implicit)
13554      .addReg(X86::EAX, RegState::Define | RegState::Implicit)
13555      .addReg(X86::ESP, RegState::Define | RegState::Implicit)
13556      .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
13557  }
13558
13559  MI->eraseFromParent();   // The pseudo instruction is gone now.
13560  return BB;
13561}
13562
13563MachineBasicBlock *
13564X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
13565                                      MachineBasicBlock *BB) const {
13566  // This is pretty easy.  We're taking the value that we received from
13567  // our load from the relocation, sticking it in either RDI (x86-64)
13568  // or EAX and doing an indirect call.  The return value will then
13569  // be in the normal return register.
13570  const X86InstrInfo *TII
13571    = static_cast<const X86InstrInfo*>(getTargetMachine().getInstrInfo());
13572  DebugLoc DL = MI->getDebugLoc();
13573  MachineFunction *F = BB->getParent();
13574
13575  assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
13576  assert(MI->getOperand(3).isGlobal() && "This should be a global");
13577
13578  // Get a register mask for the lowered call.
13579  // FIXME: The 32-bit calls have non-standard calling conventions. Use a
13580  // proper register mask.
13581  const uint32_t *RegMask =
13582    getTargetMachine().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
13583  if (Subtarget->is64Bit()) {
13584    MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
13585                                      TII->get(X86::MOV64rm), X86::RDI)
13586    .addReg(X86::RIP)
13587    .addImm(0).addReg(0)
13588    .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
13589                      MI->getOperand(3).getTargetFlags())
13590    .addReg(0);
13591    MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
13592    addDirectMem(MIB, X86::RDI);
13593    MIB.addReg(X86::RAX, RegState::ImplicitDefine).addRegMask(RegMask);
13594  } else if (getTargetMachine().getRelocationModel() != Reloc::PIC_) {
13595    MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
13596                                      TII->get(X86::MOV32rm), X86::EAX)
13597    .addReg(0)
13598    .addImm(0).addReg(0)
13599    .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
13600                      MI->getOperand(3).getTargetFlags())
13601    .addReg(0);
13602    MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
13603    addDirectMem(MIB, X86::EAX);
13604    MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
13605  } else {
13606    MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
13607                                      TII->get(X86::MOV32rm), X86::EAX)
13608    .addReg(TII->getGlobalBaseReg(F))
13609    .addImm(0).addReg(0)
13610    .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
13611                      MI->getOperand(3).getTargetFlags())
13612    .addReg(0);
13613    MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
13614    addDirectMem(MIB, X86::EAX);
13615    MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
13616  }
13617
13618  MI->eraseFromParent(); // The pseudo instruction is gone now.
13619  return BB;
13620}
13621
13622MachineBasicBlock *
13623X86TargetLowering::emitEHSjLjSetJmp(MachineInstr *MI,
13624                                    MachineBasicBlock *MBB) const {
13625  DebugLoc DL = MI->getDebugLoc();
13626  const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
13627
13628  MachineFunction *MF = MBB->getParent();
13629  MachineRegisterInfo &MRI = MF->getRegInfo();
13630
13631  const BasicBlock *BB = MBB->getBasicBlock();
13632  MachineFunction::iterator I = MBB;
13633  ++I;
13634
13635  // Memory Reference
13636  MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
13637  MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
13638
13639  unsigned DstReg;
13640  unsigned MemOpndSlot = 0;
13641
13642  unsigned CurOp = 0;
13643
13644  DstReg = MI->getOperand(CurOp++).getReg();
13645  const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
13646  assert(RC->hasType(MVT::i32) && "Invalid destination!");
13647  unsigned mainDstReg = MRI.createVirtualRegister(RC);
13648  unsigned restoreDstReg = MRI.createVirtualRegister(RC);
13649
13650  MemOpndSlot = CurOp;
13651
13652  MVT PVT = getPointerTy();
13653  assert((PVT == MVT::i64 || PVT == MVT::i32) &&
13654         "Invalid Pointer Size!");
13655
13656  // For v = setjmp(buf), we generate
13657  //
13658  // thisMBB:
13659  //  buf[LabelOffset] = restoreMBB
13660  //  SjLjSetup restoreMBB
13661  //
13662  // mainMBB:
13663  //  v_main = 0
13664  //
13665  // sinkMBB:
13666  //  v = phi(main, restore)
13667  //
13668  // restoreMBB:
13669  //  v_restore = 1
13670
13671  MachineBasicBlock *thisMBB = MBB;
13672  MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
13673  MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
13674  MachineBasicBlock *restoreMBB = MF->CreateMachineBasicBlock(BB);
13675  MF->insert(I, mainMBB);
13676  MF->insert(I, sinkMBB);
13677  MF->push_back(restoreMBB);
13678
13679  MachineInstrBuilder MIB;
13680
13681  // Transfer the remainder of BB and its successor edges to sinkMBB.
13682  sinkMBB->splice(sinkMBB->begin(), MBB,
13683                  llvm::next(MachineBasicBlock::iterator(MI)), MBB->end());
13684  sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
13685
13686  // thisMBB:
13687  unsigned PtrStoreOpc = 0;
13688  unsigned LabelReg = 0;
13689  const int64_t LabelOffset = 1 * PVT.getStoreSize();
13690  Reloc::Model RM = getTargetMachine().getRelocationModel();
13691  bool UseImmLabel = (getTargetMachine().getCodeModel() == CodeModel::Small) &&
13692                     (RM == Reloc::Static || RM == Reloc::DynamicNoPIC);
13693
13694  // Prepare IP either in reg or imm.
13695  if (!UseImmLabel) {
13696    PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mr : X86::MOV32mr;
13697    const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
13698    LabelReg = MRI.createVirtualRegister(PtrRC);
13699    if (Subtarget->is64Bit()) {
13700      MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA64r), LabelReg)
13701              .addReg(X86::RIP)
13702              .addImm(0)
13703              .addReg(0)
13704              .addMBB(restoreMBB)
13705              .addReg(0);
13706    } else {
13707      const X86InstrInfo *XII = static_cast<const X86InstrInfo*>(TII);
13708      MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA32r), LabelReg)
13709              .addReg(XII->getGlobalBaseReg(MF))
13710              .addImm(0)
13711              .addReg(0)
13712              .addMBB(restoreMBB, Subtarget->ClassifyBlockAddressReference())
13713              .addReg(0);
13714    }
13715  } else
13716    PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mi32 : X86::MOV32mi;
13717  // Store IP
13718  MIB = BuildMI(*thisMBB, MI, DL, TII->get(PtrStoreOpc));
13719  for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
13720    if (i == X86::AddrDisp)
13721      MIB.addDisp(MI->getOperand(MemOpndSlot + i), LabelOffset);
13722    else
13723      MIB.addOperand(MI->getOperand(MemOpndSlot + i));
13724  }
13725  if (!UseImmLabel)
13726    MIB.addReg(LabelReg);
13727  else
13728    MIB.addMBB(restoreMBB);
13729  MIB.setMemRefs(MMOBegin, MMOEnd);
13730  // Setup
13731  MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::EH_SjLj_Setup))
13732          .addMBB(restoreMBB);
13733  MIB.addRegMask(RegInfo->getNoPreservedMask());
13734  thisMBB->addSuccessor(mainMBB);
13735  thisMBB->addSuccessor(restoreMBB);
13736
13737  // mainMBB:
13738  //  EAX = 0
13739  BuildMI(mainMBB, DL, TII->get(X86::MOV32r0), mainDstReg);
13740  mainMBB->addSuccessor(sinkMBB);
13741
13742  // sinkMBB:
13743  BuildMI(*sinkMBB, sinkMBB->begin(), DL,
13744          TII->get(X86::PHI), DstReg)
13745    .addReg(mainDstReg).addMBB(mainMBB)
13746    .addReg(restoreDstReg).addMBB(restoreMBB);
13747
13748  // restoreMBB:
13749  BuildMI(restoreMBB, DL, TII->get(X86::MOV32ri), restoreDstReg).addImm(1);
13750  BuildMI(restoreMBB, DL, TII->get(X86::JMP_4)).addMBB(sinkMBB);
13751  restoreMBB->addSuccessor(sinkMBB);
13752
13753  MI->eraseFromParent();
13754  return sinkMBB;
13755}
13756
13757MachineBasicBlock *
13758X86TargetLowering::emitEHSjLjLongJmp(MachineInstr *MI,
13759                                     MachineBasicBlock *MBB) const {
13760  DebugLoc DL = MI->getDebugLoc();
13761  const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
13762
13763  MachineFunction *MF = MBB->getParent();
13764  MachineRegisterInfo &MRI = MF->getRegInfo();
13765
13766  // Memory Reference
13767  MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
13768  MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
13769
13770  MVT PVT = getPointerTy();
13771  assert((PVT == MVT::i64 || PVT == MVT::i32) &&
13772         "Invalid Pointer Size!");
13773
13774  const TargetRegisterClass *RC =
13775    (PVT == MVT::i64) ? &X86::GR64RegClass : &X86::GR32RegClass;
13776  unsigned Tmp = MRI.createVirtualRegister(RC);
13777  // Since FP is only updated here but NOT referenced, it's treated as GPR.
13778  unsigned FP = (PVT == MVT::i64) ? X86::RBP : X86::EBP;
13779  unsigned SP = RegInfo->getStackRegister();
13780
13781  MachineInstrBuilder MIB;
13782
13783  const int64_t LabelOffset = 1 * PVT.getStoreSize();
13784  const int64_t SPOffset = 2 * PVT.getStoreSize();
13785
13786  unsigned PtrLoadOpc = (PVT == MVT::i64) ? X86::MOV64rm : X86::MOV32rm;
13787  unsigned IJmpOpc = (PVT == MVT::i64) ? X86::JMP64r : X86::JMP32r;
13788
13789  // Reload FP
13790  MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), FP);
13791  for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
13792    MIB.addOperand(MI->getOperand(i));
13793  MIB.setMemRefs(MMOBegin, MMOEnd);
13794  // Reload IP
13795  MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), Tmp);
13796  for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
13797    if (i == X86::AddrDisp)
13798      MIB.addDisp(MI->getOperand(i), LabelOffset);
13799    else
13800      MIB.addOperand(MI->getOperand(i));
13801  }
13802  MIB.setMemRefs(MMOBegin, MMOEnd);
13803  // Reload SP
13804  MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), SP);
13805  for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
13806    if (i == X86::AddrDisp)
13807      MIB.addDisp(MI->getOperand(i), SPOffset);
13808    else
13809      MIB.addOperand(MI->getOperand(i));
13810  }
13811  MIB.setMemRefs(MMOBegin, MMOEnd);
13812  // Jump
13813  BuildMI(*MBB, MI, DL, TII->get(IJmpOpc)).addReg(Tmp);
13814
13815  MI->eraseFromParent();
13816  return MBB;
13817}
13818
13819MachineBasicBlock *
13820X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
13821                                               MachineBasicBlock *BB) const {
13822  switch (MI->getOpcode()) {
13823  default: llvm_unreachable("Unexpected instr type to insert");
13824  case X86::TAILJMPd64:
13825  case X86::TAILJMPr64:
13826  case X86::TAILJMPm64:
13827    llvm_unreachable("TAILJMP64 would not be touched here.");
13828  case X86::TCRETURNdi64:
13829  case X86::TCRETURNri64:
13830  case X86::TCRETURNmi64:
13831    return BB;
13832  case X86::WIN_ALLOCA:
13833    return EmitLoweredWinAlloca(MI, BB);
13834  case X86::SEG_ALLOCA_32:
13835    return EmitLoweredSegAlloca(MI, BB, false);
13836  case X86::SEG_ALLOCA_64:
13837    return EmitLoweredSegAlloca(MI, BB, true);
13838  case X86::TLSCall_32:
13839  case X86::TLSCall_64:
13840    return EmitLoweredTLSCall(MI, BB);
13841  case X86::CMOV_GR8:
13842  case X86::CMOV_FR32:
13843  case X86::CMOV_FR64:
13844  case X86::CMOV_V4F32:
13845  case X86::CMOV_V2F64:
13846  case X86::CMOV_V2I64:
13847  case X86::CMOV_V8F32:
13848  case X86::CMOV_V4F64:
13849  case X86::CMOV_V4I64:
13850  case X86::CMOV_GR16:
13851  case X86::CMOV_GR32:
13852  case X86::CMOV_RFP32:
13853  case X86::CMOV_RFP64:
13854  case X86::CMOV_RFP80:
13855    return EmitLoweredSelect(MI, BB);
13856
13857  case X86::FP32_TO_INT16_IN_MEM:
13858  case X86::FP32_TO_INT32_IN_MEM:
13859  case X86::FP32_TO_INT64_IN_MEM:
13860  case X86::FP64_TO_INT16_IN_MEM:
13861  case X86::FP64_TO_INT32_IN_MEM:
13862  case X86::FP64_TO_INT64_IN_MEM:
13863  case X86::FP80_TO_INT16_IN_MEM:
13864  case X86::FP80_TO_INT32_IN_MEM:
13865  case X86::FP80_TO_INT64_IN_MEM: {
13866    const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
13867    DebugLoc DL = MI->getDebugLoc();
13868
13869    // Change the floating point control register to use "round towards zero"
13870    // mode when truncating to an integer value.
13871    MachineFunction *F = BB->getParent();
13872    int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
13873    addFrameReference(BuildMI(*BB, MI, DL,
13874                              TII->get(X86::FNSTCW16m)), CWFrameIdx);
13875
13876    // Load the old value of the high byte of the control word...
13877    unsigned OldCW =
13878      F->getRegInfo().createVirtualRegister(&X86::GR16RegClass);
13879    addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
13880                      CWFrameIdx);
13881
13882    // Set the high part to be round to zero...
13883    addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
13884      .addImm(0xC7F);
13885
13886    // Reload the modified control word now...
13887    addFrameReference(BuildMI(*BB, MI, DL,
13888                              TII->get(X86::FLDCW16m)), CWFrameIdx);
13889
13890    // Restore the memory image of control word to original value
13891    addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
13892      .addReg(OldCW);
13893
13894    // Get the X86 opcode to use.
13895    unsigned Opc;
13896    switch (MI->getOpcode()) {
13897    default: llvm_unreachable("illegal opcode!");
13898    case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
13899    case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
13900    case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
13901    case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
13902    case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
13903    case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
13904    case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
13905    case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
13906    case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
13907    }
13908
13909    X86AddressMode AM;
13910    MachineOperand &Op = MI->getOperand(0);
13911    if (Op.isReg()) {
13912      AM.BaseType = X86AddressMode::RegBase;
13913      AM.Base.Reg = Op.getReg();
13914    } else {
13915      AM.BaseType = X86AddressMode::FrameIndexBase;
13916      AM.Base.FrameIndex = Op.getIndex();
13917    }
13918    Op = MI->getOperand(1);
13919    if (Op.isImm())
13920      AM.Scale = Op.getImm();
13921    Op = MI->getOperand(2);
13922    if (Op.isImm())
13923      AM.IndexReg = Op.getImm();
13924    Op = MI->getOperand(3);
13925    if (Op.isGlobal()) {
13926      AM.GV = Op.getGlobal();
13927    } else {
13928      AM.Disp = Op.getImm();
13929    }
13930    addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
13931                      .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
13932
13933    // Reload the original control word now.
13934    addFrameReference(BuildMI(*BB, MI, DL,
13935                              TII->get(X86::FLDCW16m)), CWFrameIdx);
13936
13937    MI->eraseFromParent();   // The pseudo instruction is gone now.
13938    return BB;
13939  }
13940    // String/text processing lowering.
13941  case X86::PCMPISTRM128REG:
13942  case X86::VPCMPISTRM128REG:
13943  case X86::PCMPISTRM128MEM:
13944  case X86::VPCMPISTRM128MEM:
13945  case X86::PCMPESTRM128REG:
13946  case X86::VPCMPESTRM128REG:
13947  case X86::PCMPESTRM128MEM:
13948  case X86::VPCMPESTRM128MEM:
13949    assert(Subtarget->hasSSE42() &&
13950           "Target must have SSE4.2 or AVX features enabled");
13951    return EmitPCMPSTRM(MI, BB, getTargetMachine().getInstrInfo());
13952
13953  // String/text processing lowering.
13954  case X86::PCMPISTRIREG:
13955  case X86::VPCMPISTRIREG:
13956  case X86::PCMPISTRIMEM:
13957  case X86::VPCMPISTRIMEM:
13958  case X86::PCMPESTRIREG:
13959  case X86::VPCMPESTRIREG:
13960  case X86::PCMPESTRIMEM:
13961  case X86::VPCMPESTRIMEM:
13962    assert(Subtarget->hasSSE42() &&
13963           "Target must have SSE4.2 or AVX features enabled");
13964    return EmitPCMPSTRI(MI, BB, getTargetMachine().getInstrInfo());
13965
13966  // Thread synchronization.
13967  case X86::MONITOR:
13968    return EmitMonitor(MI, BB, getTargetMachine().getInstrInfo(), Subtarget);
13969
13970  // xbegin
13971  case X86::XBEGIN:
13972    return EmitXBegin(MI, BB, getTargetMachine().getInstrInfo());
13973
13974  // Atomic Lowering.
13975  case X86::ATOMAND8:
13976  case X86::ATOMAND16:
13977  case X86::ATOMAND32:
13978  case X86::ATOMAND64:
13979    // Fall through
13980  case X86::ATOMOR8:
13981  case X86::ATOMOR16:
13982  case X86::ATOMOR32:
13983  case X86::ATOMOR64:
13984    // Fall through
13985  case X86::ATOMXOR16:
13986  case X86::ATOMXOR8:
13987  case X86::ATOMXOR32:
13988  case X86::ATOMXOR64:
13989    // Fall through
13990  case X86::ATOMNAND8:
13991  case X86::ATOMNAND16:
13992  case X86::ATOMNAND32:
13993  case X86::ATOMNAND64:
13994    // Fall through
13995  case X86::ATOMMAX8:
13996  case X86::ATOMMAX16:
13997  case X86::ATOMMAX32:
13998  case X86::ATOMMAX64:
13999    // Fall through
14000  case X86::ATOMMIN8:
14001  case X86::ATOMMIN16:
14002  case X86::ATOMMIN32:
14003  case X86::ATOMMIN64:
14004    // Fall through
14005  case X86::ATOMUMAX8:
14006  case X86::ATOMUMAX16:
14007  case X86::ATOMUMAX32:
14008  case X86::ATOMUMAX64:
14009    // Fall through
14010  case X86::ATOMUMIN8:
14011  case X86::ATOMUMIN16:
14012  case X86::ATOMUMIN32:
14013  case X86::ATOMUMIN64:
14014    return EmitAtomicLoadArith(MI, BB);
14015
14016  // This group does 64-bit operations on a 32-bit host.
14017  case X86::ATOMAND6432:
14018  case X86::ATOMOR6432:
14019  case X86::ATOMXOR6432:
14020  case X86::ATOMNAND6432:
14021  case X86::ATOMADD6432:
14022  case X86::ATOMSUB6432:
14023  case X86::ATOMMAX6432:
14024  case X86::ATOMMIN6432:
14025  case X86::ATOMUMAX6432:
14026  case X86::ATOMUMIN6432:
14027  case X86::ATOMSWAP6432:
14028    return EmitAtomicLoadArith6432(MI, BB);
14029
14030  case X86::VASTART_SAVE_XMM_REGS:
14031    return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
14032
14033  case X86::VAARG_64:
14034    return EmitVAARG64WithCustomInserter(MI, BB);
14035
14036  case X86::EH_SjLj_SetJmp32:
14037  case X86::EH_SjLj_SetJmp64:
14038    return emitEHSjLjSetJmp(MI, BB);
14039
14040  case X86::EH_SjLj_LongJmp32:
14041  case X86::EH_SjLj_LongJmp64:
14042    return emitEHSjLjLongJmp(MI, BB);
14043  }
14044}
14045
14046//===----------------------------------------------------------------------===//
14047//                           X86 Optimization Hooks
14048//===----------------------------------------------------------------------===//
14049
14050void X86TargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
14051                                                       APInt &KnownZero,
14052                                                       APInt &KnownOne,
14053                                                       const SelectionDAG &DAG,
14054                                                       unsigned Depth) const {
14055  unsigned BitWidth = KnownZero.getBitWidth();
14056  unsigned Opc = Op.getOpcode();
14057  assert((Opc >= ISD::BUILTIN_OP_END ||
14058          Opc == ISD::INTRINSIC_WO_CHAIN ||
14059          Opc == ISD::INTRINSIC_W_CHAIN ||
14060          Opc == ISD::INTRINSIC_VOID) &&
14061         "Should use MaskedValueIsZero if you don't know whether Op"
14062         " is a target node!");
14063
14064  KnownZero = KnownOne = APInt(BitWidth, 0);   // Don't know anything.
14065  switch (Opc) {
14066  default: break;
14067  case X86ISD::ADD:
14068  case X86ISD::SUB:
14069  case X86ISD::ADC:
14070  case X86ISD::SBB:
14071  case X86ISD::SMUL:
14072  case X86ISD::UMUL:
14073  case X86ISD::INC:
14074  case X86ISD::DEC:
14075  case X86ISD::OR:
14076  case X86ISD::XOR:
14077  case X86ISD::AND:
14078    // These nodes' second result is a boolean.
14079    if (Op.getResNo() == 0)
14080      break;
14081    // Fallthrough
14082  case X86ISD::SETCC:
14083    KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
14084    break;
14085  case ISD::INTRINSIC_WO_CHAIN: {
14086    unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
14087    unsigned NumLoBits = 0;
14088    switch (IntId) {
14089    default: break;
14090    case Intrinsic::x86_sse_movmsk_ps:
14091    case Intrinsic::x86_avx_movmsk_ps_256:
14092    case Intrinsic::x86_sse2_movmsk_pd:
14093    case Intrinsic::x86_avx_movmsk_pd_256:
14094    case Intrinsic::x86_mmx_pmovmskb:
14095    case Intrinsic::x86_sse2_pmovmskb_128:
14096    case Intrinsic::x86_avx2_pmovmskb: {
14097      // High bits of movmskp{s|d}, pmovmskb are known zero.
14098      switch (IntId) {
14099        default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
14100        case Intrinsic::x86_sse_movmsk_ps:      NumLoBits = 4; break;
14101        case Intrinsic::x86_avx_movmsk_ps_256:  NumLoBits = 8; break;
14102        case Intrinsic::x86_sse2_movmsk_pd:     NumLoBits = 2; break;
14103        case Intrinsic::x86_avx_movmsk_pd_256:  NumLoBits = 4; break;
14104        case Intrinsic::x86_mmx_pmovmskb:       NumLoBits = 8; break;
14105        case Intrinsic::x86_sse2_pmovmskb_128:  NumLoBits = 16; break;
14106        case Intrinsic::x86_avx2_pmovmskb:      NumLoBits = 32; break;
14107      }
14108      KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - NumLoBits);
14109      break;
14110    }
14111    }
14112    break;
14113  }
14114  }
14115}
14116
14117unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(SDValue Op,
14118                                                         unsigned Depth) const {
14119  // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
14120  if (Op.getOpcode() == X86ISD::SETCC_CARRY)
14121    return Op.getValueType().getScalarType().getSizeInBits();
14122
14123  // Fallback case.
14124  return 1;
14125}
14126
14127/// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
14128/// node is a GlobalAddress + offset.
14129bool X86TargetLowering::isGAPlusOffset(SDNode *N,
14130                                       const GlobalValue* &GA,
14131                                       int64_t &Offset) const {
14132  if (N->getOpcode() == X86ISD::Wrapper) {
14133    if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
14134      GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
14135      Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
14136      return true;
14137    }
14138  }
14139  return TargetLowering::isGAPlusOffset(N, GA, Offset);
14140}
14141
14142/// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the
14143/// same as extracting the high 128-bit part of 256-bit vector and then
14144/// inserting the result into the low part of a new 256-bit vector
14145static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) {
14146  EVT VT = SVOp->getValueType(0);
14147  unsigned NumElems = VT.getVectorNumElements();
14148
14149  // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
14150  for (unsigned i = 0, j = NumElems/2; i != NumElems/2; ++i, ++j)
14151    if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
14152        SVOp->getMaskElt(j) >= 0)
14153      return false;
14154
14155  return true;
14156}
14157
14158/// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the
14159/// same as extracting the low 128-bit part of 256-bit vector and then
14160/// inserting the result into the high part of a new 256-bit vector
14161static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) {
14162  EVT VT = SVOp->getValueType(0);
14163  unsigned NumElems = VT.getVectorNumElements();
14164
14165  // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
14166  for (unsigned i = NumElems/2, j = 0; i != NumElems; ++i, ++j)
14167    if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
14168        SVOp->getMaskElt(j) >= 0)
14169      return false;
14170
14171  return true;
14172}
14173
14174/// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
14175static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
14176                                        TargetLowering::DAGCombinerInfo &DCI,
14177                                        const X86Subtarget* Subtarget) {
14178  DebugLoc dl = N->getDebugLoc();
14179  ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
14180  SDValue V1 = SVOp->getOperand(0);
14181  SDValue V2 = SVOp->getOperand(1);
14182  EVT VT = SVOp->getValueType(0);
14183  unsigned NumElems = VT.getVectorNumElements();
14184
14185  if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
14186      V2.getOpcode() == ISD::CONCAT_VECTORS) {
14187    //
14188    //                   0,0,0,...
14189    //                      |
14190    //    V      UNDEF    BUILD_VECTOR    UNDEF
14191    //     \      /           \           /
14192    //  CONCAT_VECTOR         CONCAT_VECTOR
14193    //         \                  /
14194    //          \                /
14195    //          RESULT: V + zero extended
14196    //
14197    if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
14198        V2.getOperand(1).getOpcode() != ISD::UNDEF ||
14199        V1.getOperand(1).getOpcode() != ISD::UNDEF)
14200      return SDValue();
14201
14202    if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
14203      return SDValue();
14204
14205    // To match the shuffle mask, the first half of the mask should
14206    // be exactly the first vector, and all the rest a splat with the
14207    // first element of the second one.
14208    for (unsigned i = 0; i != NumElems/2; ++i)
14209      if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
14210          !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
14211        return SDValue();
14212
14213    // If V1 is coming from a vector load then just fold to a VZEXT_LOAD.
14214    if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(V1.getOperand(0))) {
14215      if (Ld->hasNUsesOfValue(1, 0)) {
14216        SDVTList Tys = DAG.getVTList(MVT::v4i64, MVT::Other);
14217        SDValue Ops[] = { Ld->getChain(), Ld->getBasePtr() };
14218        SDValue ResNode =
14219          DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops, 2,
14220                                  Ld->getMemoryVT(),
14221                                  Ld->getPointerInfo(),
14222                                  Ld->getAlignment(),
14223                                  false/*isVolatile*/, true/*ReadMem*/,
14224                                  false/*WriteMem*/);
14225
14226        // Make sure the newly-created LOAD is in the same position as Ld in
14227        // terms of dependency. We create a TokenFactor for Ld and ResNode,
14228        // and update uses of Ld's output chain to use the TokenFactor.
14229        if (Ld->hasAnyUseOfValue(1)) {
14230          SDValue NewChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
14231                             SDValue(Ld, 1), SDValue(ResNode.getNode(), 1));
14232          DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), NewChain);
14233          DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(Ld, 1),
14234                                 SDValue(ResNode.getNode(), 1));
14235        }
14236
14237        return DAG.getNode(ISD::BITCAST, dl, VT, ResNode);
14238      }
14239    }
14240
14241    // Emit a zeroed vector and insert the desired subvector on its
14242    // first half.
14243    SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
14244    SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0), 0, DAG, dl);
14245    return DCI.CombineTo(N, InsV);
14246  }
14247
14248  //===--------------------------------------------------------------------===//
14249  // Combine some shuffles into subvector extracts and inserts:
14250  //
14251
14252  // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
14253  if (isShuffleHigh128VectorInsertLow(SVOp)) {
14254    SDValue V = Extract128BitVector(V1, NumElems/2, DAG, dl);
14255    SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, 0, DAG, dl);
14256    return DCI.CombineTo(N, InsV);
14257  }
14258
14259  // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
14260  if (isShuffleLow128VectorInsertHigh(SVOp)) {
14261    SDValue V = Extract128BitVector(V1, 0, DAG, dl);
14262    SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, NumElems/2, DAG, dl);
14263    return DCI.CombineTo(N, InsV);
14264  }
14265
14266  return SDValue();
14267}
14268
14269/// PerformShuffleCombine - Performs several different shuffle combines.
14270static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
14271                                     TargetLowering::DAGCombinerInfo &DCI,
14272                                     const X86Subtarget *Subtarget) {
14273  DebugLoc dl = N->getDebugLoc();
14274  EVT VT = N->getValueType(0);
14275
14276  // Don't create instructions with illegal types after legalize types has run.
14277  const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14278  if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
14279    return SDValue();
14280
14281  // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
14282  if (Subtarget->hasAVX() && VT.is256BitVector() &&
14283      N->getOpcode() == ISD::VECTOR_SHUFFLE)
14284    return PerformShuffleCombine256(N, DAG, DCI, Subtarget);
14285
14286  // Only handle 128 wide vector from here on.
14287  if (!VT.is128BitVector())
14288    return SDValue();
14289
14290  // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
14291  // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
14292  // consecutive, non-overlapping, and in the right order.
14293  SmallVector<SDValue, 16> Elts;
14294  for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
14295    Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
14296
14297  return EltsFromConsecutiveLoads(VT, Elts, dl, DAG);
14298}
14299
14300
14301/// PerformTruncateCombine - Converts truncate operation to
14302/// a sequence of vector shuffle operations.
14303/// It is possible when we truncate 256-bit vector to 128-bit vector
14304static SDValue PerformTruncateCombine(SDNode *N, SelectionDAG &DAG,
14305                                      TargetLowering::DAGCombinerInfo &DCI,
14306                                      const X86Subtarget *Subtarget)  {
14307  if (!DCI.isBeforeLegalizeOps())
14308    return SDValue();
14309
14310  if (!Subtarget->hasAVX())
14311    return SDValue();
14312
14313  EVT VT = N->getValueType(0);
14314  SDValue Op = N->getOperand(0);
14315  EVT OpVT = Op.getValueType();
14316  DebugLoc dl = N->getDebugLoc();
14317
14318  if ((VT == MVT::v4i32) && (OpVT == MVT::v4i64)) {
14319
14320    if (Subtarget->hasAVX2()) {
14321      // AVX2: v4i64 -> v4i32
14322
14323      // VPERMD
14324      static const int ShufMask[] = {0, 2, 4, 6, -1, -1, -1, -1};
14325
14326      Op = DAG.getNode(ISD::BITCAST, dl, MVT::v8i32, Op);
14327      Op = DAG.getVectorShuffle(MVT::v8i32, dl, Op, DAG.getUNDEF(MVT::v8i32),
14328                                ShufMask);
14329
14330      return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, Op,
14331                         DAG.getIntPtrConstant(0));
14332    }
14333
14334    // AVX: v4i64 -> v4i32
14335    SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v2i64, Op,
14336                               DAG.getIntPtrConstant(0));
14337
14338    SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v2i64, Op,
14339                               DAG.getIntPtrConstant(2));
14340
14341    OpLo = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, OpLo);
14342    OpHi = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, OpHi);
14343
14344    // PSHUFD
14345    static const int ShufMask1[] = {0, 2, 0, 0};
14346
14347    SDValue Undef = DAG.getUNDEF(VT);
14348    OpLo = DAG.getVectorShuffle(VT, dl, OpLo, Undef, ShufMask1);
14349    OpHi = DAG.getVectorShuffle(VT, dl, OpHi, Undef, ShufMask1);
14350
14351    // MOVLHPS
14352    static const int ShufMask2[] = {0, 1, 4, 5};
14353
14354    return DAG.getVectorShuffle(VT, dl, OpLo, OpHi, ShufMask2);
14355  }
14356
14357  if ((VT == MVT::v8i16) && (OpVT == MVT::v8i32)) {
14358
14359    if (Subtarget->hasAVX2()) {
14360      // AVX2: v8i32 -> v8i16
14361
14362      Op = DAG.getNode(ISD::BITCAST, dl, MVT::v32i8, Op);
14363
14364      // PSHUFB
14365      SmallVector<SDValue,32> pshufbMask;
14366      for (unsigned i = 0; i < 2; ++i) {
14367        pshufbMask.push_back(DAG.getConstant(0x0, MVT::i8));
14368        pshufbMask.push_back(DAG.getConstant(0x1, MVT::i8));
14369        pshufbMask.push_back(DAG.getConstant(0x4, MVT::i8));
14370        pshufbMask.push_back(DAG.getConstant(0x5, MVT::i8));
14371        pshufbMask.push_back(DAG.getConstant(0x8, MVT::i8));
14372        pshufbMask.push_back(DAG.getConstant(0x9, MVT::i8));
14373        pshufbMask.push_back(DAG.getConstant(0xc, MVT::i8));
14374        pshufbMask.push_back(DAG.getConstant(0xd, MVT::i8));
14375        for (unsigned j = 0; j < 8; ++j)
14376          pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
14377      }
14378      SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v32i8,
14379                               &pshufbMask[0], 32);
14380      Op = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v32i8, Op, BV);
14381
14382      Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4i64, Op);
14383
14384      static const int ShufMask[] = {0,  2,  -1,  -1};
14385      Op = DAG.getVectorShuffle(MVT::v4i64, dl,  Op, DAG.getUNDEF(MVT::v4i64),
14386                                &ShufMask[0]);
14387
14388      Op = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v2i64, Op,
14389                       DAG.getIntPtrConstant(0));
14390
14391      return DAG.getNode(ISD::BITCAST, dl, VT, Op);
14392    }
14393
14394    SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i32, Op,
14395                               DAG.getIntPtrConstant(0));
14396
14397    SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i32, Op,
14398                               DAG.getIntPtrConstant(4));
14399
14400    OpLo = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpLo);
14401    OpHi = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpHi);
14402
14403    // PSHUFB
14404    static const int ShufMask1[] = {0,  1,  4,  5,  8,  9, 12, 13,
14405                                   -1, -1, -1, -1, -1, -1, -1, -1};
14406
14407    SDValue Undef = DAG.getUNDEF(MVT::v16i8);
14408    OpLo = DAG.getVectorShuffle(MVT::v16i8, dl, OpLo, Undef, ShufMask1);
14409    OpHi = DAG.getVectorShuffle(MVT::v16i8, dl, OpHi, Undef, ShufMask1);
14410
14411    OpLo = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, OpLo);
14412    OpHi = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, OpHi);
14413
14414    // MOVLHPS
14415    static const int ShufMask2[] = {0, 1, 4, 5};
14416
14417    SDValue res = DAG.getVectorShuffle(MVT::v4i32, dl, OpLo, OpHi, ShufMask2);
14418    return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, res);
14419  }
14420
14421  return SDValue();
14422}
14423
14424/// XFormVExtractWithShuffleIntoLoad - Check if a vector extract from a target
14425/// specific shuffle of a load can be folded into a single element load.
14426/// Similar handling for VECTOR_SHUFFLE is performed by DAGCombiner, but
14427/// shuffles have been customed lowered so we need to handle those here.
14428static SDValue XFormVExtractWithShuffleIntoLoad(SDNode *N, SelectionDAG &DAG,
14429                                         TargetLowering::DAGCombinerInfo &DCI) {
14430  if (DCI.isBeforeLegalizeOps())
14431    return SDValue();
14432
14433  SDValue InVec = N->getOperand(0);
14434  SDValue EltNo = N->getOperand(1);
14435
14436  if (!isa<ConstantSDNode>(EltNo))
14437    return SDValue();
14438
14439  EVT VT = InVec.getValueType();
14440
14441  bool HasShuffleIntoBitcast = false;
14442  if (InVec.getOpcode() == ISD::BITCAST) {
14443    // Don't duplicate a load with other uses.
14444    if (!InVec.hasOneUse())
14445      return SDValue();
14446    EVT BCVT = InVec.getOperand(0).getValueType();
14447    if (BCVT.getVectorNumElements() != VT.getVectorNumElements())
14448      return SDValue();
14449    InVec = InVec.getOperand(0);
14450    HasShuffleIntoBitcast = true;
14451  }
14452
14453  if (!isTargetShuffle(InVec.getOpcode()))
14454    return SDValue();
14455
14456  // Don't duplicate a load with other uses.
14457  if (!InVec.hasOneUse())
14458    return SDValue();
14459
14460  SmallVector<int, 16> ShuffleMask;
14461  bool UnaryShuffle;
14462  if (!getTargetShuffleMask(InVec.getNode(), VT.getSimpleVT(), ShuffleMask,
14463                            UnaryShuffle))
14464    return SDValue();
14465
14466  // Select the input vector, guarding against out of range extract vector.
14467  unsigned NumElems = VT.getVectorNumElements();
14468  int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
14469  int Idx = (Elt > (int)NumElems) ? -1 : ShuffleMask[Elt];
14470  SDValue LdNode = (Idx < (int)NumElems) ? InVec.getOperand(0)
14471                                         : InVec.getOperand(1);
14472
14473  // If inputs to shuffle are the same for both ops, then allow 2 uses
14474  unsigned AllowedUses = InVec.getOperand(0) == InVec.getOperand(1) ? 2 : 1;
14475
14476  if (LdNode.getOpcode() == ISD::BITCAST) {
14477    // Don't duplicate a load with other uses.
14478    if (!LdNode.getNode()->hasNUsesOfValue(AllowedUses, 0))
14479      return SDValue();
14480
14481    AllowedUses = 1; // only allow 1 load use if we have a bitcast
14482    LdNode = LdNode.getOperand(0);
14483  }
14484
14485  if (!ISD::isNormalLoad(LdNode.getNode()))
14486    return SDValue();
14487
14488  LoadSDNode *LN0 = cast<LoadSDNode>(LdNode);
14489
14490  if (!LN0 ||!LN0->hasNUsesOfValue(AllowedUses, 0) || LN0->isVolatile())
14491    return SDValue();
14492
14493  if (HasShuffleIntoBitcast) {
14494    // If there's a bitcast before the shuffle, check if the load type and
14495    // alignment is valid.
14496    unsigned Align = LN0->getAlignment();
14497    const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14498    unsigned NewAlign = TLI.getDataLayout()->
14499      getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
14500
14501    if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VT))
14502      return SDValue();
14503  }
14504
14505  // All checks match so transform back to vector_shuffle so that DAG combiner
14506  // can finish the job
14507  DebugLoc dl = N->getDebugLoc();
14508
14509  // Create shuffle node taking into account the case that its a unary shuffle
14510  SDValue Shuffle = (UnaryShuffle) ? DAG.getUNDEF(VT) : InVec.getOperand(1);
14511  Shuffle = DAG.getVectorShuffle(InVec.getValueType(), dl,
14512                                 InVec.getOperand(0), Shuffle,
14513                                 &ShuffleMask[0]);
14514  Shuffle = DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
14515  return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0), Shuffle,
14516                     EltNo);
14517}
14518
14519/// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
14520/// generation and convert it from being a bunch of shuffles and extracts
14521/// to a simple store and scalar loads to extract the elements.
14522static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
14523                                         TargetLowering::DAGCombinerInfo &DCI) {
14524  SDValue NewOp = XFormVExtractWithShuffleIntoLoad(N, DAG, DCI);
14525  if (NewOp.getNode())
14526    return NewOp;
14527
14528  SDValue InputVector = N->getOperand(0);
14529  // Detect whether we are trying to convert from mmx to i32 and the bitcast
14530  // from mmx to v2i32 has a single usage.
14531  if (InputVector.getNode()->getOpcode() == llvm::ISD::BITCAST &&
14532      InputVector.getNode()->getOperand(0).getValueType() == MVT::x86mmx &&
14533      InputVector.hasOneUse() && N->getValueType(0) == MVT::i32)
14534    return DAG.getNode(X86ISD::MMX_MOVD2W, InputVector.getDebugLoc(),
14535                       N->getValueType(0),
14536                       InputVector.getNode()->getOperand(0));
14537
14538  // Only operate on vectors of 4 elements, where the alternative shuffling
14539  // gets to be more expensive.
14540  if (InputVector.getValueType() != MVT::v4i32)
14541    return SDValue();
14542
14543  // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
14544  // single use which is a sign-extend or zero-extend, and all elements are
14545  // used.
14546  SmallVector<SDNode *, 4> Uses;
14547  unsigned ExtractedElements = 0;
14548  for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
14549       UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
14550    if (UI.getUse().getResNo() != InputVector.getResNo())
14551      return SDValue();
14552
14553    SDNode *Extract = *UI;
14554    if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
14555      return SDValue();
14556
14557    if (Extract->getValueType(0) != MVT::i32)
14558      return SDValue();
14559    if (!Extract->hasOneUse())
14560      return SDValue();
14561    if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
14562        Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
14563      return SDValue();
14564    if (!isa<ConstantSDNode>(Extract->getOperand(1)))
14565      return SDValue();
14566
14567    // Record which element was extracted.
14568    ExtractedElements |=
14569      1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
14570
14571    Uses.push_back(Extract);
14572  }
14573
14574  // If not all the elements were used, this may not be worthwhile.
14575  if (ExtractedElements != 15)
14576    return SDValue();
14577
14578  // Ok, we've now decided to do the transformation.
14579  DebugLoc dl = InputVector.getDebugLoc();
14580
14581  // Store the value to a temporary stack slot.
14582  SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
14583  SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
14584                            MachinePointerInfo(), false, false, 0);
14585
14586  // Replace each use (extract) with a load of the appropriate element.
14587  for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
14588       UE = Uses.end(); UI != UE; ++UI) {
14589    SDNode *Extract = *UI;
14590
14591    // cOMpute the element's address.
14592    SDValue Idx = Extract->getOperand(1);
14593    unsigned EltSize =
14594        InputVector.getValueType().getVectorElementType().getSizeInBits()/8;
14595    uint64_t Offset = EltSize * cast<ConstantSDNode>(Idx)->getZExtValue();
14596    const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14597    SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy());
14598
14599    SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(),
14600                                     StackPtr, OffsetVal);
14601
14602    // Load the scalar.
14603    SDValue LoadScalar = DAG.getLoad(Extract->getValueType(0), dl, Ch,
14604                                     ScalarAddr, MachinePointerInfo(),
14605                                     false, false, false, 0);
14606
14607    // Replace the exact with the load.
14608    DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), LoadScalar);
14609  }
14610
14611  // The replacement was made in place; don't return anything.
14612  return SDValue();
14613}
14614
14615/// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
14616/// nodes.
14617static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
14618                                    TargetLowering::DAGCombinerInfo &DCI,
14619                                    const X86Subtarget *Subtarget) {
14620  DebugLoc DL = N->getDebugLoc();
14621  SDValue Cond = N->getOperand(0);
14622  // Get the LHS/RHS of the select.
14623  SDValue LHS = N->getOperand(1);
14624  SDValue RHS = N->getOperand(2);
14625  EVT VT = LHS.getValueType();
14626
14627  // If we have SSE[12] support, try to form min/max nodes. SSE min/max
14628  // instructions match the semantics of the common C idiom x<y?x:y but not
14629  // x<=y?x:y, because of how they handle negative zero (which can be
14630  // ignored in unsafe-math mode).
14631  if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
14632      VT != MVT::f80 && DAG.getTargetLoweringInfo().isTypeLegal(VT) &&
14633      (Subtarget->hasSSE2() ||
14634       (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
14635    ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
14636
14637    unsigned Opcode = 0;
14638    // Check for x CC y ? x : y.
14639    if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
14640        DAG.isEqualTo(RHS, Cond.getOperand(1))) {
14641      switch (CC) {
14642      default: break;
14643      case ISD::SETULT:
14644        // Converting this to a min would handle NaNs incorrectly, and swapping
14645        // the operands would cause it to handle comparisons between positive
14646        // and negative zero incorrectly.
14647        if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
14648          if (!DAG.getTarget().Options.UnsafeFPMath &&
14649              !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
14650            break;
14651          std::swap(LHS, RHS);
14652        }
14653        Opcode = X86ISD::FMIN;
14654        break;
14655      case ISD::SETOLE:
14656        // Converting this to a min would handle comparisons between positive
14657        // and negative zero incorrectly.
14658        if (!DAG.getTarget().Options.UnsafeFPMath &&
14659            !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
14660          break;
14661        Opcode = X86ISD::FMIN;
14662        break;
14663      case ISD::SETULE:
14664        // Converting this to a min would handle both negative zeros and NaNs
14665        // incorrectly, but we can swap the operands to fix both.
14666        std::swap(LHS, RHS);
14667      case ISD::SETOLT:
14668      case ISD::SETLT:
14669      case ISD::SETLE:
14670        Opcode = X86ISD::FMIN;
14671        break;
14672
14673      case ISD::SETOGE:
14674        // Converting this to a max would handle comparisons between positive
14675        // and negative zero incorrectly.
14676        if (!DAG.getTarget().Options.UnsafeFPMath &&
14677            !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
14678          break;
14679        Opcode = X86ISD::FMAX;
14680        break;
14681      case ISD::SETUGT:
14682        // Converting this to a max would handle NaNs incorrectly, and swapping
14683        // the operands would cause it to handle comparisons between positive
14684        // and negative zero incorrectly.
14685        if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
14686          if (!DAG.getTarget().Options.UnsafeFPMath &&
14687              !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
14688            break;
14689          std::swap(LHS, RHS);
14690        }
14691        Opcode = X86ISD::FMAX;
14692        break;
14693      case ISD::SETUGE:
14694        // Converting this to a max would handle both negative zeros and NaNs
14695        // incorrectly, but we can swap the operands to fix both.
14696        std::swap(LHS, RHS);
14697      case ISD::SETOGT:
14698      case ISD::SETGT:
14699      case ISD::SETGE:
14700        Opcode = X86ISD::FMAX;
14701        break;
14702      }
14703    // Check for x CC y ? y : x -- a min/max with reversed arms.
14704    } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
14705               DAG.isEqualTo(RHS, Cond.getOperand(0))) {
14706      switch (CC) {
14707      default: break;
14708      case ISD::SETOGE:
14709        // Converting this to a min would handle comparisons between positive
14710        // and negative zero incorrectly, and swapping the operands would
14711        // cause it to handle NaNs incorrectly.
14712        if (!DAG.getTarget().Options.UnsafeFPMath &&
14713            !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
14714          if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
14715            break;
14716          std::swap(LHS, RHS);
14717        }
14718        Opcode = X86ISD::FMIN;
14719        break;
14720      case ISD::SETUGT:
14721        // Converting this to a min would handle NaNs incorrectly.
14722        if (!DAG.getTarget().Options.UnsafeFPMath &&
14723            (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
14724          break;
14725        Opcode = X86ISD::FMIN;
14726        break;
14727      case ISD::SETUGE:
14728        // Converting this to a min would handle both negative zeros and NaNs
14729        // incorrectly, but we can swap the operands to fix both.
14730        std::swap(LHS, RHS);
14731      case ISD::SETOGT:
14732      case ISD::SETGT:
14733      case ISD::SETGE:
14734        Opcode = X86ISD::FMIN;
14735        break;
14736
14737      case ISD::SETULT:
14738        // Converting this to a max would handle NaNs incorrectly.
14739        if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
14740          break;
14741        Opcode = X86ISD::FMAX;
14742        break;
14743      case ISD::SETOLE:
14744        // Converting this to a max would handle comparisons between positive
14745        // and negative zero incorrectly, and swapping the operands would
14746        // cause it to handle NaNs incorrectly.
14747        if (!DAG.getTarget().Options.UnsafeFPMath &&
14748            !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
14749          if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
14750            break;
14751          std::swap(LHS, RHS);
14752        }
14753        Opcode = X86ISD::FMAX;
14754        break;
14755      case ISD::SETULE:
14756        // Converting this to a max would handle both negative zeros and NaNs
14757        // incorrectly, but we can swap the operands to fix both.
14758        std::swap(LHS, RHS);
14759      case ISD::SETOLT:
14760      case ISD::SETLT:
14761      case ISD::SETLE:
14762        Opcode = X86ISD::FMAX;
14763        break;
14764      }
14765    }
14766
14767    if (Opcode)
14768      return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
14769  }
14770
14771  // If this is a select between two integer constants, try to do some
14772  // optimizations.
14773  if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
14774    if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
14775      // Don't do this for crazy integer types.
14776      if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
14777        // If this is efficiently invertible, canonicalize the LHSC/RHSC values
14778        // so that TrueC (the true value) is larger than FalseC.
14779        bool NeedsCondInvert = false;
14780
14781        if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
14782            // Efficiently invertible.
14783            (Cond.getOpcode() == ISD::SETCC ||  // setcc -> invertible.
14784             (Cond.getOpcode() == ISD::XOR &&   // xor(X, C) -> invertible.
14785              isa<ConstantSDNode>(Cond.getOperand(1))))) {
14786          NeedsCondInvert = true;
14787          std::swap(TrueC, FalseC);
14788        }
14789
14790        // Optimize C ? 8 : 0 -> zext(C) << 3.  Likewise for any pow2/0.
14791        if (FalseC->getAPIntValue() == 0 &&
14792            TrueC->getAPIntValue().isPowerOf2()) {
14793          if (NeedsCondInvert) // Invert the condition if needed.
14794            Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
14795                               DAG.getConstant(1, Cond.getValueType()));
14796
14797          // Zero extend the condition if needed.
14798          Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
14799
14800          unsigned ShAmt = TrueC->getAPIntValue().logBase2();
14801          return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
14802                             DAG.getConstant(ShAmt, MVT::i8));
14803        }
14804
14805        // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
14806        if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
14807          if (NeedsCondInvert) // Invert the condition if needed.
14808            Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
14809                               DAG.getConstant(1, Cond.getValueType()));
14810
14811          // Zero extend the condition if needed.
14812          Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
14813                             FalseC->getValueType(0), Cond);
14814          return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
14815                             SDValue(FalseC, 0));
14816        }
14817
14818        // Optimize cases that will turn into an LEA instruction.  This requires
14819        // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
14820        if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
14821          uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
14822          if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
14823
14824          bool isFastMultiplier = false;
14825          if (Diff < 10) {
14826            switch ((unsigned char)Diff) {
14827              default: break;
14828              case 1:  // result = add base, cond
14829              case 2:  // result = lea base(    , cond*2)
14830              case 3:  // result = lea base(cond, cond*2)
14831              case 4:  // result = lea base(    , cond*4)
14832              case 5:  // result = lea base(cond, cond*4)
14833              case 8:  // result = lea base(    , cond*8)
14834              case 9:  // result = lea base(cond, cond*8)
14835                isFastMultiplier = true;
14836                break;
14837            }
14838          }
14839
14840          if (isFastMultiplier) {
14841            APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
14842            if (NeedsCondInvert) // Invert the condition if needed.
14843              Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
14844                                 DAG.getConstant(1, Cond.getValueType()));
14845
14846            // Zero extend the condition if needed.
14847            Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
14848                               Cond);
14849            // Scale the condition by the difference.
14850            if (Diff != 1)
14851              Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
14852                                 DAG.getConstant(Diff, Cond.getValueType()));
14853
14854            // Add the base if non-zero.
14855            if (FalseC->getAPIntValue() != 0)
14856              Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
14857                                 SDValue(FalseC, 0));
14858            return Cond;
14859          }
14860        }
14861      }
14862  }
14863
14864  // Canonicalize max and min:
14865  // (x > y) ? x : y -> (x >= y) ? x : y
14866  // (x < y) ? x : y -> (x <= y) ? x : y
14867  // This allows use of COND_S / COND_NS (see TranslateX86CC) which eliminates
14868  // the need for an extra compare
14869  // against zero. e.g.
14870  // (x - y) > 0 : (x - y) ? 0 -> (x - y) >= 0 : (x - y) ? 0
14871  // subl   %esi, %edi
14872  // testl  %edi, %edi
14873  // movl   $0, %eax
14874  // cmovgl %edi, %eax
14875  // =>
14876  // xorl   %eax, %eax
14877  // subl   %esi, $edi
14878  // cmovsl %eax, %edi
14879  if (N->getOpcode() == ISD::SELECT && Cond.getOpcode() == ISD::SETCC &&
14880      DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
14881      DAG.isEqualTo(RHS, Cond.getOperand(1))) {
14882    ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
14883    switch (CC) {
14884    default: break;
14885    case ISD::SETLT:
14886    case ISD::SETGT: {
14887      ISD::CondCode NewCC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGE;
14888      Cond = DAG.getSetCC(Cond.getDebugLoc(), Cond.getValueType(),
14889                          Cond.getOperand(0), Cond.getOperand(1), NewCC);
14890      return DAG.getNode(ISD::SELECT, DL, VT, Cond, LHS, RHS);
14891    }
14892    }
14893  }
14894
14895  // If we know that this node is legal then we know that it is going to be
14896  // matched by one of the SSE/AVX BLEND instructions. These instructions only
14897  // depend on the highest bit in each word. Try to use SimplifyDemandedBits
14898  // to simplify previous instructions.
14899  const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14900  if (N->getOpcode() == ISD::VSELECT && DCI.isBeforeLegalizeOps() &&
14901      !DCI.isBeforeLegalize() && TLI.isOperationLegal(ISD::VSELECT, VT)) {
14902    unsigned BitWidth = Cond.getValueType().getScalarType().getSizeInBits();
14903
14904    // Don't optimize vector selects that map to mask-registers.
14905    if (BitWidth == 1)
14906      return SDValue();
14907
14908    assert(BitWidth >= 8 && BitWidth <= 64 && "Invalid mask size");
14909    APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 1);
14910
14911    APInt KnownZero, KnownOne;
14912    TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
14913                                          DCI.isBeforeLegalizeOps());
14914    if (TLO.ShrinkDemandedConstant(Cond, DemandedMask) ||
14915        TLI.SimplifyDemandedBits(Cond, DemandedMask, KnownZero, KnownOne, TLO))
14916      DCI.CommitTargetLoweringOpt(TLO);
14917  }
14918
14919  return SDValue();
14920}
14921
14922// Check whether a boolean test is testing a boolean value generated by
14923// X86ISD::SETCC. If so, return the operand of that SETCC and proper condition
14924// code.
14925//
14926// Simplify the following patterns:
14927// (Op (CMP (SETCC Cond EFLAGS) 1) EQ) or
14928// (Op (CMP (SETCC Cond EFLAGS) 0) NEQ)
14929// to (Op EFLAGS Cond)
14930//
14931// (Op (CMP (SETCC Cond EFLAGS) 0) EQ) or
14932// (Op (CMP (SETCC Cond EFLAGS) 1) NEQ)
14933// to (Op EFLAGS !Cond)
14934//
14935// where Op could be BRCOND or CMOV.
14936//
14937static SDValue checkBoolTestSetCCCombine(SDValue Cmp, X86::CondCode &CC) {
14938  // Quit if not CMP and SUB with its value result used.
14939  if (Cmp.getOpcode() != X86ISD::CMP &&
14940      (Cmp.getOpcode() != X86ISD::SUB || Cmp.getNode()->hasAnyUseOfValue(0)))
14941      return SDValue();
14942
14943  // Quit if not used as a boolean value.
14944  if (CC != X86::COND_E && CC != X86::COND_NE)
14945    return SDValue();
14946
14947  // Check CMP operands. One of them should be 0 or 1 and the other should be
14948  // an SetCC or extended from it.
14949  SDValue Op1 = Cmp.getOperand(0);
14950  SDValue Op2 = Cmp.getOperand(1);
14951
14952  SDValue SetCC;
14953  const ConstantSDNode* C = 0;
14954  bool needOppositeCond = (CC == X86::COND_E);
14955
14956  if ((C = dyn_cast<ConstantSDNode>(Op1)))
14957    SetCC = Op2;
14958  else if ((C = dyn_cast<ConstantSDNode>(Op2)))
14959    SetCC = Op1;
14960  else // Quit if all operands are not constants.
14961    return SDValue();
14962
14963  if (C->getZExtValue() == 1)
14964    needOppositeCond = !needOppositeCond;
14965  else if (C->getZExtValue() != 0)
14966    // Quit if the constant is neither 0 or 1.
14967    return SDValue();
14968
14969  // Skip 'zext' node.
14970  if (SetCC.getOpcode() == ISD::ZERO_EXTEND)
14971    SetCC = SetCC.getOperand(0);
14972
14973  switch (SetCC.getOpcode()) {
14974  case X86ISD::SETCC:
14975    // Set the condition code or opposite one if necessary.
14976    CC = X86::CondCode(SetCC.getConstantOperandVal(0));
14977    if (needOppositeCond)
14978      CC = X86::GetOppositeBranchCondition(CC);
14979    return SetCC.getOperand(1);
14980  case X86ISD::CMOV: {
14981    // Check whether false/true value has canonical one, i.e. 0 or 1.
14982    ConstantSDNode *FVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(0));
14983    ConstantSDNode *TVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(1));
14984    // Quit if true value is not a constant.
14985    if (!TVal)
14986      return SDValue();
14987    // Quit if false value is not a constant.
14988    if (!FVal) {
14989      // A special case for rdrand, where 0 is set if false cond is found.
14990      SDValue Op = SetCC.getOperand(0);
14991      if (Op.getOpcode() != X86ISD::RDRAND)
14992        return SDValue();
14993    }
14994    // Quit if false value is not the constant 0 or 1.
14995    bool FValIsFalse = true;
14996    if (FVal && FVal->getZExtValue() != 0) {
14997      if (FVal->getZExtValue() != 1)
14998        return SDValue();
14999      // If FVal is 1, opposite cond is needed.
15000      needOppositeCond = !needOppositeCond;
15001      FValIsFalse = false;
15002    }
15003    // Quit if TVal is not the constant opposite of FVal.
15004    if (FValIsFalse && TVal->getZExtValue() != 1)
15005      return SDValue();
15006    if (!FValIsFalse && TVal->getZExtValue() != 0)
15007      return SDValue();
15008    CC = X86::CondCode(SetCC.getConstantOperandVal(2));
15009    if (needOppositeCond)
15010      CC = X86::GetOppositeBranchCondition(CC);
15011    return SetCC.getOperand(3);
15012  }
15013  }
15014
15015  return SDValue();
15016}
15017
15018/// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
15019static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
15020                                  TargetLowering::DAGCombinerInfo &DCI,
15021                                  const X86Subtarget *Subtarget) {
15022  DebugLoc DL = N->getDebugLoc();
15023
15024  // If the flag operand isn't dead, don't touch this CMOV.
15025  if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
15026    return SDValue();
15027
15028  SDValue FalseOp = N->getOperand(0);
15029  SDValue TrueOp = N->getOperand(1);
15030  X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
15031  SDValue Cond = N->getOperand(3);
15032
15033  if (CC == X86::COND_E || CC == X86::COND_NE) {
15034    switch (Cond.getOpcode()) {
15035    default: break;
15036    case X86ISD::BSR:
15037    case X86ISD::BSF:
15038      // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
15039      if (DAG.isKnownNeverZero(Cond.getOperand(0)))
15040        return (CC == X86::COND_E) ? FalseOp : TrueOp;
15041    }
15042  }
15043
15044  SDValue Flags;
15045
15046  Flags = checkBoolTestSetCCCombine(Cond, CC);
15047  if (Flags.getNode() &&
15048      // Extra check as FCMOV only supports a subset of X86 cond.
15049      (FalseOp.getValueType() != MVT::f80 || hasFPCMov(CC))) {
15050    SDValue Ops[] = { FalseOp, TrueOp,
15051                      DAG.getConstant(CC, MVT::i8), Flags };
15052    return DAG.getNode(X86ISD::CMOV, DL, N->getVTList(),
15053                       Ops, array_lengthof(Ops));
15054  }
15055
15056  // If this is a select between two integer constants, try to do some
15057  // optimizations.  Note that the operands are ordered the opposite of SELECT
15058  // operands.
15059  if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
15060    if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
15061      // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
15062      // larger than FalseC (the false value).
15063      if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
15064        CC = X86::GetOppositeBranchCondition(CC);
15065        std::swap(TrueC, FalseC);
15066        std::swap(TrueOp, FalseOp);
15067      }
15068
15069      // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3.  Likewise for any pow2/0.
15070      // This is efficient for any integer data type (including i8/i16) and
15071      // shift amount.
15072      if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
15073        Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
15074                           DAG.getConstant(CC, MVT::i8), Cond);
15075
15076        // Zero extend the condition if needed.
15077        Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
15078
15079        unsigned ShAmt = TrueC->getAPIntValue().logBase2();
15080        Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
15081                           DAG.getConstant(ShAmt, MVT::i8));
15082        if (N->getNumValues() == 2)  // Dead flag value?
15083          return DCI.CombineTo(N, Cond, SDValue());
15084        return Cond;
15085      }
15086
15087      // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.  This is efficient
15088      // for any integer data type, including i8/i16.
15089      if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
15090        Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
15091                           DAG.getConstant(CC, MVT::i8), Cond);
15092
15093        // Zero extend the condition if needed.
15094        Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
15095                           FalseC->getValueType(0), Cond);
15096        Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
15097                           SDValue(FalseC, 0));
15098
15099        if (N->getNumValues() == 2)  // Dead flag value?
15100          return DCI.CombineTo(N, Cond, SDValue());
15101        return Cond;
15102      }
15103
15104      // Optimize cases that will turn into an LEA instruction.  This requires
15105      // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
15106      if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
15107        uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
15108        if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
15109
15110        bool isFastMultiplier = false;
15111        if (Diff < 10) {
15112          switch ((unsigned char)Diff) {
15113          default: break;
15114          case 1:  // result = add base, cond
15115          case 2:  // result = lea base(    , cond*2)
15116          case 3:  // result = lea base(cond, cond*2)
15117          case 4:  // result = lea base(    , cond*4)
15118          case 5:  // result = lea base(cond, cond*4)
15119          case 8:  // result = lea base(    , cond*8)
15120          case 9:  // result = lea base(cond, cond*8)
15121            isFastMultiplier = true;
15122            break;
15123          }
15124        }
15125
15126        if (isFastMultiplier) {
15127          APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
15128          Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
15129                             DAG.getConstant(CC, MVT::i8), Cond);
15130          // Zero extend the condition if needed.
15131          Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
15132                             Cond);
15133          // Scale the condition by the difference.
15134          if (Diff != 1)
15135            Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
15136                               DAG.getConstant(Diff, Cond.getValueType()));
15137
15138          // Add the base if non-zero.
15139          if (FalseC->getAPIntValue() != 0)
15140            Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
15141                               SDValue(FalseC, 0));
15142          if (N->getNumValues() == 2)  // Dead flag value?
15143            return DCI.CombineTo(N, Cond, SDValue());
15144          return Cond;
15145        }
15146      }
15147    }
15148  }
15149
15150  // Handle these cases:
15151  //   (select (x != c), e, c) -> select (x != c), e, x),
15152  //   (select (x == c), c, e) -> select (x == c), x, e)
15153  // where the c is an integer constant, and the "select" is the combination
15154  // of CMOV and CMP.
15155  //
15156  // The rationale for this change is that the conditional-move from a constant
15157  // needs two instructions, however, conditional-move from a register needs
15158  // only one instruction.
15159  //
15160  // CAVEAT: By replacing a constant with a symbolic value, it may obscure
15161  //  some instruction-combining opportunities. This opt needs to be
15162  //  postponed as late as possible.
15163  //
15164  if (!DCI.isBeforeLegalize() && !DCI.isBeforeLegalizeOps()) {
15165    // the DCI.xxxx conditions are provided to postpone the optimization as
15166    // late as possible.
15167
15168    ConstantSDNode *CmpAgainst = 0;
15169    if ((Cond.getOpcode() == X86ISD::CMP || Cond.getOpcode() == X86ISD::SUB) &&
15170        (CmpAgainst = dyn_cast<ConstantSDNode>(Cond.getOperand(1))) &&
15171        dyn_cast<ConstantSDNode>(Cond.getOperand(0)) == 0) {
15172
15173      if (CC == X86::COND_NE &&
15174          CmpAgainst == dyn_cast<ConstantSDNode>(FalseOp)) {
15175        CC = X86::GetOppositeBranchCondition(CC);
15176        std::swap(TrueOp, FalseOp);
15177      }
15178
15179      if (CC == X86::COND_E &&
15180          CmpAgainst == dyn_cast<ConstantSDNode>(TrueOp)) {
15181        SDValue Ops[] = { FalseOp, Cond.getOperand(0),
15182                          DAG.getConstant(CC, MVT::i8), Cond };
15183        return DAG.getNode(X86ISD::CMOV, DL, N->getVTList (), Ops,
15184                           array_lengthof(Ops));
15185      }
15186    }
15187  }
15188
15189  return SDValue();
15190}
15191
15192
15193/// PerformMulCombine - Optimize a single multiply with constant into two
15194/// in order to implement it with two cheaper instructions, e.g.
15195/// LEA + SHL, LEA + LEA.
15196static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
15197                                 TargetLowering::DAGCombinerInfo &DCI) {
15198  if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
15199    return SDValue();
15200
15201  EVT VT = N->getValueType(0);
15202  if (VT != MVT::i64)
15203    return SDValue();
15204
15205  ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
15206  if (!C)
15207    return SDValue();
15208  uint64_t MulAmt = C->getZExtValue();
15209  if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
15210    return SDValue();
15211
15212  uint64_t MulAmt1 = 0;
15213  uint64_t MulAmt2 = 0;
15214  if ((MulAmt % 9) == 0) {
15215    MulAmt1 = 9;
15216    MulAmt2 = MulAmt / 9;
15217  } else if ((MulAmt % 5) == 0) {
15218    MulAmt1 = 5;
15219    MulAmt2 = MulAmt / 5;
15220  } else if ((MulAmt % 3) == 0) {
15221    MulAmt1 = 3;
15222    MulAmt2 = MulAmt / 3;
15223  }
15224  if (MulAmt2 &&
15225      (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
15226    DebugLoc DL = N->getDebugLoc();
15227
15228    if (isPowerOf2_64(MulAmt2) &&
15229        !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
15230      // If second multiplifer is pow2, issue it first. We want the multiply by
15231      // 3, 5, or 9 to be folded into the addressing mode unless the lone use
15232      // is an add.
15233      std::swap(MulAmt1, MulAmt2);
15234
15235    SDValue NewMul;
15236    if (isPowerOf2_64(MulAmt1))
15237      NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
15238                           DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
15239    else
15240      NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
15241                           DAG.getConstant(MulAmt1, VT));
15242
15243    if (isPowerOf2_64(MulAmt2))
15244      NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
15245                           DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
15246    else
15247      NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
15248                           DAG.getConstant(MulAmt2, VT));
15249
15250    // Do not add new nodes to DAG combiner worklist.
15251    DCI.CombineTo(N, NewMul, false);
15252  }
15253  return SDValue();
15254}
15255
15256static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
15257  SDValue N0 = N->getOperand(0);
15258  SDValue N1 = N->getOperand(1);
15259  ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
15260  EVT VT = N0.getValueType();
15261
15262  // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
15263  // since the result of setcc_c is all zero's or all ones.
15264  if (VT.isInteger() && !VT.isVector() &&
15265      N1C && N0.getOpcode() == ISD::AND &&
15266      N0.getOperand(1).getOpcode() == ISD::Constant) {
15267    SDValue N00 = N0.getOperand(0);
15268    if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
15269        ((N00.getOpcode() == ISD::ANY_EXTEND ||
15270          N00.getOpcode() == ISD::ZERO_EXTEND) &&
15271         N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
15272      APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
15273      APInt ShAmt = N1C->getAPIntValue();
15274      Mask = Mask.shl(ShAmt);
15275      if (Mask != 0)
15276        return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
15277                           N00, DAG.getConstant(Mask, VT));
15278    }
15279  }
15280
15281
15282  // Hardware support for vector shifts is sparse which makes us scalarize the
15283  // vector operations in many cases. Also, on sandybridge ADD is faster than
15284  // shl.
15285  // (shl V, 1) -> add V,V
15286  if (isSplatVector(N1.getNode())) {
15287    assert(N0.getValueType().isVector() && "Invalid vector shift type");
15288    ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1->getOperand(0));
15289    // We shift all of the values by one. In many cases we do not have
15290    // hardware support for this operation. This is better expressed as an ADD
15291    // of two values.
15292    if (N1C && (1 == N1C->getZExtValue())) {
15293      return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, N0, N0);
15294    }
15295  }
15296
15297  return SDValue();
15298}
15299
15300/// PerformShiftCombine - Transforms vector shift nodes to use vector shifts
15301///                       when possible.
15302static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
15303                                   TargetLowering::DAGCombinerInfo &DCI,
15304                                   const X86Subtarget *Subtarget) {
15305  EVT VT = N->getValueType(0);
15306  if (N->getOpcode() == ISD::SHL) {
15307    SDValue V = PerformSHLCombine(N, DAG);
15308    if (V.getNode()) return V;
15309  }
15310
15311  // On X86 with SSE2 support, we can transform this to a vector shift if
15312  // all elements are shifted by the same amount.  We can't do this in legalize
15313  // because the a constant vector is typically transformed to a constant pool
15314  // so we have no knowledge of the shift amount.
15315  if (!Subtarget->hasSSE2())
15316    return SDValue();
15317
15318  if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16 &&
15319      (!Subtarget->hasAVX2() ||
15320       (VT != MVT::v4i64 && VT != MVT::v8i32 && VT != MVT::v16i16)))
15321    return SDValue();
15322
15323  SDValue ShAmtOp = N->getOperand(1);
15324  EVT EltVT = VT.getVectorElementType();
15325  DebugLoc DL = N->getDebugLoc();
15326  SDValue BaseShAmt = SDValue();
15327  if (ShAmtOp.getOpcode() == ISD::BUILD_VECTOR) {
15328    unsigned NumElts = VT.getVectorNumElements();
15329    unsigned i = 0;
15330    for (; i != NumElts; ++i) {
15331      SDValue Arg = ShAmtOp.getOperand(i);
15332      if (Arg.getOpcode() == ISD::UNDEF) continue;
15333      BaseShAmt = Arg;
15334      break;
15335    }
15336    // Handle the case where the build_vector is all undef
15337    // FIXME: Should DAG allow this?
15338    if (i == NumElts)
15339      return SDValue();
15340
15341    for (; i != NumElts; ++i) {
15342      SDValue Arg = ShAmtOp.getOperand(i);
15343      if (Arg.getOpcode() == ISD::UNDEF) continue;
15344      if (Arg != BaseShAmt) {
15345        return SDValue();
15346      }
15347    }
15348  } else if (ShAmtOp.getOpcode() == ISD::VECTOR_SHUFFLE &&
15349             cast<ShuffleVectorSDNode>(ShAmtOp)->isSplat()) {
15350    SDValue InVec = ShAmtOp.getOperand(0);
15351    if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
15352      unsigned NumElts = InVec.getValueType().getVectorNumElements();
15353      unsigned i = 0;
15354      for (; i != NumElts; ++i) {
15355        SDValue Arg = InVec.getOperand(i);
15356        if (Arg.getOpcode() == ISD::UNDEF) continue;
15357        BaseShAmt = Arg;
15358        break;
15359      }
15360    } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
15361       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
15362         unsigned SplatIdx= cast<ShuffleVectorSDNode>(ShAmtOp)->getSplatIndex();
15363         if (C->getZExtValue() == SplatIdx)
15364           BaseShAmt = InVec.getOperand(1);
15365       }
15366    }
15367    if (BaseShAmt.getNode() == 0) {
15368      // Don't create instructions with illegal types after legalize
15369      // types has run.
15370      if (!DAG.getTargetLoweringInfo().isTypeLegal(EltVT) &&
15371          !DCI.isBeforeLegalize())
15372        return SDValue();
15373
15374      BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, ShAmtOp,
15375                              DAG.getIntPtrConstant(0));
15376    }
15377  } else
15378    return SDValue();
15379
15380  // The shift amount is an i32.
15381  if (EltVT.bitsGT(MVT::i32))
15382    BaseShAmt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, BaseShAmt);
15383  else if (EltVT.bitsLT(MVT::i32))
15384    BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, BaseShAmt);
15385
15386  // The shift amount is identical so we can do a vector shift.
15387  SDValue  ValOp = N->getOperand(0);
15388  switch (N->getOpcode()) {
15389  default:
15390    llvm_unreachable("Unknown shift opcode!");
15391  case ISD::SHL:
15392    switch (VT.getSimpleVT().SimpleTy) {
15393    default: return SDValue();
15394    case MVT::v2i64:
15395    case MVT::v4i32:
15396    case MVT::v8i16:
15397    case MVT::v4i64:
15398    case MVT::v8i32:
15399    case MVT::v16i16:
15400      return getTargetVShiftNode(X86ISD::VSHLI, DL, VT, ValOp, BaseShAmt, DAG);
15401    }
15402  case ISD::SRA:
15403    switch (VT.getSimpleVT().SimpleTy) {
15404    default: return SDValue();
15405    case MVT::v4i32:
15406    case MVT::v8i16:
15407    case MVT::v8i32:
15408    case MVT::v16i16:
15409      return getTargetVShiftNode(X86ISD::VSRAI, DL, VT, ValOp, BaseShAmt, DAG);
15410    }
15411  case ISD::SRL:
15412    switch (VT.getSimpleVT().SimpleTy) {
15413    default: return SDValue();
15414    case MVT::v2i64:
15415    case MVT::v4i32:
15416    case MVT::v8i16:
15417    case MVT::v4i64:
15418    case MVT::v8i32:
15419    case MVT::v16i16:
15420      return getTargetVShiftNode(X86ISD::VSRLI, DL, VT, ValOp, BaseShAmt, DAG);
15421    }
15422  }
15423}
15424
15425
15426// CMPEQCombine - Recognize the distinctive  (AND (setcc ...) (setcc ..))
15427// where both setccs reference the same FP CMP, and rewrite for CMPEQSS
15428// and friends.  Likewise for OR -> CMPNEQSS.
15429static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
15430                            TargetLowering::DAGCombinerInfo &DCI,
15431                            const X86Subtarget *Subtarget) {
15432  unsigned opcode;
15433
15434  // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
15435  // we're requiring SSE2 for both.
15436  if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
15437    SDValue N0 = N->getOperand(0);
15438    SDValue N1 = N->getOperand(1);
15439    SDValue CMP0 = N0->getOperand(1);
15440    SDValue CMP1 = N1->getOperand(1);
15441    DebugLoc DL = N->getDebugLoc();
15442
15443    // The SETCCs should both refer to the same CMP.
15444    if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
15445      return SDValue();
15446
15447    SDValue CMP00 = CMP0->getOperand(0);
15448    SDValue CMP01 = CMP0->getOperand(1);
15449    EVT     VT    = CMP00.getValueType();
15450
15451    if (VT == MVT::f32 || VT == MVT::f64) {
15452      bool ExpectingFlags = false;
15453      // Check for any users that want flags:
15454      for (SDNode::use_iterator UI = N->use_begin(),
15455             UE = N->use_end();
15456           !ExpectingFlags && UI != UE; ++UI)
15457        switch (UI->getOpcode()) {
15458        default:
15459        case ISD::BR_CC:
15460        case ISD::BRCOND:
15461        case ISD::SELECT:
15462          ExpectingFlags = true;
15463          break;
15464        case ISD::CopyToReg:
15465        case ISD::SIGN_EXTEND:
15466        case ISD::ZERO_EXTEND:
15467        case ISD::ANY_EXTEND:
15468          break;
15469        }
15470
15471      if (!ExpectingFlags) {
15472        enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
15473        enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
15474
15475        if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
15476          X86::CondCode tmp = cc0;
15477          cc0 = cc1;
15478          cc1 = tmp;
15479        }
15480
15481        if ((cc0 == X86::COND_E  && cc1 == X86::COND_NP) ||
15482            (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
15483          bool is64BitFP = (CMP00.getValueType() == MVT::f64);
15484          X86ISD::NodeType NTOperator = is64BitFP ?
15485            X86ISD::FSETCCsd : X86ISD::FSETCCss;
15486          // FIXME: need symbolic constants for these magic numbers.
15487          // See X86ATTInstPrinter.cpp:printSSECC().
15488          unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
15489          SDValue OnesOrZeroesF = DAG.getNode(NTOperator, DL, MVT::f32, CMP00, CMP01,
15490                                              DAG.getConstant(x86cc, MVT::i8));
15491          SDValue OnesOrZeroesI = DAG.getNode(ISD::BITCAST, DL, MVT::i32,
15492                                              OnesOrZeroesF);
15493          SDValue ANDed = DAG.getNode(ISD::AND, DL, MVT::i32, OnesOrZeroesI,
15494                                      DAG.getConstant(1, MVT::i32));
15495          SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8, ANDed);
15496          return OneBitOfTruth;
15497        }
15498      }
15499    }
15500  }
15501  return SDValue();
15502}
15503
15504/// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
15505/// so it can be folded inside ANDNP.
15506static bool CanFoldXORWithAllOnes(const SDNode *N) {
15507  EVT VT = N->getValueType(0);
15508
15509  // Match direct AllOnes for 128 and 256-bit vectors
15510  if (ISD::isBuildVectorAllOnes(N))
15511    return true;
15512
15513  // Look through a bit convert.
15514  if (N->getOpcode() == ISD::BITCAST)
15515    N = N->getOperand(0).getNode();
15516
15517  // Sometimes the operand may come from a insert_subvector building a 256-bit
15518  // allones vector
15519  if (VT.is256BitVector() &&
15520      N->getOpcode() == ISD::INSERT_SUBVECTOR) {
15521    SDValue V1 = N->getOperand(0);
15522    SDValue V2 = N->getOperand(1);
15523
15524    if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
15525        V1.getOperand(0).getOpcode() == ISD::UNDEF &&
15526        ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
15527        ISD::isBuildVectorAllOnes(V2.getNode()))
15528      return true;
15529  }
15530
15531  return false;
15532}
15533
15534static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
15535                                 TargetLowering::DAGCombinerInfo &DCI,
15536                                 const X86Subtarget *Subtarget) {
15537  if (DCI.isBeforeLegalizeOps())
15538    return SDValue();
15539
15540  SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
15541  if (R.getNode())
15542    return R;
15543
15544  EVT VT = N->getValueType(0);
15545
15546  // Create ANDN, BLSI, and BLSR instructions
15547  // BLSI is X & (-X)
15548  // BLSR is X & (X-1)
15549  if (Subtarget->hasBMI() && (VT == MVT::i32 || VT == MVT::i64)) {
15550    SDValue N0 = N->getOperand(0);
15551    SDValue N1 = N->getOperand(1);
15552    DebugLoc DL = N->getDebugLoc();
15553
15554    // Check LHS for not
15555    if (N0.getOpcode() == ISD::XOR && isAllOnes(N0.getOperand(1)))
15556      return DAG.getNode(X86ISD::ANDN, DL, VT, N0.getOperand(0), N1);
15557    // Check RHS for not
15558    if (N1.getOpcode() == ISD::XOR && isAllOnes(N1.getOperand(1)))
15559      return DAG.getNode(X86ISD::ANDN, DL, VT, N1.getOperand(0), N0);
15560
15561    // Check LHS for neg
15562    if (N0.getOpcode() == ISD::SUB && N0.getOperand(1) == N1 &&
15563        isZero(N0.getOperand(0)))
15564      return DAG.getNode(X86ISD::BLSI, DL, VT, N1);
15565
15566    // Check RHS for neg
15567    if (N1.getOpcode() == ISD::SUB && N1.getOperand(1) == N0 &&
15568        isZero(N1.getOperand(0)))
15569      return DAG.getNode(X86ISD::BLSI, DL, VT, N0);
15570
15571    // Check LHS for X-1
15572    if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1 &&
15573        isAllOnes(N0.getOperand(1)))
15574      return DAG.getNode(X86ISD::BLSR, DL, VT, N1);
15575
15576    // Check RHS for X-1
15577    if (N1.getOpcode() == ISD::ADD && N1.getOperand(0) == N0 &&
15578        isAllOnes(N1.getOperand(1)))
15579      return DAG.getNode(X86ISD::BLSR, DL, VT, N0);
15580
15581    return SDValue();
15582  }
15583
15584  // Want to form ANDNP nodes:
15585  // 1) In the hopes of then easily combining them with OR and AND nodes
15586  //    to form PBLEND/PSIGN.
15587  // 2) To match ANDN packed intrinsics
15588  if (VT != MVT::v2i64 && VT != MVT::v4i64)
15589    return SDValue();
15590
15591  SDValue N0 = N->getOperand(0);
15592  SDValue N1 = N->getOperand(1);
15593  DebugLoc DL = N->getDebugLoc();
15594
15595  // Check LHS for vnot
15596  if (N0.getOpcode() == ISD::XOR &&
15597      //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
15598      CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
15599    return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
15600
15601  // Check RHS for vnot
15602  if (N1.getOpcode() == ISD::XOR &&
15603      //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
15604      CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
15605    return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
15606
15607  return SDValue();
15608}
15609
15610static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
15611                                TargetLowering::DAGCombinerInfo &DCI,
15612                                const X86Subtarget *Subtarget) {
15613  if (DCI.isBeforeLegalizeOps())
15614    return SDValue();
15615
15616  SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
15617  if (R.getNode())
15618    return R;
15619
15620  EVT VT = N->getValueType(0);
15621
15622  SDValue N0 = N->getOperand(0);
15623  SDValue N1 = N->getOperand(1);
15624
15625  // look for psign/blend
15626  if (VT == MVT::v2i64 || VT == MVT::v4i64) {
15627    if (!Subtarget->hasSSSE3() ||
15628        (VT == MVT::v4i64 && !Subtarget->hasAVX2()))
15629      return SDValue();
15630
15631    // Canonicalize pandn to RHS
15632    if (N0.getOpcode() == X86ISD::ANDNP)
15633      std::swap(N0, N1);
15634    // or (and (m, y), (pandn m, x))
15635    if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
15636      SDValue Mask = N1.getOperand(0);
15637      SDValue X    = N1.getOperand(1);
15638      SDValue Y;
15639      if (N0.getOperand(0) == Mask)
15640        Y = N0.getOperand(1);
15641      if (N0.getOperand(1) == Mask)
15642        Y = N0.getOperand(0);
15643
15644      // Check to see if the mask appeared in both the AND and ANDNP and
15645      if (!Y.getNode())
15646        return SDValue();
15647
15648      // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
15649      // Look through mask bitcast.
15650      if (Mask.getOpcode() == ISD::BITCAST)
15651        Mask = Mask.getOperand(0);
15652      if (X.getOpcode() == ISD::BITCAST)
15653        X = X.getOperand(0);
15654      if (Y.getOpcode() == ISD::BITCAST)
15655        Y = Y.getOperand(0);
15656
15657      EVT MaskVT = Mask.getValueType();
15658
15659      // Validate that the Mask operand is a vector sra node.
15660      // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
15661      // there is no psrai.b
15662      if (Mask.getOpcode() != X86ISD::VSRAI)
15663        return SDValue();
15664
15665      // Check that the SRA is all signbits.
15666      SDValue SraC = Mask.getOperand(1);
15667      unsigned SraAmt  = cast<ConstantSDNode>(SraC)->getZExtValue();
15668      unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
15669      if ((SraAmt + 1) != EltBits)
15670        return SDValue();
15671
15672      DebugLoc DL = N->getDebugLoc();
15673
15674      // Now we know we at least have a plendvb with the mask val.  See if
15675      // we can form a psignb/w/d.
15676      // psign = x.type == y.type == mask.type && y = sub(0, x);
15677      if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
15678          ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
15679          X.getValueType() == MaskVT && Y.getValueType() == MaskVT) {
15680        assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
15681               "Unsupported VT for PSIGN");
15682        Mask = DAG.getNode(X86ISD::PSIGN, DL, MaskVT, X, Mask.getOperand(0));
15683        return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
15684      }
15685      // PBLENDVB only available on SSE 4.1
15686      if (!Subtarget->hasSSE41())
15687        return SDValue();
15688
15689      EVT BlendVT = (VT == MVT::v4i64) ? MVT::v32i8 : MVT::v16i8;
15690
15691      X = DAG.getNode(ISD::BITCAST, DL, BlendVT, X);
15692      Y = DAG.getNode(ISD::BITCAST, DL, BlendVT, Y);
15693      Mask = DAG.getNode(ISD::BITCAST, DL, BlendVT, Mask);
15694      Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, Y, X);
15695      return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
15696    }
15697  }
15698
15699  if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
15700    return SDValue();
15701
15702  // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
15703  if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
15704    std::swap(N0, N1);
15705  if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
15706    return SDValue();
15707  if (!N0.hasOneUse() || !N1.hasOneUse())
15708    return SDValue();
15709
15710  SDValue ShAmt0 = N0.getOperand(1);
15711  if (ShAmt0.getValueType() != MVT::i8)
15712    return SDValue();
15713  SDValue ShAmt1 = N1.getOperand(1);
15714  if (ShAmt1.getValueType() != MVT::i8)
15715    return SDValue();
15716  if (ShAmt0.getOpcode() == ISD::TRUNCATE)
15717    ShAmt0 = ShAmt0.getOperand(0);
15718  if (ShAmt1.getOpcode() == ISD::TRUNCATE)
15719    ShAmt1 = ShAmt1.getOperand(0);
15720
15721  DebugLoc DL = N->getDebugLoc();
15722  unsigned Opc = X86ISD::SHLD;
15723  SDValue Op0 = N0.getOperand(0);
15724  SDValue Op1 = N1.getOperand(0);
15725  if (ShAmt0.getOpcode() == ISD::SUB) {
15726    Opc = X86ISD::SHRD;
15727    std::swap(Op0, Op1);
15728    std::swap(ShAmt0, ShAmt1);
15729  }
15730
15731  unsigned Bits = VT.getSizeInBits();
15732  if (ShAmt1.getOpcode() == ISD::SUB) {
15733    SDValue Sum = ShAmt1.getOperand(0);
15734    if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
15735      SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
15736      if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
15737        ShAmt1Op1 = ShAmt1Op1.getOperand(0);
15738      if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
15739        return DAG.getNode(Opc, DL, VT,
15740                           Op0, Op1,
15741                           DAG.getNode(ISD::TRUNCATE, DL,
15742                                       MVT::i8, ShAmt0));
15743    }
15744  } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
15745    ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
15746    if (ShAmt0C &&
15747        ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
15748      return DAG.getNode(Opc, DL, VT,
15749                         N0.getOperand(0), N1.getOperand(0),
15750                         DAG.getNode(ISD::TRUNCATE, DL,
15751                                       MVT::i8, ShAmt0));
15752  }
15753
15754  return SDValue();
15755}
15756
15757// Generate NEG and CMOV for integer abs.
15758static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
15759  EVT VT = N->getValueType(0);
15760
15761  // Since X86 does not have CMOV for 8-bit integer, we don't convert
15762  // 8-bit integer abs to NEG and CMOV.
15763  if (VT.isInteger() && VT.getSizeInBits() == 8)
15764    return SDValue();
15765
15766  SDValue N0 = N->getOperand(0);
15767  SDValue N1 = N->getOperand(1);
15768  DebugLoc DL = N->getDebugLoc();
15769
15770  // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
15771  // and change it to SUB and CMOV.
15772  if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
15773      N0.getOpcode() == ISD::ADD &&
15774      N0.getOperand(1) == N1 &&
15775      N1.getOpcode() == ISD::SRA &&
15776      N1.getOperand(0) == N0.getOperand(0))
15777    if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
15778      if (Y1C->getAPIntValue() == VT.getSizeInBits()-1) {
15779        // Generate SUB & CMOV.
15780        SDValue Neg = DAG.getNode(X86ISD::SUB, DL, DAG.getVTList(VT, MVT::i32),
15781                                  DAG.getConstant(0, VT), N0.getOperand(0));
15782
15783        SDValue Ops[] = { N0.getOperand(0), Neg,
15784                          DAG.getConstant(X86::COND_GE, MVT::i8),
15785                          SDValue(Neg.getNode(), 1) };
15786        return DAG.getNode(X86ISD::CMOV, DL, DAG.getVTList(VT, MVT::Glue),
15787                           Ops, array_lengthof(Ops));
15788      }
15789  return SDValue();
15790}
15791
15792// PerformXorCombine - Attempts to turn XOR nodes into BLSMSK nodes
15793static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
15794                                 TargetLowering::DAGCombinerInfo &DCI,
15795                                 const X86Subtarget *Subtarget) {
15796  if (DCI.isBeforeLegalizeOps())
15797    return SDValue();
15798
15799  if (Subtarget->hasCMov()) {
15800    SDValue RV = performIntegerAbsCombine(N, DAG);
15801    if (RV.getNode())
15802      return RV;
15803  }
15804
15805  // Try forming BMI if it is available.
15806  if (!Subtarget->hasBMI())
15807    return SDValue();
15808
15809  EVT VT = N->getValueType(0);
15810
15811  if (VT != MVT::i32 && VT != MVT::i64)
15812    return SDValue();
15813
15814  assert(Subtarget->hasBMI() && "Creating BLSMSK requires BMI instructions");
15815
15816  // Create BLSMSK instructions by finding X ^ (X-1)
15817  SDValue N0 = N->getOperand(0);
15818  SDValue N1 = N->getOperand(1);
15819  DebugLoc DL = N->getDebugLoc();
15820
15821  if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1 &&
15822      isAllOnes(N0.getOperand(1)))
15823    return DAG.getNode(X86ISD::BLSMSK, DL, VT, N1);
15824
15825  if (N1.getOpcode() == ISD::ADD && N1.getOperand(0) == N0 &&
15826      isAllOnes(N1.getOperand(1)))
15827    return DAG.getNode(X86ISD::BLSMSK, DL, VT, N0);
15828
15829  return SDValue();
15830}
15831
15832/// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
15833static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
15834                                  TargetLowering::DAGCombinerInfo &DCI,
15835                                  const X86Subtarget *Subtarget) {
15836  LoadSDNode *Ld = cast<LoadSDNode>(N);
15837  EVT RegVT = Ld->getValueType(0);
15838  EVT MemVT = Ld->getMemoryVT();
15839  DebugLoc dl = Ld->getDebugLoc();
15840  const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15841
15842  ISD::LoadExtType Ext = Ld->getExtensionType();
15843
15844  // If this is a vector EXT Load then attempt to optimize it using a
15845  // shuffle. We need SSSE3 shuffles.
15846  // TODO: It is possible to support ZExt by zeroing the undef values
15847  // during the shuffle phase or after the shuffle.
15848  if (RegVT.isVector() && RegVT.isInteger() &&
15849      Ext == ISD::EXTLOAD && Subtarget->hasSSSE3()) {
15850    assert(MemVT != RegVT && "Cannot extend to the same type");
15851    assert(MemVT.isVector() && "Must load a vector from memory");
15852
15853    unsigned NumElems = RegVT.getVectorNumElements();
15854    unsigned RegSz = RegVT.getSizeInBits();
15855    unsigned MemSz = MemVT.getSizeInBits();
15856    assert(RegSz > MemSz && "Register size must be greater than the mem size");
15857
15858    // All sizes must be a power of two.
15859    if (!isPowerOf2_32(RegSz * MemSz * NumElems))
15860      return SDValue();
15861
15862    // Attempt to load the original value using scalar loads.
15863    // Find the largest scalar type that divides the total loaded size.
15864    MVT SclrLoadTy = MVT::i8;
15865    for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
15866         tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
15867      MVT Tp = (MVT::SimpleValueType)tp;
15868      if (TLI.isTypeLegal(Tp) && ((MemSz % Tp.getSizeInBits()) == 0)) {
15869        SclrLoadTy = Tp;
15870      }
15871    }
15872
15873    // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
15874    if (TLI.isTypeLegal(MVT::f64) && SclrLoadTy.getSizeInBits() < 64 &&
15875        (64 <= MemSz))
15876      SclrLoadTy = MVT::f64;
15877
15878    // Calculate the number of scalar loads that we need to perform
15879    // in order to load our vector from memory.
15880    unsigned NumLoads = MemSz / SclrLoadTy.getSizeInBits();
15881
15882    // Represent our vector as a sequence of elements which are the
15883    // largest scalar that we can load.
15884    EVT LoadUnitVecVT = EVT::getVectorVT(*DAG.getContext(), SclrLoadTy,
15885      RegSz/SclrLoadTy.getSizeInBits());
15886
15887    // Represent the data using the same element type that is stored in
15888    // memory. In practice, we ''widen'' MemVT.
15889    EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
15890                                  RegSz/MemVT.getScalarType().getSizeInBits());
15891
15892    assert(WideVecVT.getSizeInBits() == LoadUnitVecVT.getSizeInBits() &&
15893      "Invalid vector type");
15894
15895    // We can't shuffle using an illegal type.
15896    if (!TLI.isTypeLegal(WideVecVT))
15897      return SDValue();
15898
15899    SmallVector<SDValue, 8> Chains;
15900    SDValue Ptr = Ld->getBasePtr();
15901    SDValue Increment = DAG.getConstant(SclrLoadTy.getSizeInBits()/8,
15902                                        TLI.getPointerTy());
15903    SDValue Res = DAG.getUNDEF(LoadUnitVecVT);
15904
15905    for (unsigned i = 0; i < NumLoads; ++i) {
15906      // Perform a single load.
15907      SDValue ScalarLoad = DAG.getLoad(SclrLoadTy, dl, Ld->getChain(),
15908                                       Ptr, Ld->getPointerInfo(),
15909                                       Ld->isVolatile(), Ld->isNonTemporal(),
15910                                       Ld->isInvariant(), Ld->getAlignment());
15911      Chains.push_back(ScalarLoad.getValue(1));
15912      // Create the first element type using SCALAR_TO_VECTOR in order to avoid
15913      // another round of DAGCombining.
15914      if (i == 0)
15915        Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LoadUnitVecVT, ScalarLoad);
15916      else
15917        Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, LoadUnitVecVT, Res,
15918                          ScalarLoad, DAG.getIntPtrConstant(i));
15919
15920      Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
15921    }
15922
15923    SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Chains[0],
15924                               Chains.size());
15925
15926    // Bitcast the loaded value to a vector of the original element type, in
15927    // the size of the target vector type.
15928    SDValue SlicedVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Res);
15929    unsigned SizeRatio = RegSz/MemSz;
15930
15931    // Redistribute the loaded elements into the different locations.
15932    SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
15933    for (unsigned i = 0; i != NumElems; ++i)
15934      ShuffleVec[i*SizeRatio] = i;
15935
15936    SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
15937                                         DAG.getUNDEF(WideVecVT),
15938                                         &ShuffleVec[0]);
15939
15940    // Bitcast to the requested type.
15941    Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
15942    // Replace the original load with the new sequence
15943    // and return the new chain.
15944    return DCI.CombineTo(N, Shuff, TF, true);
15945  }
15946
15947  return SDValue();
15948}
15949
15950/// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
15951static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
15952                                   const X86Subtarget *Subtarget) {
15953  StoreSDNode *St = cast<StoreSDNode>(N);
15954  EVT VT = St->getValue().getValueType();
15955  EVT StVT = St->getMemoryVT();
15956  DebugLoc dl = St->getDebugLoc();
15957  SDValue StoredVal = St->getOperand(1);
15958  const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15959
15960  // If we are saving a concatenation of two XMM registers, perform two stores.
15961  // On Sandy Bridge, 256-bit memory operations are executed by two
15962  // 128-bit ports. However, on Haswell it is better to issue a single 256-bit
15963  // memory  operation.
15964  if (VT.is256BitVector() && !Subtarget->hasAVX2() &&
15965      StoredVal.getNode()->getOpcode() == ISD::CONCAT_VECTORS &&
15966      StoredVal.getNumOperands() == 2) {
15967    SDValue Value0 = StoredVal.getOperand(0);
15968    SDValue Value1 = StoredVal.getOperand(1);
15969
15970    SDValue Stride = DAG.getConstant(16, TLI.getPointerTy());
15971    SDValue Ptr0 = St->getBasePtr();
15972    SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
15973
15974    SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
15975                                St->getPointerInfo(), St->isVolatile(),
15976                                St->isNonTemporal(), St->getAlignment());
15977    SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
15978                                St->getPointerInfo(), St->isVolatile(),
15979                                St->isNonTemporal(), St->getAlignment());
15980    return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
15981  }
15982
15983  // Optimize trunc store (of multiple scalars) to shuffle and store.
15984  // First, pack all of the elements in one place. Next, store to memory
15985  // in fewer chunks.
15986  if (St->isTruncatingStore() && VT.isVector()) {
15987    const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15988    unsigned NumElems = VT.getVectorNumElements();
15989    assert(StVT != VT && "Cannot truncate to the same type");
15990    unsigned FromSz = VT.getVectorElementType().getSizeInBits();
15991    unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
15992
15993    // From, To sizes and ElemCount must be pow of two
15994    if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
15995    // We are going to use the original vector elt for storing.
15996    // Accumulated smaller vector elements must be a multiple of the store size.
15997    if (0 != (NumElems * FromSz) % ToSz) return SDValue();
15998
15999    unsigned SizeRatio  = FromSz / ToSz;
16000
16001    assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
16002
16003    // Create a type on which we perform the shuffle
16004    EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
16005            StVT.getScalarType(), NumElems*SizeRatio);
16006
16007    assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
16008
16009    SDValue WideVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, St->getValue());
16010    SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
16011    for (unsigned i = 0; i != NumElems; ++i)
16012      ShuffleVec[i] = i * SizeRatio;
16013
16014    // Can't shuffle using an illegal type.
16015    if (!TLI.isTypeLegal(WideVecVT))
16016      return SDValue();
16017
16018    SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
16019                                         DAG.getUNDEF(WideVecVT),
16020                                         &ShuffleVec[0]);
16021    // At this point all of the data is stored at the bottom of the
16022    // register. We now need to save it to mem.
16023
16024    // Find the largest store unit
16025    MVT StoreType = MVT::i8;
16026    for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
16027         tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
16028      MVT Tp = (MVT::SimpleValueType)tp;
16029      if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToSz)
16030        StoreType = Tp;
16031    }
16032
16033    // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
16034    if (TLI.isTypeLegal(MVT::f64) && StoreType.getSizeInBits() < 64 &&
16035        (64 <= NumElems * ToSz))
16036      StoreType = MVT::f64;
16037
16038    // Bitcast the original vector into a vector of store-size units
16039    EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
16040            StoreType, VT.getSizeInBits()/StoreType.getSizeInBits());
16041    assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
16042    SDValue ShuffWide = DAG.getNode(ISD::BITCAST, dl, StoreVecVT, Shuff);
16043    SmallVector<SDValue, 8> Chains;
16044    SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
16045                                        TLI.getPointerTy());
16046    SDValue Ptr = St->getBasePtr();
16047
16048    // Perform one or more big stores into memory.
16049    for (unsigned i=0, e=(ToSz*NumElems)/StoreType.getSizeInBits(); i!=e; ++i) {
16050      SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
16051                                   StoreType, ShuffWide,
16052                                   DAG.getIntPtrConstant(i));
16053      SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
16054                                St->getPointerInfo(), St->isVolatile(),
16055                                St->isNonTemporal(), St->getAlignment());
16056      Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
16057      Chains.push_back(Ch);
16058    }
16059
16060    return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Chains[0],
16061                               Chains.size());
16062  }
16063
16064
16065  // Turn load->store of MMX types into GPR load/stores.  This avoids clobbering
16066  // the FP state in cases where an emms may be missing.
16067  // A preferable solution to the general problem is to figure out the right
16068  // places to insert EMMS.  This qualifies as a quick hack.
16069
16070  // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
16071  if (VT.getSizeInBits() != 64)
16072    return SDValue();
16073
16074  const Function *F = DAG.getMachineFunction().getFunction();
16075  bool NoImplicitFloatOps = F->getFnAttributes().
16076    hasAttribute(Attributes::NoImplicitFloat);
16077  bool F64IsLegal = !DAG.getTarget().Options.UseSoftFloat && !NoImplicitFloatOps
16078                     && Subtarget->hasSSE2();
16079  if ((VT.isVector() ||
16080       (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
16081      isa<LoadSDNode>(St->getValue()) &&
16082      !cast<LoadSDNode>(St->getValue())->isVolatile() &&
16083      St->getChain().hasOneUse() && !St->isVolatile()) {
16084    SDNode* LdVal = St->getValue().getNode();
16085    LoadSDNode *Ld = 0;
16086    int TokenFactorIndex = -1;
16087    SmallVector<SDValue, 8> Ops;
16088    SDNode* ChainVal = St->getChain().getNode();
16089    // Must be a store of a load.  We currently handle two cases:  the load
16090    // is a direct child, and it's under an intervening TokenFactor.  It is
16091    // possible to dig deeper under nested TokenFactors.
16092    if (ChainVal == LdVal)
16093      Ld = cast<LoadSDNode>(St->getChain());
16094    else if (St->getValue().hasOneUse() &&
16095             ChainVal->getOpcode() == ISD::TokenFactor) {
16096      for (unsigned i = 0, e = ChainVal->getNumOperands(); i != e; ++i) {
16097        if (ChainVal->getOperand(i).getNode() == LdVal) {
16098          TokenFactorIndex = i;
16099          Ld = cast<LoadSDNode>(St->getValue());
16100        } else
16101          Ops.push_back(ChainVal->getOperand(i));
16102      }
16103    }
16104
16105    if (!Ld || !ISD::isNormalLoad(Ld))
16106      return SDValue();
16107
16108    // If this is not the MMX case, i.e. we are just turning i64 load/store
16109    // into f64 load/store, avoid the transformation if there are multiple
16110    // uses of the loaded value.
16111    if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
16112      return SDValue();
16113
16114    DebugLoc LdDL = Ld->getDebugLoc();
16115    DebugLoc StDL = N->getDebugLoc();
16116    // If we are a 64-bit capable x86, lower to a single movq load/store pair.
16117    // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
16118    // pair instead.
16119    if (Subtarget->is64Bit() || F64IsLegal) {
16120      EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
16121      SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
16122                                  Ld->getPointerInfo(), Ld->isVolatile(),
16123                                  Ld->isNonTemporal(), Ld->isInvariant(),
16124                                  Ld->getAlignment());
16125      SDValue NewChain = NewLd.getValue(1);
16126      if (TokenFactorIndex != -1) {
16127        Ops.push_back(NewChain);
16128        NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
16129                               Ops.size());
16130      }
16131      return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
16132                          St->getPointerInfo(),
16133                          St->isVolatile(), St->isNonTemporal(),
16134                          St->getAlignment());
16135    }
16136
16137    // Otherwise, lower to two pairs of 32-bit loads / stores.
16138    SDValue LoAddr = Ld->getBasePtr();
16139    SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
16140                                 DAG.getConstant(4, MVT::i32));
16141
16142    SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
16143                               Ld->getPointerInfo(),
16144                               Ld->isVolatile(), Ld->isNonTemporal(),
16145                               Ld->isInvariant(), Ld->getAlignment());
16146    SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
16147                               Ld->getPointerInfo().getWithOffset(4),
16148                               Ld->isVolatile(), Ld->isNonTemporal(),
16149                               Ld->isInvariant(),
16150                               MinAlign(Ld->getAlignment(), 4));
16151
16152    SDValue NewChain = LoLd.getValue(1);
16153    if (TokenFactorIndex != -1) {
16154      Ops.push_back(LoLd);
16155      Ops.push_back(HiLd);
16156      NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
16157                             Ops.size());
16158    }
16159
16160    LoAddr = St->getBasePtr();
16161    HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
16162                         DAG.getConstant(4, MVT::i32));
16163
16164    SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
16165                                St->getPointerInfo(),
16166                                St->isVolatile(), St->isNonTemporal(),
16167                                St->getAlignment());
16168    SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
16169                                St->getPointerInfo().getWithOffset(4),
16170                                St->isVolatile(),
16171                                St->isNonTemporal(),
16172                                MinAlign(St->getAlignment(), 4));
16173    return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
16174  }
16175  return SDValue();
16176}
16177
16178/// isHorizontalBinOp - Return 'true' if this vector operation is "horizontal"
16179/// and return the operands for the horizontal operation in LHS and RHS.  A
16180/// horizontal operation performs the binary operation on successive elements
16181/// of its first operand, then on successive elements of its second operand,
16182/// returning the resulting values in a vector.  For example, if
16183///   A = < float a0, float a1, float a2, float a3 >
16184/// and
16185///   B = < float b0, float b1, float b2, float b3 >
16186/// then the result of doing a horizontal operation on A and B is
16187///   A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
16188/// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
16189/// A horizontal-op B, for some already available A and B, and if so then LHS is
16190/// set to A, RHS to B, and the routine returns 'true'.
16191/// Note that the binary operation should have the property that if one of the
16192/// operands is UNDEF then the result is UNDEF.
16193static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool IsCommutative) {
16194  // Look for the following pattern: if
16195  //   A = < float a0, float a1, float a2, float a3 >
16196  //   B = < float b0, float b1, float b2, float b3 >
16197  // and
16198  //   LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
16199  //   RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
16200  // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
16201  // which is A horizontal-op B.
16202
16203  // At least one of the operands should be a vector shuffle.
16204  if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
16205      RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
16206    return false;
16207
16208  EVT VT = LHS.getValueType();
16209
16210  assert((VT.is128BitVector() || VT.is256BitVector()) &&
16211         "Unsupported vector type for horizontal add/sub");
16212
16213  // Handle 128 and 256-bit vector lengths. AVX defines horizontal add/sub to
16214  // operate independently on 128-bit lanes.
16215  unsigned NumElts = VT.getVectorNumElements();
16216  unsigned NumLanes = VT.getSizeInBits()/128;
16217  unsigned NumLaneElts = NumElts / NumLanes;
16218  assert((NumLaneElts % 2 == 0) &&
16219         "Vector type should have an even number of elements in each lane");
16220  unsigned HalfLaneElts = NumLaneElts/2;
16221
16222  // View LHS in the form
16223  //   LHS = VECTOR_SHUFFLE A, B, LMask
16224  // If LHS is not a shuffle then pretend it is the shuffle
16225  //   LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
16226  // NOTE: in what follows a default initialized SDValue represents an UNDEF of
16227  // type VT.
16228  SDValue A, B;
16229  SmallVector<int, 16> LMask(NumElts);
16230  if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
16231    if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
16232      A = LHS.getOperand(0);
16233    if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
16234      B = LHS.getOperand(1);
16235    ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(LHS.getNode())->getMask();
16236    std::copy(Mask.begin(), Mask.end(), LMask.begin());
16237  } else {
16238    if (LHS.getOpcode() != ISD::UNDEF)
16239      A = LHS;
16240    for (unsigned i = 0; i != NumElts; ++i)
16241      LMask[i] = i;
16242  }
16243
16244  // Likewise, view RHS in the form
16245  //   RHS = VECTOR_SHUFFLE C, D, RMask
16246  SDValue C, D;
16247  SmallVector<int, 16> RMask(NumElts);
16248  if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
16249    if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
16250      C = RHS.getOperand(0);
16251    if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
16252      D = RHS.getOperand(1);
16253    ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(RHS.getNode())->getMask();
16254    std::copy(Mask.begin(), Mask.end(), RMask.begin());
16255  } else {
16256    if (RHS.getOpcode() != ISD::UNDEF)
16257      C = RHS;
16258    for (unsigned i = 0; i != NumElts; ++i)
16259      RMask[i] = i;
16260  }
16261
16262  // Check that the shuffles are both shuffling the same vectors.
16263  if (!(A == C && B == D) && !(A == D && B == C))
16264    return false;
16265
16266  // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
16267  if (!A.getNode() && !B.getNode())
16268    return false;
16269
16270  // If A and B occur in reverse order in RHS, then "swap" them (which means
16271  // rewriting the mask).
16272  if (A != C)
16273    CommuteVectorShuffleMask(RMask, NumElts);
16274
16275  // At this point LHS and RHS are equivalent to
16276  //   LHS = VECTOR_SHUFFLE A, B, LMask
16277  //   RHS = VECTOR_SHUFFLE A, B, RMask
16278  // Check that the masks correspond to performing a horizontal operation.
16279  for (unsigned i = 0; i != NumElts; ++i) {
16280    int LIdx = LMask[i], RIdx = RMask[i];
16281
16282    // Ignore any UNDEF components.
16283    if (LIdx < 0 || RIdx < 0 ||
16284        (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) ||
16285        (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts)))
16286      continue;
16287
16288    // Check that successive elements are being operated on.  If not, this is
16289    // not a horizontal operation.
16290    unsigned Src = (i/HalfLaneElts) % 2; // each lane is split between srcs
16291    unsigned LaneStart = (i/NumLaneElts) * NumLaneElts;
16292    int Index = 2*(i%HalfLaneElts) + NumElts*Src + LaneStart;
16293    if (!(LIdx == Index && RIdx == Index + 1) &&
16294        !(IsCommutative && LIdx == Index + 1 && RIdx == Index))
16295      return false;
16296  }
16297
16298  LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
16299  RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
16300  return true;
16301}
16302
16303/// PerformFADDCombine - Do target-specific dag combines on floating point adds.
16304static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
16305                                  const X86Subtarget *Subtarget) {
16306  EVT VT = N->getValueType(0);
16307  SDValue LHS = N->getOperand(0);
16308  SDValue RHS = N->getOperand(1);
16309
16310  // Try to synthesize horizontal adds from adds of shuffles.
16311  if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
16312       (Subtarget->hasAVX() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
16313      isHorizontalBinOp(LHS, RHS, true))
16314    return DAG.getNode(X86ISD::FHADD, N->getDebugLoc(), VT, LHS, RHS);
16315  return SDValue();
16316}
16317
16318/// PerformFSUBCombine - Do target-specific dag combines on floating point subs.
16319static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
16320                                  const X86Subtarget *Subtarget) {
16321  EVT VT = N->getValueType(0);
16322  SDValue LHS = N->getOperand(0);
16323  SDValue RHS = N->getOperand(1);
16324
16325  // Try to synthesize horizontal subs from subs of shuffles.
16326  if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
16327       (Subtarget->hasAVX() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
16328      isHorizontalBinOp(LHS, RHS, false))
16329    return DAG.getNode(X86ISD::FHSUB, N->getDebugLoc(), VT, LHS, RHS);
16330  return SDValue();
16331}
16332
16333/// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
16334/// X86ISD::FXOR nodes.
16335static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
16336  assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
16337  // F[X]OR(0.0, x) -> x
16338  // F[X]OR(x, 0.0) -> x
16339  if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
16340    if (C->getValueAPF().isPosZero())
16341      return N->getOperand(1);
16342  if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
16343    if (C->getValueAPF().isPosZero())
16344      return N->getOperand(0);
16345  return SDValue();
16346}
16347
16348/// PerformFMinFMaxCombine - Do target-specific dag combines on X86ISD::FMIN and
16349/// X86ISD::FMAX nodes.
16350static SDValue PerformFMinFMaxCombine(SDNode *N, SelectionDAG &DAG) {
16351  assert(N->getOpcode() == X86ISD::FMIN || N->getOpcode() == X86ISD::FMAX);
16352
16353  // Only perform optimizations if UnsafeMath is used.
16354  if (!DAG.getTarget().Options.UnsafeFPMath)
16355    return SDValue();
16356
16357  // If we run in unsafe-math mode, then convert the FMAX and FMIN nodes
16358  // into FMINC and FMAXC, which are Commutative operations.
16359  unsigned NewOp = 0;
16360  switch (N->getOpcode()) {
16361    default: llvm_unreachable("unknown opcode");
16362    case X86ISD::FMIN:  NewOp = X86ISD::FMINC; break;
16363    case X86ISD::FMAX:  NewOp = X86ISD::FMAXC; break;
16364  }
16365
16366  return DAG.getNode(NewOp, N->getDebugLoc(), N->getValueType(0),
16367                     N->getOperand(0), N->getOperand(1));
16368}
16369
16370
16371/// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
16372static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
16373  // FAND(0.0, x) -> 0.0
16374  // FAND(x, 0.0) -> 0.0
16375  if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
16376    if (C->getValueAPF().isPosZero())
16377      return N->getOperand(0);
16378  if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
16379    if (C->getValueAPF().isPosZero())
16380      return N->getOperand(1);
16381  return SDValue();
16382}
16383
16384static SDValue PerformBTCombine(SDNode *N,
16385                                SelectionDAG &DAG,
16386                                TargetLowering::DAGCombinerInfo &DCI) {
16387  // BT ignores high bits in the bit index operand.
16388  SDValue Op1 = N->getOperand(1);
16389  if (Op1.hasOneUse()) {
16390    unsigned BitWidth = Op1.getValueSizeInBits();
16391    APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
16392    APInt KnownZero, KnownOne;
16393    TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
16394                                          !DCI.isBeforeLegalizeOps());
16395    const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16396    if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
16397        TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
16398      DCI.CommitTargetLoweringOpt(TLO);
16399  }
16400  return SDValue();
16401}
16402
16403static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
16404  SDValue Op = N->getOperand(0);
16405  if (Op.getOpcode() == ISD::BITCAST)
16406    Op = Op.getOperand(0);
16407  EVT VT = N->getValueType(0), OpVT = Op.getValueType();
16408  if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
16409      VT.getVectorElementType().getSizeInBits() ==
16410      OpVT.getVectorElementType().getSizeInBits()) {
16411    return DAG.getNode(ISD::BITCAST, N->getDebugLoc(), VT, Op);
16412  }
16413  return SDValue();
16414}
16415
16416static SDValue PerformSExtCombine(SDNode *N, SelectionDAG &DAG,
16417                                  TargetLowering::DAGCombinerInfo &DCI,
16418                                  const X86Subtarget *Subtarget) {
16419  if (!DCI.isBeforeLegalizeOps())
16420    return SDValue();
16421
16422  if (!Subtarget->hasAVX())
16423    return SDValue();
16424
16425  EVT VT = N->getValueType(0);
16426  SDValue Op = N->getOperand(0);
16427  EVT OpVT = Op.getValueType();
16428  DebugLoc dl = N->getDebugLoc();
16429
16430  if ((VT == MVT::v4i64 && OpVT == MVT::v4i32) ||
16431      (VT == MVT::v8i32 && OpVT == MVT::v8i16)) {
16432
16433    if (Subtarget->hasAVX2())
16434      return DAG.getNode(X86ISD::VSEXT_MOVL, dl, VT, Op);
16435
16436    // Optimize vectors in AVX mode
16437    // Sign extend  v8i16 to v8i32 and
16438    //              v4i32 to v4i64
16439    //
16440    // Divide input vector into two parts
16441    // for v4i32 the shuffle mask will be { 0, 1, -1, -1} {2, 3, -1, -1}
16442    // use vpmovsx instruction to extend v4i32 -> v2i64; v8i16 -> v4i32
16443    // concat the vectors to original VT
16444
16445    unsigned NumElems = OpVT.getVectorNumElements();
16446    SDValue Undef = DAG.getUNDEF(OpVT);
16447
16448    SmallVector<int,8> ShufMask1(NumElems, -1);
16449    for (unsigned i = 0; i != NumElems/2; ++i)
16450      ShufMask1[i] = i;
16451
16452    SDValue OpLo = DAG.getVectorShuffle(OpVT, dl, Op, Undef, &ShufMask1[0]);
16453
16454    SmallVector<int,8> ShufMask2(NumElems, -1);
16455    for (unsigned i = 0; i != NumElems/2; ++i)
16456      ShufMask2[i] = i + NumElems/2;
16457
16458    SDValue OpHi = DAG.getVectorShuffle(OpVT, dl, Op, Undef, &ShufMask2[0]);
16459
16460    EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), VT.getScalarType(),
16461                                  VT.getVectorNumElements()/2);
16462
16463    OpLo = DAG.getNode(X86ISD::VSEXT_MOVL, dl, HalfVT, OpLo);
16464    OpHi = DAG.getNode(X86ISD::VSEXT_MOVL, dl, HalfVT, OpHi);
16465
16466    return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
16467  }
16468  return SDValue();
16469}
16470
16471static SDValue PerformFMACombine(SDNode *N, SelectionDAG &DAG,
16472                                 const X86Subtarget* Subtarget) {
16473  DebugLoc dl = N->getDebugLoc();
16474  EVT VT = N->getValueType(0);
16475
16476  // Let legalize expand this if it isn't a legal type yet.
16477  if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
16478    return SDValue();
16479
16480  EVT ScalarVT = VT.getScalarType();
16481  if ((ScalarVT != MVT::f32 && ScalarVT != MVT::f64) ||
16482      (!Subtarget->hasFMA() && !Subtarget->hasFMA4()))
16483    return SDValue();
16484
16485  SDValue A = N->getOperand(0);
16486  SDValue B = N->getOperand(1);
16487  SDValue C = N->getOperand(2);
16488
16489  bool NegA = (A.getOpcode() == ISD::FNEG);
16490  bool NegB = (B.getOpcode() == ISD::FNEG);
16491  bool NegC = (C.getOpcode() == ISD::FNEG);
16492
16493  // Negative multiplication when NegA xor NegB
16494  bool NegMul = (NegA != NegB);
16495  if (NegA)
16496    A = A.getOperand(0);
16497  if (NegB)
16498    B = B.getOperand(0);
16499  if (NegC)
16500    C = C.getOperand(0);
16501
16502  unsigned Opcode;
16503  if (!NegMul)
16504    Opcode = (!NegC) ? X86ISD::FMADD : X86ISD::FMSUB;
16505  else
16506    Opcode = (!NegC) ? X86ISD::FNMADD : X86ISD::FNMSUB;
16507
16508  return DAG.getNode(Opcode, dl, VT, A, B, C);
16509}
16510
16511static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG,
16512                                  TargetLowering::DAGCombinerInfo &DCI,
16513                                  const X86Subtarget *Subtarget) {
16514  // (i32 zext (and (i8  x86isd::setcc_carry), 1)) ->
16515  //           (and (i32 x86isd::setcc_carry), 1)
16516  // This eliminates the zext. This transformation is necessary because
16517  // ISD::SETCC is always legalized to i8.
16518  DebugLoc dl = N->getDebugLoc();
16519  SDValue N0 = N->getOperand(0);
16520  EVT VT = N->getValueType(0);
16521  EVT OpVT = N0.getValueType();
16522
16523  if (N0.getOpcode() == ISD::AND &&
16524      N0.hasOneUse() &&
16525      N0.getOperand(0).hasOneUse()) {
16526    SDValue N00 = N0.getOperand(0);
16527    if (N00.getOpcode() != X86ISD::SETCC_CARRY)
16528      return SDValue();
16529    ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
16530    if (!C || C->getZExtValue() != 1)
16531      return SDValue();
16532    return DAG.getNode(ISD::AND, dl, VT,
16533                       DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
16534                                   N00.getOperand(0), N00.getOperand(1)),
16535                       DAG.getConstant(1, VT));
16536  }
16537
16538  // Optimize vectors in AVX mode:
16539  //
16540  //   v8i16 -> v8i32
16541  //   Use vpunpcklwd for 4 lower elements  v8i16 -> v4i32.
16542  //   Use vpunpckhwd for 4 upper elements  v8i16 -> v4i32.
16543  //   Concat upper and lower parts.
16544  //
16545  //   v4i32 -> v4i64
16546  //   Use vpunpckldq for 4 lower elements  v4i32 -> v2i64.
16547  //   Use vpunpckhdq for 4 upper elements  v4i32 -> v2i64.
16548  //   Concat upper and lower parts.
16549  //
16550  if (!DCI.isBeforeLegalizeOps())
16551    return SDValue();
16552
16553  if (!Subtarget->hasAVX())
16554    return SDValue();
16555
16556  if (((VT == MVT::v8i32) && (OpVT == MVT::v8i16)) ||
16557      ((VT == MVT::v4i64) && (OpVT == MVT::v4i32)))  {
16558
16559    if (Subtarget->hasAVX2())
16560      return DAG.getNode(X86ISD::VZEXT_MOVL, dl, VT, N0);
16561
16562    SDValue ZeroVec = getZeroVector(OpVT, Subtarget, DAG, dl);
16563    SDValue OpLo = getUnpackl(DAG, dl, OpVT, N0, ZeroVec);
16564    SDValue OpHi = getUnpackh(DAG, dl, OpVT, N0, ZeroVec);
16565
16566    EVT HVT = EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(),
16567                               VT.getVectorNumElements()/2);
16568
16569    OpLo = DAG.getNode(ISD::BITCAST, dl, HVT, OpLo);
16570    OpHi = DAG.getNode(ISD::BITCAST, dl, HVT, OpHi);
16571
16572    return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
16573  }
16574
16575  return SDValue();
16576}
16577
16578// Optimize x == -y --> x+y == 0
16579//          x != -y --> x+y != 0
16580static SDValue PerformISDSETCCCombine(SDNode *N, SelectionDAG &DAG) {
16581  ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
16582  SDValue LHS = N->getOperand(0);
16583  SDValue RHS = N->getOperand(1);
16584
16585  if ((CC == ISD::SETNE || CC == ISD::SETEQ) && LHS.getOpcode() == ISD::SUB)
16586    if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(LHS.getOperand(0)))
16587      if (C->getAPIntValue() == 0 && LHS.hasOneUse()) {
16588        SDValue addV = DAG.getNode(ISD::ADD, N->getDebugLoc(),
16589                                   LHS.getValueType(), RHS, LHS.getOperand(1));
16590        return DAG.getSetCC(N->getDebugLoc(), N->getValueType(0),
16591                            addV, DAG.getConstant(0, addV.getValueType()), CC);
16592      }
16593  if ((CC == ISD::SETNE || CC == ISD::SETEQ) && RHS.getOpcode() == ISD::SUB)
16594    if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS.getOperand(0)))
16595      if (C->getAPIntValue() == 0 && RHS.hasOneUse()) {
16596        SDValue addV = DAG.getNode(ISD::ADD, N->getDebugLoc(),
16597                                   RHS.getValueType(), LHS, RHS.getOperand(1));
16598        return DAG.getSetCC(N->getDebugLoc(), N->getValueType(0),
16599                            addV, DAG.getConstant(0, addV.getValueType()), CC);
16600      }
16601  return SDValue();
16602}
16603
16604// Helper function of PerformSETCCCombine. It is to materialize "setb reg"
16605// as "sbb reg,reg", since it can be extended without zext and produces
16606// an all-ones bit which is more useful than 0/1 in some cases.
16607static SDValue MaterializeSETB(DebugLoc DL, SDValue EFLAGS, SelectionDAG &DAG) {
16608  return DAG.getNode(ISD::AND, DL, MVT::i8,
16609                     DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
16610                                 DAG.getConstant(X86::COND_B, MVT::i8), EFLAGS),
16611                     DAG.getConstant(1, MVT::i8));
16612}
16613
16614// Optimize  RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
16615static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG,
16616                                   TargetLowering::DAGCombinerInfo &DCI,
16617                                   const X86Subtarget *Subtarget) {
16618  DebugLoc DL = N->getDebugLoc();
16619  X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(0));
16620  SDValue EFLAGS = N->getOperand(1);
16621
16622  if (CC == X86::COND_A) {
16623    // Try to convert COND_A into COND_B in an attempt to facilitate
16624    // materializing "setb reg".
16625    //
16626    // Do not flip "e > c", where "c" is a constant, because Cmp instruction
16627    // cannot take an immediate as its first operand.
16628    //
16629    if (EFLAGS.getOpcode() == X86ISD::SUB && EFLAGS.hasOneUse() &&
16630        EFLAGS.getValueType().isInteger() &&
16631        !isa<ConstantSDNode>(EFLAGS.getOperand(1))) {
16632      SDValue NewSub = DAG.getNode(X86ISD::SUB, EFLAGS.getDebugLoc(),
16633                                   EFLAGS.getNode()->getVTList(),
16634                                   EFLAGS.getOperand(1), EFLAGS.getOperand(0));
16635      SDValue NewEFLAGS = SDValue(NewSub.getNode(), EFLAGS.getResNo());
16636      return MaterializeSETB(DL, NewEFLAGS, DAG);
16637    }
16638  }
16639
16640  // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
16641  // a zext and produces an all-ones bit which is more useful than 0/1 in some
16642  // cases.
16643  if (CC == X86::COND_B)
16644    return MaterializeSETB(DL, EFLAGS, DAG);
16645
16646  SDValue Flags;
16647
16648  Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
16649  if (Flags.getNode()) {
16650    SDValue Cond = DAG.getConstant(CC, MVT::i8);
16651    return DAG.getNode(X86ISD::SETCC, DL, N->getVTList(), Cond, Flags);
16652  }
16653
16654  return SDValue();
16655}
16656
16657// Optimize branch condition evaluation.
16658//
16659static SDValue PerformBrCondCombine(SDNode *N, SelectionDAG &DAG,
16660                                    TargetLowering::DAGCombinerInfo &DCI,
16661                                    const X86Subtarget *Subtarget) {
16662  DebugLoc DL = N->getDebugLoc();
16663  SDValue Chain = N->getOperand(0);
16664  SDValue Dest = N->getOperand(1);
16665  SDValue EFLAGS = N->getOperand(3);
16666  X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(2));
16667
16668  SDValue Flags;
16669
16670  Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
16671  if (Flags.getNode()) {
16672    SDValue Cond = DAG.getConstant(CC, MVT::i8);
16673    return DAG.getNode(X86ISD::BRCOND, DL, N->getVTList(), Chain, Dest, Cond,
16674                       Flags);
16675  }
16676
16677  return SDValue();
16678}
16679
16680static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
16681                                        const X86TargetLowering *XTLI) {
16682  SDValue Op0 = N->getOperand(0);
16683  EVT InVT = Op0->getValueType(0);
16684
16685  // SINT_TO_FP(v4i8) -> SINT_TO_FP(SEXT(v4i8 to v4i32))
16686  if (InVT == MVT::v8i8 || InVT == MVT::v4i8) {
16687    DebugLoc dl = N->getDebugLoc();
16688    MVT DstVT = InVT == MVT::v4i8 ? MVT::v4i32 : MVT::v8i32;
16689    SDValue P = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Op0);
16690    return DAG.getNode(ISD::SINT_TO_FP, dl, N->getValueType(0), P);
16691  }
16692
16693  // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
16694  // a 32-bit target where SSE doesn't support i64->FP operations.
16695  if (Op0.getOpcode() == ISD::LOAD) {
16696    LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
16697    EVT VT = Ld->getValueType(0);
16698    if (!Ld->isVolatile() && !N->getValueType(0).isVector() &&
16699        ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
16700        !XTLI->getSubtarget()->is64Bit() &&
16701        !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
16702      SDValue FILDChain = XTLI->BuildFILD(SDValue(N, 0), Ld->getValueType(0),
16703                                          Ld->getChain(), Op0, DAG);
16704      DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
16705      return FILDChain;
16706    }
16707  }
16708  return SDValue();
16709}
16710
16711// Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
16712static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
16713                                 X86TargetLowering::DAGCombinerInfo &DCI) {
16714  // If the LHS and RHS of the ADC node are zero, then it can't overflow and
16715  // the result is either zero or one (depending on the input carry bit).
16716  // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
16717  if (X86::isZeroNode(N->getOperand(0)) &&
16718      X86::isZeroNode(N->getOperand(1)) &&
16719      // We don't have a good way to replace an EFLAGS use, so only do this when
16720      // dead right now.
16721      SDValue(N, 1).use_empty()) {
16722    DebugLoc DL = N->getDebugLoc();
16723    EVT VT = N->getValueType(0);
16724    SDValue CarryOut = DAG.getConstant(0, N->getValueType(1));
16725    SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
16726                               DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
16727                                           DAG.getConstant(X86::COND_B,MVT::i8),
16728                                           N->getOperand(2)),
16729                               DAG.getConstant(1, VT));
16730    return DCI.CombineTo(N, Res1, CarryOut);
16731  }
16732
16733  return SDValue();
16734}
16735
16736// fold (add Y, (sete  X, 0)) -> adc  0, Y
16737//      (add Y, (setne X, 0)) -> sbb -1, Y
16738//      (sub (sete  X, 0), Y) -> sbb  0, Y
16739//      (sub (setne X, 0), Y) -> adc -1, Y
16740static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
16741  DebugLoc DL = N->getDebugLoc();
16742
16743  // Look through ZExts.
16744  SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
16745  if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
16746    return SDValue();
16747
16748  SDValue SetCC = Ext.getOperand(0);
16749  if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
16750    return SDValue();
16751
16752  X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
16753  if (CC != X86::COND_E && CC != X86::COND_NE)
16754    return SDValue();
16755
16756  SDValue Cmp = SetCC.getOperand(1);
16757  if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
16758      !X86::isZeroNode(Cmp.getOperand(1)) ||
16759      !Cmp.getOperand(0).getValueType().isInteger())
16760    return SDValue();
16761
16762  SDValue CmpOp0 = Cmp.getOperand(0);
16763  SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
16764                               DAG.getConstant(1, CmpOp0.getValueType()));
16765
16766  SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
16767  if (CC == X86::COND_NE)
16768    return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
16769                       DL, OtherVal.getValueType(), OtherVal,
16770                       DAG.getConstant(-1ULL, OtherVal.getValueType()), NewCmp);
16771  return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
16772                     DL, OtherVal.getValueType(), OtherVal,
16773                     DAG.getConstant(0, OtherVal.getValueType()), NewCmp);
16774}
16775
16776/// PerformADDCombine - Do target-specific dag combines on integer adds.
16777static SDValue PerformAddCombine(SDNode *N, SelectionDAG &DAG,
16778                                 const X86Subtarget *Subtarget) {
16779  EVT VT = N->getValueType(0);
16780  SDValue Op0 = N->getOperand(0);
16781  SDValue Op1 = N->getOperand(1);
16782
16783  // Try to synthesize horizontal adds from adds of shuffles.
16784  if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
16785       (Subtarget->hasAVX2() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
16786      isHorizontalBinOp(Op0, Op1, true))
16787    return DAG.getNode(X86ISD::HADD, N->getDebugLoc(), VT, Op0, Op1);
16788
16789  return OptimizeConditionalInDecrement(N, DAG);
16790}
16791
16792static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG,
16793                                 const X86Subtarget *Subtarget) {
16794  SDValue Op0 = N->getOperand(0);
16795  SDValue Op1 = N->getOperand(1);
16796
16797  // X86 can't encode an immediate LHS of a sub. See if we can push the
16798  // negation into a preceding instruction.
16799  if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
16800    // If the RHS of the sub is a XOR with one use and a constant, invert the
16801    // immediate. Then add one to the LHS of the sub so we can turn
16802    // X-Y -> X+~Y+1, saving one register.
16803    if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
16804        isa<ConstantSDNode>(Op1.getOperand(1))) {
16805      APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
16806      EVT VT = Op0.getValueType();
16807      SDValue NewXor = DAG.getNode(ISD::XOR, Op1.getDebugLoc(), VT,
16808                                   Op1.getOperand(0),
16809                                   DAG.getConstant(~XorC, VT));
16810      return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, NewXor,
16811                         DAG.getConstant(C->getAPIntValue()+1, VT));
16812    }
16813  }
16814
16815  // Try to synthesize horizontal adds from adds of shuffles.
16816  EVT VT = N->getValueType(0);
16817  if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
16818       (Subtarget->hasAVX2() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
16819      isHorizontalBinOp(Op0, Op1, true))
16820    return DAG.getNode(X86ISD::HSUB, N->getDebugLoc(), VT, Op0, Op1);
16821
16822  return OptimizeConditionalInDecrement(N, DAG);
16823}
16824
16825/// performVZEXTCombine - Performs build vector combines
16826static SDValue performVZEXTCombine(SDNode *N, SelectionDAG &DAG,
16827                                        TargetLowering::DAGCombinerInfo &DCI,
16828                                        const X86Subtarget *Subtarget) {
16829  // (vzext (bitcast (vzext (x)) -> (vzext x)
16830  SDValue In = N->getOperand(0);
16831  while (In.getOpcode() == ISD::BITCAST)
16832    In = In.getOperand(0);
16833
16834  if (In.getOpcode() != X86ISD::VZEXT)
16835    return SDValue();
16836
16837  return DAG.getNode(X86ISD::VZEXT, N->getDebugLoc(), N->getValueType(0), In.getOperand(0));
16838}
16839
16840SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
16841                                             DAGCombinerInfo &DCI) const {
16842  SelectionDAG &DAG = DCI.DAG;
16843  switch (N->getOpcode()) {
16844  default: break;
16845  case ISD::EXTRACT_VECTOR_ELT:
16846    return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, DCI);
16847  case ISD::VSELECT:
16848  case ISD::SELECT:         return PerformSELECTCombine(N, DAG, DCI, Subtarget);
16849  case X86ISD::CMOV:        return PerformCMOVCombine(N, DAG, DCI, Subtarget);
16850  case ISD::ADD:            return PerformAddCombine(N, DAG, Subtarget);
16851  case ISD::SUB:            return PerformSubCombine(N, DAG, Subtarget);
16852  case X86ISD::ADC:         return PerformADCCombine(N, DAG, DCI);
16853  case ISD::MUL:            return PerformMulCombine(N, DAG, DCI);
16854  case ISD::SHL:
16855  case ISD::SRA:
16856  case ISD::SRL:            return PerformShiftCombine(N, DAG, DCI, Subtarget);
16857  case ISD::AND:            return PerformAndCombine(N, DAG, DCI, Subtarget);
16858  case ISD::OR:             return PerformOrCombine(N, DAG, DCI, Subtarget);
16859  case ISD::XOR:            return PerformXorCombine(N, DAG, DCI, Subtarget);
16860  case ISD::LOAD:           return PerformLOADCombine(N, DAG, DCI, Subtarget);
16861  case ISD::STORE:          return PerformSTORECombine(N, DAG, Subtarget);
16862  case ISD::SINT_TO_FP:     return PerformSINT_TO_FPCombine(N, DAG, this);
16863  case ISD::FADD:           return PerformFADDCombine(N, DAG, Subtarget);
16864  case ISD::FSUB:           return PerformFSUBCombine(N, DAG, Subtarget);
16865  case X86ISD::FXOR:
16866  case X86ISD::FOR:         return PerformFORCombine(N, DAG);
16867  case X86ISD::FMIN:
16868  case X86ISD::FMAX:        return PerformFMinFMaxCombine(N, DAG);
16869  case X86ISD::FAND:        return PerformFANDCombine(N, DAG);
16870  case X86ISD::BT:          return PerformBTCombine(N, DAG, DCI);
16871  case X86ISD::VZEXT_MOVL:  return PerformVZEXT_MOVLCombine(N, DAG);
16872  case ISD::ANY_EXTEND:
16873  case ISD::ZERO_EXTEND:    return PerformZExtCombine(N, DAG, DCI, Subtarget);
16874  case ISD::SIGN_EXTEND:    return PerformSExtCombine(N, DAG, DCI, Subtarget);
16875  case ISD::TRUNCATE:       return PerformTruncateCombine(N, DAG,DCI,Subtarget);
16876  case ISD::SETCC:          return PerformISDSETCCCombine(N, DAG);
16877  case X86ISD::SETCC:       return PerformSETCCCombine(N, DAG, DCI, Subtarget);
16878  case X86ISD::BRCOND:      return PerformBrCondCombine(N, DAG, DCI, Subtarget);
16879  case X86ISD::VZEXT:       return performVZEXTCombine(N, DAG, DCI, Subtarget);
16880  case X86ISD::SHUFP:       // Handle all target specific shuffles
16881  case X86ISD::PALIGN:
16882  case X86ISD::UNPCKH:
16883  case X86ISD::UNPCKL:
16884  case X86ISD::MOVHLPS:
16885  case X86ISD::MOVLHPS:
16886  case X86ISD::PSHUFD:
16887  case X86ISD::PSHUFHW:
16888  case X86ISD::PSHUFLW:
16889  case X86ISD::MOVSS:
16890  case X86ISD::MOVSD:
16891  case X86ISD::VPERMILP:
16892  case X86ISD::VPERM2X128:
16893  case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
16894  case ISD::FMA:            return PerformFMACombine(N, DAG, Subtarget);
16895  }
16896
16897  return SDValue();
16898}
16899
16900/// isTypeDesirableForOp - Return true if the target has native support for
16901/// the specified value type and it is 'desirable' to use the type for the
16902/// given node type. e.g. On x86 i16 is legal, but undesirable since i16
16903/// instruction encodings are longer and some i16 instructions are slow.
16904bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
16905  if (!isTypeLegal(VT))
16906    return false;
16907  if (VT != MVT::i16)
16908    return true;
16909
16910  switch (Opc) {
16911  default:
16912    return true;
16913  case ISD::LOAD:
16914  case ISD::SIGN_EXTEND:
16915  case ISD::ZERO_EXTEND:
16916  case ISD::ANY_EXTEND:
16917  case ISD::SHL:
16918  case ISD::SRL:
16919  case ISD::SUB:
16920  case ISD::ADD:
16921  case ISD::MUL:
16922  case ISD::AND:
16923  case ISD::OR:
16924  case ISD::XOR:
16925    return false;
16926  }
16927}
16928
16929/// IsDesirableToPromoteOp - This method query the target whether it is
16930/// beneficial for dag combiner to promote the specified node. If true, it
16931/// should return the desired promotion type by reference.
16932bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
16933  EVT VT = Op.getValueType();
16934  if (VT != MVT::i16)
16935    return false;
16936
16937  bool Promote = false;
16938  bool Commute = false;
16939  switch (Op.getOpcode()) {
16940  default: break;
16941  case ISD::LOAD: {
16942    LoadSDNode *LD = cast<LoadSDNode>(Op);
16943    // If the non-extending load has a single use and it's not live out, then it
16944    // might be folded.
16945    if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
16946                                                     Op.hasOneUse()*/) {
16947      for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
16948             UE = Op.getNode()->use_end(); UI != UE; ++UI) {
16949        // The only case where we'd want to promote LOAD (rather then it being
16950        // promoted as an operand is when it's only use is liveout.
16951        if (UI->getOpcode() != ISD::CopyToReg)
16952          return false;
16953      }
16954    }
16955    Promote = true;
16956    break;
16957  }
16958  case ISD::SIGN_EXTEND:
16959  case ISD::ZERO_EXTEND:
16960  case ISD::ANY_EXTEND:
16961    Promote = true;
16962    break;
16963  case ISD::SHL:
16964  case ISD::SRL: {
16965    SDValue N0 = Op.getOperand(0);
16966    // Look out for (store (shl (load), x)).
16967    if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
16968      return false;
16969    Promote = true;
16970    break;
16971  }
16972  case ISD::ADD:
16973  case ISD::MUL:
16974  case ISD::AND:
16975  case ISD::OR:
16976  case ISD::XOR:
16977    Commute = true;
16978    // fallthrough
16979  case ISD::SUB: {
16980    SDValue N0 = Op.getOperand(0);
16981    SDValue N1 = Op.getOperand(1);
16982    if (!Commute && MayFoldLoad(N1))
16983      return false;
16984    // Avoid disabling potential load folding opportunities.
16985    if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
16986      return false;
16987    if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
16988      return false;
16989    Promote = true;
16990  }
16991  }
16992
16993  PVT = MVT::i32;
16994  return Promote;
16995}
16996
16997//===----------------------------------------------------------------------===//
16998//                           X86 Inline Assembly Support
16999//===----------------------------------------------------------------------===//
17000
17001namespace {
17002  // Helper to match a string separated by whitespace.
17003  bool matchAsmImpl(StringRef s, ArrayRef<const StringRef *> args) {
17004    s = s.substr(s.find_first_not_of(" \t")); // Skip leading whitespace.
17005
17006    for (unsigned i = 0, e = args.size(); i != e; ++i) {
17007      StringRef piece(*args[i]);
17008      if (!s.startswith(piece)) // Check if the piece matches.
17009        return false;
17010
17011      s = s.substr(piece.size());
17012      StringRef::size_type pos = s.find_first_not_of(" \t");
17013      if (pos == 0) // We matched a prefix.
17014        return false;
17015
17016      s = s.substr(pos);
17017    }
17018
17019    return s.empty();
17020  }
17021  const VariadicFunction1<bool, StringRef, StringRef, matchAsmImpl> matchAsm={};
17022}
17023
17024bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
17025  InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
17026
17027  std::string AsmStr = IA->getAsmString();
17028
17029  IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
17030  if (!Ty || Ty->getBitWidth() % 16 != 0)
17031    return false;
17032
17033  // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
17034  SmallVector<StringRef, 4> AsmPieces;
17035  SplitString(AsmStr, AsmPieces, ";\n");
17036
17037  switch (AsmPieces.size()) {
17038  default: return false;
17039  case 1:
17040    // FIXME: this should verify that we are targeting a 486 or better.  If not,
17041    // we will turn this bswap into something that will be lowered to logical
17042    // ops instead of emitting the bswap asm.  For now, we don't support 486 or
17043    // lower so don't worry about this.
17044    // bswap $0
17045    if (matchAsm(AsmPieces[0], "bswap", "$0") ||
17046        matchAsm(AsmPieces[0], "bswapl", "$0") ||
17047        matchAsm(AsmPieces[0], "bswapq", "$0") ||
17048        matchAsm(AsmPieces[0], "bswap", "${0:q}") ||
17049        matchAsm(AsmPieces[0], "bswapl", "${0:q}") ||
17050        matchAsm(AsmPieces[0], "bswapq", "${0:q}")) {
17051      // No need to check constraints, nothing other than the equivalent of
17052      // "=r,0" would be valid here.
17053      return IntrinsicLowering::LowerToByteSwap(CI);
17054    }
17055
17056    // rorw $$8, ${0:w}  -->  llvm.bswap.i16
17057    if (CI->getType()->isIntegerTy(16) &&
17058        IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
17059        (matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") ||
17060         matchAsm(AsmPieces[0], "rolw", "$$8,", "${0:w}"))) {
17061      AsmPieces.clear();
17062      const std::string &ConstraintsStr = IA->getConstraintString();
17063      SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
17064      std::sort(AsmPieces.begin(), AsmPieces.end());
17065      if (AsmPieces.size() == 4 &&
17066          AsmPieces[0] == "~{cc}" &&
17067          AsmPieces[1] == "~{dirflag}" &&
17068          AsmPieces[2] == "~{flags}" &&
17069          AsmPieces[3] == "~{fpsr}")
17070      return IntrinsicLowering::LowerToByteSwap(CI);
17071    }
17072    break;
17073  case 3:
17074    if (CI->getType()->isIntegerTy(32) &&
17075        IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
17076        matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") &&
17077        matchAsm(AsmPieces[1], "rorl", "$$16,", "$0") &&
17078        matchAsm(AsmPieces[2], "rorw", "$$8,", "${0:w}")) {
17079      AsmPieces.clear();
17080      const std::string &ConstraintsStr = IA->getConstraintString();
17081      SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
17082      std::sort(AsmPieces.begin(), AsmPieces.end());
17083      if (AsmPieces.size() == 4 &&
17084          AsmPieces[0] == "~{cc}" &&
17085          AsmPieces[1] == "~{dirflag}" &&
17086          AsmPieces[2] == "~{flags}" &&
17087          AsmPieces[3] == "~{fpsr}")
17088        return IntrinsicLowering::LowerToByteSwap(CI);
17089    }
17090
17091    if (CI->getType()->isIntegerTy(64)) {
17092      InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
17093      if (Constraints.size() >= 2 &&
17094          Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
17095          Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
17096        // bswap %eax / bswap %edx / xchgl %eax, %edx  -> llvm.bswap.i64
17097        if (matchAsm(AsmPieces[0], "bswap", "%eax") &&
17098            matchAsm(AsmPieces[1], "bswap", "%edx") &&
17099            matchAsm(AsmPieces[2], "xchgl", "%eax,", "%edx"))
17100          return IntrinsicLowering::LowerToByteSwap(CI);
17101      }
17102    }
17103    break;
17104  }
17105  return false;
17106}
17107
17108
17109
17110/// getConstraintType - Given a constraint letter, return the type of
17111/// constraint it is for this target.
17112X86TargetLowering::ConstraintType
17113X86TargetLowering::getConstraintType(const std::string &Constraint) const {
17114  if (Constraint.size() == 1) {
17115    switch (Constraint[0]) {
17116    case 'R':
17117    case 'q':
17118    case 'Q':
17119    case 'f':
17120    case 't':
17121    case 'u':
17122    case 'y':
17123    case 'x':
17124    case 'Y':
17125    case 'l':
17126      return C_RegisterClass;
17127    case 'a':
17128    case 'b':
17129    case 'c':
17130    case 'd':
17131    case 'S':
17132    case 'D':
17133    case 'A':
17134      return C_Register;
17135    case 'I':
17136    case 'J':
17137    case 'K':
17138    case 'L':
17139    case 'M':
17140    case 'N':
17141    case 'G':
17142    case 'C':
17143    case 'e':
17144    case 'Z':
17145      return C_Other;
17146    default:
17147      break;
17148    }
17149  }
17150  return TargetLowering::getConstraintType(Constraint);
17151}
17152
17153/// Examine constraint type and operand type and determine a weight value.
17154/// This object must already have been set up with the operand type
17155/// and the current alternative constraint selected.
17156TargetLowering::ConstraintWeight
17157  X86TargetLowering::getSingleConstraintMatchWeight(
17158    AsmOperandInfo &info, const char *constraint) const {
17159  ConstraintWeight weight = CW_Invalid;
17160  Value *CallOperandVal = info.CallOperandVal;
17161    // If we don't have a value, we can't do a match,
17162    // but allow it at the lowest weight.
17163  if (CallOperandVal == NULL)
17164    return CW_Default;
17165  Type *type = CallOperandVal->getType();
17166  // Look at the constraint type.
17167  switch (*constraint) {
17168  default:
17169    weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
17170  case 'R':
17171  case 'q':
17172  case 'Q':
17173  case 'a':
17174  case 'b':
17175  case 'c':
17176  case 'd':
17177  case 'S':
17178  case 'D':
17179  case 'A':
17180    if (CallOperandVal->getType()->isIntegerTy())
17181      weight = CW_SpecificReg;
17182    break;
17183  case 'f':
17184  case 't':
17185  case 'u':
17186      if (type->isFloatingPointTy())
17187        weight = CW_SpecificReg;
17188      break;
17189  case 'y':
17190      if (type->isX86_MMXTy() && Subtarget->hasMMX())
17191        weight = CW_SpecificReg;
17192      break;
17193  case 'x':
17194  case 'Y':
17195    if (((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasSSE1()) ||
17196        ((type->getPrimitiveSizeInBits() == 256) && Subtarget->hasAVX()))
17197      weight = CW_Register;
17198    break;
17199  case 'I':
17200    if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
17201      if (C->getZExtValue() <= 31)
17202        weight = CW_Constant;
17203    }
17204    break;
17205  case 'J':
17206    if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
17207      if (C->getZExtValue() <= 63)
17208        weight = CW_Constant;
17209    }
17210    break;
17211  case 'K':
17212    if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
17213      if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
17214        weight = CW_Constant;
17215    }
17216    break;
17217  case 'L':
17218    if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
17219      if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
17220        weight = CW_Constant;
17221    }
17222    break;
17223  case 'M':
17224    if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
17225      if (C->getZExtValue() <= 3)
17226        weight = CW_Constant;
17227    }
17228    break;
17229  case 'N':
17230    if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
17231      if (C->getZExtValue() <= 0xff)
17232        weight = CW_Constant;
17233    }
17234    break;
17235  case 'G':
17236  case 'C':
17237    if (dyn_cast<ConstantFP>(CallOperandVal)) {
17238      weight = CW_Constant;
17239    }
17240    break;
17241  case 'e':
17242    if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
17243      if ((C->getSExtValue() >= -0x80000000LL) &&
17244          (C->getSExtValue() <= 0x7fffffffLL))
17245        weight = CW_Constant;
17246    }
17247    break;
17248  case 'Z':
17249    if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
17250      if (C->getZExtValue() <= 0xffffffff)
17251        weight = CW_Constant;
17252    }
17253    break;
17254  }
17255  return weight;
17256}
17257
17258/// LowerXConstraint - try to replace an X constraint, which matches anything,
17259/// with another that has more specific requirements based on the type of the
17260/// corresponding operand.
17261const char *X86TargetLowering::
17262LowerXConstraint(EVT ConstraintVT) const {
17263  // FP X constraints get lowered to SSE1/2 registers if available, otherwise
17264  // 'f' like normal targets.
17265  if (ConstraintVT.isFloatingPoint()) {
17266    if (Subtarget->hasSSE2())
17267      return "Y";
17268    if (Subtarget->hasSSE1())
17269      return "x";
17270  }
17271
17272  return TargetLowering::LowerXConstraint(ConstraintVT);
17273}
17274
17275/// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
17276/// vector.  If it is invalid, don't add anything to Ops.
17277void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
17278                                                     std::string &Constraint,
17279                                                     std::vector<SDValue>&Ops,
17280                                                     SelectionDAG &DAG) const {
17281  SDValue Result(0, 0);
17282
17283  // Only support length 1 constraints for now.
17284  if (Constraint.length() > 1) return;
17285
17286  char ConstraintLetter = Constraint[0];
17287  switch (ConstraintLetter) {
17288  default: break;
17289  case 'I':
17290    if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
17291      if (C->getZExtValue() <= 31) {
17292        Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
17293        break;
17294      }
17295    }
17296    return;
17297  case 'J':
17298    if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
17299      if (C->getZExtValue() <= 63) {
17300        Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
17301        break;
17302      }
17303    }
17304    return;
17305  case 'K':
17306    if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
17307      if (isInt<8>(C->getSExtValue())) {
17308        Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
17309        break;
17310      }
17311    }
17312    return;
17313  case 'N':
17314    if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
17315      if (C->getZExtValue() <= 255) {
17316        Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
17317        break;
17318      }
17319    }
17320    return;
17321  case 'e': {
17322    // 32-bit signed value
17323    if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
17324      if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
17325                                           C->getSExtValue())) {
17326        // Widen to 64 bits here to get it sign extended.
17327        Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
17328        break;
17329      }
17330    // FIXME gcc accepts some relocatable values here too, but only in certain
17331    // memory models; it's complicated.
17332    }
17333    return;
17334  }
17335  case 'Z': {
17336    // 32-bit unsigned value
17337    if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
17338      if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
17339                                           C->getZExtValue())) {
17340        Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
17341        break;
17342      }
17343    }
17344    // FIXME gcc accepts some relocatable values here too, but only in certain
17345    // memory models; it's complicated.
17346    return;
17347  }
17348  case 'i': {
17349    // Literal immediates are always ok.
17350    if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
17351      // Widen to 64 bits here to get it sign extended.
17352      Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
17353      break;
17354    }
17355
17356    // In any sort of PIC mode addresses need to be computed at runtime by
17357    // adding in a register or some sort of table lookup.  These can't
17358    // be used as immediates.
17359    if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
17360      return;
17361
17362    // If we are in non-pic codegen mode, we allow the address of a global (with
17363    // an optional displacement) to be used with 'i'.
17364    GlobalAddressSDNode *GA = 0;
17365    int64_t Offset = 0;
17366
17367    // Match either (GA), (GA+C), (GA+C1+C2), etc.
17368    while (1) {
17369      if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
17370        Offset += GA->getOffset();
17371        break;
17372      } else if (Op.getOpcode() == ISD::ADD) {
17373        if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
17374          Offset += C->getZExtValue();
17375          Op = Op.getOperand(0);
17376          continue;
17377        }
17378      } else if (Op.getOpcode() == ISD::SUB) {
17379        if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
17380          Offset += -C->getZExtValue();
17381          Op = Op.getOperand(0);
17382          continue;
17383        }
17384      }
17385
17386      // Otherwise, this isn't something we can handle, reject it.
17387      return;
17388    }
17389
17390    const GlobalValue *GV = GA->getGlobal();
17391    // If we require an extra load to get this address, as in PIC mode, we
17392    // can't accept it.
17393    if (isGlobalStubReference(Subtarget->ClassifyGlobalReference(GV,
17394                                                        getTargetMachine())))
17395      return;
17396
17397    Result = DAG.getTargetGlobalAddress(GV, Op.getDebugLoc(),
17398                                        GA->getValueType(0), Offset);
17399    break;
17400  }
17401  }
17402
17403  if (Result.getNode()) {
17404    Ops.push_back(Result);
17405    return;
17406  }
17407  return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
17408}
17409
17410std::pair<unsigned, const TargetRegisterClass*>
17411X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
17412                                                EVT VT) const {
17413  // First, see if this is a constraint that directly corresponds to an LLVM
17414  // register class.
17415  if (Constraint.size() == 1) {
17416    // GCC Constraint Letters
17417    switch (Constraint[0]) {
17418    default: break;
17419      // TODO: Slight differences here in allocation order and leaving
17420      // RIP in the class. Do they matter any more here than they do
17421      // in the normal allocation?
17422    case 'q':   // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
17423      if (Subtarget->is64Bit()) {
17424        if (VT == MVT::i32 || VT == MVT::f32)
17425          return std::make_pair(0U, &X86::GR32RegClass);
17426        if (VT == MVT::i16)
17427          return std::make_pair(0U, &X86::GR16RegClass);
17428        if (VT == MVT::i8 || VT == MVT::i1)
17429          return std::make_pair(0U, &X86::GR8RegClass);
17430        if (VT == MVT::i64 || VT == MVT::f64)
17431          return std::make_pair(0U, &X86::GR64RegClass);
17432        break;
17433      }
17434      // 32-bit fallthrough
17435    case 'Q':   // Q_REGS
17436      if (VT == MVT::i32 || VT == MVT::f32)
17437        return std::make_pair(0U, &X86::GR32_ABCDRegClass);
17438      if (VT == MVT::i16)
17439        return std::make_pair(0U, &X86::GR16_ABCDRegClass);
17440      if (VT == MVT::i8 || VT == MVT::i1)
17441        return std::make_pair(0U, &X86::GR8_ABCD_LRegClass);
17442      if (VT == MVT::i64)
17443        return std::make_pair(0U, &X86::GR64_ABCDRegClass);
17444      break;
17445    case 'r':   // GENERAL_REGS
17446    case 'l':   // INDEX_REGS
17447      if (VT == MVT::i8 || VT == MVT::i1)
17448        return std::make_pair(0U, &X86::GR8RegClass);
17449      if (VT == MVT::i16)
17450        return std::make_pair(0U, &X86::GR16RegClass);
17451      if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
17452        return std::make_pair(0U, &X86::GR32RegClass);
17453      return std::make_pair(0U, &X86::GR64RegClass);
17454    case 'R':   // LEGACY_REGS
17455      if (VT == MVT::i8 || VT == MVT::i1)
17456        return std::make_pair(0U, &X86::GR8_NOREXRegClass);
17457      if (VT == MVT::i16)
17458        return std::make_pair(0U, &X86::GR16_NOREXRegClass);
17459      if (VT == MVT::i32 || !Subtarget->is64Bit())
17460        return std::make_pair(0U, &X86::GR32_NOREXRegClass);
17461      return std::make_pair(0U, &X86::GR64_NOREXRegClass);
17462    case 'f':  // FP Stack registers.
17463      // If SSE is enabled for this VT, use f80 to ensure the isel moves the
17464      // value to the correct fpstack register class.
17465      if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
17466        return std::make_pair(0U, &X86::RFP32RegClass);
17467      if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
17468        return std::make_pair(0U, &X86::RFP64RegClass);
17469      return std::make_pair(0U, &X86::RFP80RegClass);
17470    case 'y':   // MMX_REGS if MMX allowed.
17471      if (!Subtarget->hasMMX()) break;
17472      return std::make_pair(0U, &X86::VR64RegClass);
17473    case 'Y':   // SSE_REGS if SSE2 allowed
17474      if (!Subtarget->hasSSE2()) break;
17475      // FALL THROUGH.
17476    case 'x':   // SSE_REGS if SSE1 allowed or AVX_REGS if AVX allowed
17477      if (!Subtarget->hasSSE1()) break;
17478
17479      switch (VT.getSimpleVT().SimpleTy) {
17480      default: break;
17481      // Scalar SSE types.
17482      case MVT::f32:
17483      case MVT::i32:
17484        return std::make_pair(0U, &X86::FR32RegClass);
17485      case MVT::f64:
17486      case MVT::i64:
17487        return std::make_pair(0U, &X86::FR64RegClass);
17488      // Vector types.
17489      case MVT::v16i8:
17490      case MVT::v8i16:
17491      case MVT::v4i32:
17492      case MVT::v2i64:
17493      case MVT::v4f32:
17494      case MVT::v2f64:
17495        return std::make_pair(0U, &X86::VR128RegClass);
17496      // AVX types.
17497      case MVT::v32i8:
17498      case MVT::v16i16:
17499      case MVT::v8i32:
17500      case MVT::v4i64:
17501      case MVT::v8f32:
17502      case MVT::v4f64:
17503        return std::make_pair(0U, &X86::VR256RegClass);
17504      }
17505      break;
17506    }
17507  }
17508
17509  // Use the default implementation in TargetLowering to convert the register
17510  // constraint into a member of a register class.
17511  std::pair<unsigned, const TargetRegisterClass*> Res;
17512  Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
17513
17514  // Not found as a standard register?
17515  if (Res.second == 0) {
17516    // Map st(0) -> st(7) -> ST0
17517    if (Constraint.size() == 7 && Constraint[0] == '{' &&
17518        tolower(Constraint[1]) == 's' &&
17519        tolower(Constraint[2]) == 't' &&
17520        Constraint[3] == '(' &&
17521        (Constraint[4] >= '0' && Constraint[4] <= '7') &&
17522        Constraint[5] == ')' &&
17523        Constraint[6] == '}') {
17524
17525      Res.first = X86::ST0+Constraint[4]-'0';
17526      Res.second = &X86::RFP80RegClass;
17527      return Res;
17528    }
17529
17530    // GCC allows "st(0)" to be called just plain "st".
17531    if (StringRef("{st}").equals_lower(Constraint)) {
17532      Res.first = X86::ST0;
17533      Res.second = &X86::RFP80RegClass;
17534      return Res;
17535    }
17536
17537    // flags -> EFLAGS
17538    if (StringRef("{flags}").equals_lower(Constraint)) {
17539      Res.first = X86::EFLAGS;
17540      Res.second = &X86::CCRRegClass;
17541      return Res;
17542    }
17543
17544    // 'A' means EAX + EDX.
17545    if (Constraint == "A") {
17546      Res.first = X86::EAX;
17547      Res.second = &X86::GR32_ADRegClass;
17548      return Res;
17549    }
17550    return Res;
17551  }
17552
17553  // Otherwise, check to see if this is a register class of the wrong value
17554  // type.  For example, we want to map "{ax},i32" -> {eax}, we don't want it to
17555  // turn into {ax},{dx}.
17556  if (Res.second->hasType(VT))
17557    return Res;   // Correct type already, nothing to do.
17558
17559  // All of the single-register GCC register classes map their values onto
17560  // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp".  If we
17561  // really want an 8-bit or 32-bit register, map to the appropriate register
17562  // class and return the appropriate register.
17563  if (Res.second == &X86::GR16RegClass) {
17564    if (VT == MVT::i8) {
17565      unsigned DestReg = 0;
17566      switch (Res.first) {
17567      default: break;
17568      case X86::AX: DestReg = X86::AL; break;
17569      case X86::DX: DestReg = X86::DL; break;
17570      case X86::CX: DestReg = X86::CL; break;
17571      case X86::BX: DestReg = X86::BL; break;
17572      }
17573      if (DestReg) {
17574        Res.first = DestReg;
17575        Res.second = &X86::GR8RegClass;
17576      }
17577    } else if (VT == MVT::i32) {
17578      unsigned DestReg = 0;
17579      switch (Res.first) {
17580      default: break;
17581      case X86::AX: DestReg = X86::EAX; break;
17582      case X86::DX: DestReg = X86::EDX; break;
17583      case X86::CX: DestReg = X86::ECX; break;
17584      case X86::BX: DestReg = X86::EBX; break;
17585      case X86::SI: DestReg = X86::ESI; break;
17586      case X86::DI: DestReg = X86::EDI; break;
17587      case X86::BP: DestReg = X86::EBP; break;
17588      case X86::SP: DestReg = X86::ESP; break;
17589      }
17590      if (DestReg) {
17591        Res.first = DestReg;
17592        Res.second = &X86::GR32RegClass;
17593      }
17594    } else if (VT == MVT::i64) {
17595      unsigned DestReg = 0;
17596      switch (Res.first) {
17597      default: break;
17598      case X86::AX: DestReg = X86::RAX; break;
17599      case X86::DX: DestReg = X86::RDX; break;
17600      case X86::CX: DestReg = X86::RCX; break;
17601      case X86::BX: DestReg = X86::RBX; break;
17602      case X86::SI: DestReg = X86::RSI; break;
17603      case X86::DI: DestReg = X86::RDI; break;
17604      case X86::BP: DestReg = X86::RBP; break;
17605      case X86::SP: DestReg = X86::RSP; break;
17606      }
17607      if (DestReg) {
17608        Res.first = DestReg;
17609        Res.second = &X86::GR64RegClass;
17610      }
17611    }
17612  } else if (Res.second == &X86::FR32RegClass ||
17613             Res.second == &X86::FR64RegClass ||
17614             Res.second == &X86::VR128RegClass) {
17615    // Handle references to XMM physical registers that got mapped into the
17616    // wrong class.  This can happen with constraints like {xmm0} where the
17617    // target independent register mapper will just pick the first match it can
17618    // find, ignoring the required type.
17619
17620    if (VT == MVT::f32 || VT == MVT::i32)
17621      Res.second = &X86::FR32RegClass;
17622    else if (VT == MVT::f64 || VT == MVT::i64)
17623      Res.second = &X86::FR64RegClass;
17624    else if (X86::VR128RegClass.hasType(VT))
17625      Res.second = &X86::VR128RegClass;
17626    else if (X86::VR256RegClass.hasType(VT))
17627      Res.second = &X86::VR256RegClass;
17628  }
17629
17630  return Res;
17631}
17632
17633//===----------------------------------------------------------------------===//
17634//
17635// X86 cost model.
17636//
17637//===----------------------------------------------------------------------===//
17638
17639struct X86CostTblEntry {
17640  int ISD;
17641  MVT Type;
17642  unsigned Cost;
17643};
17644
17645static int
17646FindInTable(const X86CostTblEntry *Tbl, unsigned len, int ISD, MVT Ty) {
17647  for (unsigned int i = 0; i < len; ++i)
17648    if (Tbl[i].ISD == ISD && Tbl[i].Type == Ty)
17649      return i;
17650
17651  // Could not find an entry.
17652  return -1;
17653}
17654
17655struct X86TypeConversionCostTblEntry {
17656  int ISD;
17657  MVT Dst;
17658  MVT Src;
17659  unsigned Cost;
17660};
17661
17662static int
17663FindInConvertTable(const X86TypeConversionCostTblEntry *Tbl, unsigned len,
17664                   int ISD, MVT Dst, MVT Src) {
17665  for (unsigned int i = 0; i < len; ++i)
17666    if (Tbl[i].ISD == ISD && Tbl[i].Src == Src && Tbl[i].Dst == Dst)
17667      return i;
17668
17669  // Could not find an entry.
17670  return -1;
17671}
17672
17673unsigned
17674X86VectorTargetTransformInfo::getArithmeticInstrCost(unsigned Opcode,
17675                                                     Type *Ty) const {
17676  // Legalize the type.
17677  std::pair<unsigned, MVT> LT = getTypeLegalizationCost(Ty);
17678
17679  int ISD = InstructionOpcodeToISD(Opcode);
17680  assert(ISD && "Invalid opcode");
17681
17682  const X86Subtarget &ST = TLI->getTargetMachine().getSubtarget<X86Subtarget>();
17683
17684  static const X86CostTblEntry AVX1CostTable[] = {
17685    // We don't have to scalarize unsupported ops. We can issue two half-sized
17686    // operations and we only need to extract the upper YMM half.
17687    // Two ops + 1 extract + 1 insert = 4.
17688    { ISD::MUL,     MVT::v8i32,    4 },
17689    { ISD::SUB,     MVT::v8i32,    4 },
17690    { ISD::ADD,     MVT::v8i32,    4 },
17691    { ISD::MUL,     MVT::v4i64,    4 },
17692    { ISD::SUB,     MVT::v4i64,    4 },
17693    { ISD::ADD,     MVT::v4i64,    4 },
17694    };
17695
17696  // Look for AVX1 lowering tricks.
17697  if (ST.hasAVX()) {
17698    int Idx = FindInTable(AVX1CostTable, array_lengthof(AVX1CostTable), ISD,
17699                          LT.second);
17700    if (Idx != -1)
17701      return LT.first * AVX1CostTable[Idx].Cost;
17702  }
17703  // Fallback to the default implementation.
17704  return VectorTargetTransformImpl::getArithmeticInstrCost(Opcode, Ty);
17705}
17706
17707unsigned
17708X86VectorTargetTransformInfo::getVectorInstrCost(unsigned Opcode, Type *Val,
17709                                                 unsigned Index) const {
17710  assert(Val->isVectorTy() && "This must be a vector type");
17711
17712  if (Index != -1U) {
17713    // Legalize the type.
17714    std::pair<unsigned, MVT> LT = getTypeLegalizationCost(Val);
17715
17716    // This type is legalized to a scalar type.
17717    if (!LT.second.isVector())
17718      return 0;
17719
17720    // The type may be split. Normalize the index to the new type.
17721    unsigned Width = LT.second.getVectorNumElements();
17722    Index = Index % Width;
17723
17724    // Floating point scalars are already located in index #0.
17725    if (Val->getScalarType()->isFloatingPointTy() && Index == 0)
17726      return 0;
17727  }
17728
17729  return VectorTargetTransformImpl::getVectorInstrCost(Opcode, Val, Index);
17730}
17731
17732unsigned X86VectorTargetTransformInfo::getCmpSelInstrCost(unsigned Opcode,
17733                                                          Type *ValTy,
17734                                                          Type *CondTy) const {
17735  // Legalize the type.
17736  std::pair<unsigned, MVT> LT = getTypeLegalizationCost(ValTy);
17737
17738  MVT MTy = LT.second;
17739
17740  int ISD = InstructionOpcodeToISD(Opcode);
17741  assert(ISD && "Invalid opcode");
17742
17743  const X86Subtarget &ST =
17744  TLI->getTargetMachine().getSubtarget<X86Subtarget>();
17745
17746  static const X86CostTblEntry SSE42CostTbl[] = {
17747    { ISD::SETCC,   MVT::v2f64,   1 },
17748    { ISD::SETCC,   MVT::v4f32,   1 },
17749    { ISD::SETCC,   MVT::v2i64,   1 },
17750    { ISD::SETCC,   MVT::v4i32,   1 },
17751    { ISD::SETCC,   MVT::v8i16,   1 },
17752    { ISD::SETCC,   MVT::v16i8,   1 },
17753  };
17754
17755  static const X86CostTblEntry AVX1CostTbl[] = {
17756    { ISD::SETCC,   MVT::v4f64,   1 },
17757    { ISD::SETCC,   MVT::v8f32,   1 },
17758    // AVX1 does not support 8-wide integer compare.
17759    { ISD::SETCC,   MVT::v4i64,   4 },
17760    { ISD::SETCC,   MVT::v8i32,   4 },
17761    { ISD::SETCC,   MVT::v16i16,  4 },
17762    { ISD::SETCC,   MVT::v32i8,   4 },
17763  };
17764
17765  static const X86CostTblEntry AVX2CostTbl[] = {
17766    { ISD::SETCC,   MVT::v4i64,   1 },
17767    { ISD::SETCC,   MVT::v8i32,   1 },
17768    { ISD::SETCC,   MVT::v16i16,  1 },
17769    { ISD::SETCC,   MVT::v32i8,   1 },
17770  };
17771
17772  if (ST.hasSSE42()) {
17773    int Idx = FindInTable(SSE42CostTbl, array_lengthof(SSE42CostTbl), ISD, MTy);
17774    if (Idx != -1)
17775      return LT.first * SSE42CostTbl[Idx].Cost;
17776  }
17777
17778  if (ST.hasAVX()) {
17779    int Idx = FindInTable(AVX1CostTbl, array_lengthof(AVX1CostTbl), ISD, MTy);
17780    if (Idx != -1)
17781      return LT.first * AVX1CostTbl[Idx].Cost;
17782  }
17783
17784  if (ST.hasAVX2()) {
17785    int Idx = FindInTable(AVX2CostTbl, array_lengthof(AVX2CostTbl), ISD, MTy);
17786    if (Idx != -1)
17787      return LT.first * AVX2CostTbl[Idx].Cost;
17788  }
17789
17790  return VectorTargetTransformImpl::getCmpSelInstrCost(Opcode, ValTy, CondTy);
17791}
17792
17793unsigned X86VectorTargetTransformInfo::getCastInstrCost(unsigned Opcode,
17794                                                        Type *Dst,
17795                                                        Type *Src) const {
17796  int ISD = InstructionOpcodeToISD(Opcode);
17797  assert(ISD && "Invalid opcode");
17798
17799  EVT SrcTy = TLI->getValueType(Src);
17800  EVT DstTy = TLI->getValueType(Dst);
17801
17802  if (!SrcTy.isSimple() || !DstTy.isSimple())
17803    return VectorTargetTransformImpl::getCastInstrCost(Opcode, Dst, Src);
17804
17805  const X86Subtarget &ST = TLI->getTargetMachine().getSubtarget<X86Subtarget>();
17806
17807  static const X86TypeConversionCostTblEntry AVXConversionTbl[] = {
17808    { ISD::SIGN_EXTEND, MVT::v8i32, MVT::v8i16, 1 },
17809    { ISD::ZERO_EXTEND, MVT::v8i32, MVT::v8i16, 1 },
17810    { ISD::SIGN_EXTEND, MVT::v4i64, MVT::v4i32, 1 },
17811    { ISD::ZERO_EXTEND, MVT::v4i64, MVT::v4i32, 1 },
17812    { ISD::TRUNCATE,    MVT::v4i32, MVT::v4i64, 1 },
17813    { ISD::TRUNCATE,    MVT::v8i16, MVT::v8i32, 1 },
17814    { ISD::SINT_TO_FP,  MVT::v8f32, MVT::v8i8,  1 },
17815    { ISD::SINT_TO_FP,  MVT::v4f32, MVT::v4i8,  1 },
17816    { ISD::UINT_TO_FP,  MVT::v8f32, MVT::v8i8,  1 },
17817    { ISD::UINT_TO_FP,  MVT::v4f32, MVT::v4i8,  1 },
17818    { ISD::FP_TO_SINT,  MVT::v8i8,  MVT::v8f32, 1 },
17819    { ISD::FP_TO_SINT,  MVT::v4i8,  MVT::v4f32, 1 },
17820    { ISD::ZERO_EXTEND, MVT::v8i32, MVT::v8i1,  6 },
17821    { ISD::SIGN_EXTEND, MVT::v8i32, MVT::v8i1,  9 },
17822    { ISD::TRUNCATE,    MVT::v8i32, MVT::v8i64, 3 },
17823  };
17824
17825  if (ST.hasAVX()) {
17826    int Idx = FindInConvertTable(AVXConversionTbl,
17827                                 array_lengthof(AVXConversionTbl),
17828                                 ISD, DstTy.getSimpleVT(), SrcTy.getSimpleVT());
17829    if (Idx != -1)
17830      return AVXConversionTbl[Idx].Cost;
17831  }
17832
17833  return VectorTargetTransformImpl::getCastInstrCost(Opcode, Dst, Src);
17834}
17835
17836