X86ISelLowering.cpp revision 2b7a2e8833c00a484bd9d54db77959cfe31dfc8d
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.getConstant(NormalizedIdxVal, MVT::i32);
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.getConstant(NormalizedIdxVal, MVT::i32);
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  X86StackPtr = Subtarget->is64Bit() ? X86::RSP : X86::ESP;
162
163  RegInfo = TM.getRegisterInfo();
164  TD = getTargetData();
165
166  // Set up the TargetLowering object.
167  static const MVT IntVTs[] = { MVT::i8, MVT::i16, MVT::i32, MVT::i64 };
168
169  // X86 is weird, it always uses i8 for shift amounts and setcc results.
170  setBooleanContents(ZeroOrOneBooleanContent);
171  // X86-SSE is even stranger. It uses -1 or 0 for vector masks.
172  setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
173
174  // For 64-bit since we have so many registers use the ILP scheduler, for
175  // 32-bit code use the register pressure specific scheduling.
176  // For Atom, always use ILP scheduling.
177  if (Subtarget->isAtom())
178    setSchedulingPreference(Sched::ILP);
179  else if (Subtarget->is64Bit())
180    setSchedulingPreference(Sched::ILP);
181  else
182    setSchedulingPreference(Sched::RegPressure);
183  setStackPointerRegisterToSaveRestore(X86StackPtr);
184
185  if (Subtarget->isTargetWindows() && !Subtarget->isTargetCygMing()) {
186    // Setup Windows compiler runtime calls.
187    setLibcallName(RTLIB::SDIV_I64, "_alldiv");
188    setLibcallName(RTLIB::UDIV_I64, "_aulldiv");
189    setLibcallName(RTLIB::SREM_I64, "_allrem");
190    setLibcallName(RTLIB::UREM_I64, "_aullrem");
191    setLibcallName(RTLIB::MUL_I64, "_allmul");
192    setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::X86_StdCall);
193    setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::X86_StdCall);
194    setLibcallCallingConv(RTLIB::SREM_I64, CallingConv::X86_StdCall);
195    setLibcallCallingConv(RTLIB::UREM_I64, CallingConv::X86_StdCall);
196    setLibcallCallingConv(RTLIB::MUL_I64, CallingConv::X86_StdCall);
197
198    // The _ftol2 runtime function has an unusual calling conv, which
199    // is modeled by a special pseudo-instruction.
200    setLibcallName(RTLIB::FPTOUINT_F64_I64, 0);
201    setLibcallName(RTLIB::FPTOUINT_F32_I64, 0);
202    setLibcallName(RTLIB::FPTOUINT_F64_I32, 0);
203    setLibcallName(RTLIB::FPTOUINT_F32_I32, 0);
204  }
205
206  if (Subtarget->isTargetDarwin()) {
207    // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
208    setUseUnderscoreSetJmp(false);
209    setUseUnderscoreLongJmp(false);
210  } else if (Subtarget->isTargetMingw()) {
211    // MS runtime is weird: it exports _setjmp, but longjmp!
212    setUseUnderscoreSetJmp(true);
213    setUseUnderscoreLongJmp(false);
214  } else {
215    setUseUnderscoreSetJmp(true);
216    setUseUnderscoreLongJmp(true);
217  }
218
219  // Set up the register classes.
220  addRegisterClass(MVT::i8, &X86::GR8RegClass);
221  addRegisterClass(MVT::i16, &X86::GR16RegClass);
222  addRegisterClass(MVT::i32, &X86::GR32RegClass);
223  if (Subtarget->is64Bit())
224    addRegisterClass(MVT::i64, &X86::GR64RegClass);
225
226  setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
227
228  // We don't accept any truncstore of integer registers.
229  setTruncStoreAction(MVT::i64, MVT::i32, Expand);
230  setTruncStoreAction(MVT::i64, MVT::i16, Expand);
231  setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
232  setTruncStoreAction(MVT::i32, MVT::i16, Expand);
233  setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
234  setTruncStoreAction(MVT::i16, MVT::i8,  Expand);
235
236  // SETOEQ and SETUNE require checking two conditions.
237  setCondCodeAction(ISD::SETOEQ, MVT::f32, Expand);
238  setCondCodeAction(ISD::SETOEQ, MVT::f64, Expand);
239  setCondCodeAction(ISD::SETOEQ, MVT::f80, Expand);
240  setCondCodeAction(ISD::SETUNE, MVT::f32, Expand);
241  setCondCodeAction(ISD::SETUNE, MVT::f64, Expand);
242  setCondCodeAction(ISD::SETUNE, MVT::f80, Expand);
243
244  // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
245  // operation.
246  setOperationAction(ISD::UINT_TO_FP       , MVT::i1   , Promote);
247  setOperationAction(ISD::UINT_TO_FP       , MVT::i8   , Promote);
248  setOperationAction(ISD::UINT_TO_FP       , MVT::i16  , Promote);
249
250  if (Subtarget->is64Bit()) {
251    setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Promote);
252    setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Custom);
253  } else if (!TM.Options.UseSoftFloat) {
254    // We have an algorithm for SSE2->double, and we turn this into a
255    // 64-bit FILD followed by conditional FADD for other targets.
256    setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Custom);
257    // We have an algorithm for SSE2, and we turn this into a 64-bit
258    // FILD for other targets.
259    setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Custom);
260  }
261
262  // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
263  // this operation.
264  setOperationAction(ISD::SINT_TO_FP       , MVT::i1   , Promote);
265  setOperationAction(ISD::SINT_TO_FP       , MVT::i8   , Promote);
266
267  if (!TM.Options.UseSoftFloat) {
268    // SSE has no i16 to fp conversion, only i32
269    if (X86ScalarSSEf32) {
270      setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
271      // f32 and f64 cases are Legal, f80 case is not
272      setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
273    } else {
274      setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Custom);
275      setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
276    }
277  } else {
278    setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
279    setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Promote);
280  }
281
282  // In 32-bit mode these are custom lowered.  In 64-bit mode F32 and F64
283  // are Legal, f80 is custom lowered.
284  setOperationAction(ISD::FP_TO_SINT     , MVT::i64  , Custom);
285  setOperationAction(ISD::SINT_TO_FP     , MVT::i64  , Custom);
286
287  // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
288  // this operation.
289  setOperationAction(ISD::FP_TO_SINT       , MVT::i1   , Promote);
290  setOperationAction(ISD::FP_TO_SINT       , MVT::i8   , Promote);
291
292  if (X86ScalarSSEf32) {
293    setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Promote);
294    // f32 and f64 cases are Legal, f80 case is not
295    setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
296  } else {
297    setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Custom);
298    setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
299  }
300
301  // Handle FP_TO_UINT by promoting the destination to a larger signed
302  // conversion.
303  setOperationAction(ISD::FP_TO_UINT       , MVT::i1   , Promote);
304  setOperationAction(ISD::FP_TO_UINT       , MVT::i8   , Promote);
305  setOperationAction(ISD::FP_TO_UINT       , MVT::i16  , Promote);
306
307  if (Subtarget->is64Bit()) {
308    setOperationAction(ISD::FP_TO_UINT     , MVT::i64  , Expand);
309    setOperationAction(ISD::FP_TO_UINT     , MVT::i32  , Promote);
310  } else if (!TM.Options.UseSoftFloat) {
311    // Since AVX is a superset of SSE3, only check for SSE here.
312    if (Subtarget->hasSSE1() && !Subtarget->hasSSE3())
313      // Expand FP_TO_UINT into a select.
314      // FIXME: We would like to use a Custom expander here eventually to do
315      // the optimal thing for SSE vs. the default expansion in the legalizer.
316      setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Expand);
317    else
318      // With SSE3 we can use fisttpll to convert to a signed i64; without
319      // SSE, we're stuck with a fistpll.
320      setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Custom);
321  }
322
323  if (isTargetFTOL()) {
324    // Use the _ftol2 runtime function, which has a pseudo-instruction
325    // to handle its weird calling convention.
326    setOperationAction(ISD::FP_TO_UINT     , MVT::i64  , Custom);
327  }
328
329  // TODO: when we have SSE, these could be more efficient, by using movd/movq.
330  if (!X86ScalarSSEf64) {
331    setOperationAction(ISD::BITCAST        , MVT::f32  , Expand);
332    setOperationAction(ISD::BITCAST        , MVT::i32  , Expand);
333    if (Subtarget->is64Bit()) {
334      setOperationAction(ISD::BITCAST      , MVT::f64  , Expand);
335      // Without SSE, i64->f64 goes through memory.
336      setOperationAction(ISD::BITCAST      , MVT::i64  , Expand);
337    }
338  }
339
340  // Scalar integer divide and remainder are lowered to use operations that
341  // produce two results, to match the available instructions. This exposes
342  // the two-result form to trivial CSE, which is able to combine x/y and x%y
343  // into a single instruction.
344  //
345  // Scalar integer multiply-high is also lowered to use two-result
346  // operations, to match the available instructions. However, plain multiply
347  // (low) operations are left as Legal, as there are single-result
348  // instructions for this in x86. Using the two-result multiply instructions
349  // when both high and low results are needed must be arranged by dagcombine.
350  for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
351    MVT VT = IntVTs[i];
352    setOperationAction(ISD::MULHS, VT, Expand);
353    setOperationAction(ISD::MULHU, VT, Expand);
354    setOperationAction(ISD::SDIV, VT, Expand);
355    setOperationAction(ISD::UDIV, VT, Expand);
356    setOperationAction(ISD::SREM, VT, Expand);
357    setOperationAction(ISD::UREM, VT, Expand);
358
359    // Add/Sub overflow ops with MVT::Glues are lowered to EFLAGS dependences.
360    setOperationAction(ISD::ADDC, VT, Custom);
361    setOperationAction(ISD::ADDE, VT, Custom);
362    setOperationAction(ISD::SUBC, VT, Custom);
363    setOperationAction(ISD::SUBE, VT, Custom);
364  }
365
366  setOperationAction(ISD::BR_JT            , MVT::Other, Expand);
367  setOperationAction(ISD::BRCOND           , MVT::Other, Custom);
368  setOperationAction(ISD::BR_CC            , MVT::Other, Expand);
369  setOperationAction(ISD::SELECT_CC        , MVT::Other, Expand);
370  if (Subtarget->is64Bit())
371    setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
372  setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16  , Legal);
373  setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8   , Legal);
374  setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1   , Expand);
375  setOperationAction(ISD::FP_ROUND_INREG   , MVT::f32  , Expand);
376  setOperationAction(ISD::FREM             , MVT::f32  , Expand);
377  setOperationAction(ISD::FREM             , MVT::f64  , Expand);
378  setOperationAction(ISD::FREM             , MVT::f80  , Expand);
379  setOperationAction(ISD::FLT_ROUNDS_      , MVT::i32  , Custom);
380
381  // Promote the i8 variants and force them on up to i32 which has a shorter
382  // encoding.
383  setOperationAction(ISD::CTTZ             , MVT::i8   , Promote);
384  AddPromotedToType (ISD::CTTZ             , MVT::i8   , MVT::i32);
385  setOperationAction(ISD::CTTZ_ZERO_UNDEF  , MVT::i8   , Promote);
386  AddPromotedToType (ISD::CTTZ_ZERO_UNDEF  , MVT::i8   , MVT::i32);
387  if (Subtarget->hasBMI()) {
388    setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16  , Expand);
389    setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32  , Expand);
390    if (Subtarget->is64Bit())
391      setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
392  } else {
393    setOperationAction(ISD::CTTZ           , MVT::i16  , Custom);
394    setOperationAction(ISD::CTTZ           , MVT::i32  , Custom);
395    if (Subtarget->is64Bit())
396      setOperationAction(ISD::CTTZ         , MVT::i64  , Custom);
397  }
398
399  if (Subtarget->hasLZCNT()) {
400    // When promoting the i8 variants, force them to i32 for a shorter
401    // encoding.
402    setOperationAction(ISD::CTLZ           , MVT::i8   , Promote);
403    AddPromotedToType (ISD::CTLZ           , MVT::i8   , MVT::i32);
404    setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8   , Promote);
405    AddPromotedToType (ISD::CTLZ_ZERO_UNDEF, MVT::i8   , MVT::i32);
406    setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16  , Expand);
407    setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32  , Expand);
408    if (Subtarget->is64Bit())
409      setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
410  } else {
411    setOperationAction(ISD::CTLZ           , MVT::i8   , Custom);
412    setOperationAction(ISD::CTLZ           , MVT::i16  , Custom);
413    setOperationAction(ISD::CTLZ           , MVT::i32  , Custom);
414    setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8   , Custom);
415    setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16  , Custom);
416    setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32  , Custom);
417    if (Subtarget->is64Bit()) {
418      setOperationAction(ISD::CTLZ         , MVT::i64  , Custom);
419      setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Custom);
420    }
421  }
422
423  if (Subtarget->hasPOPCNT()) {
424    setOperationAction(ISD::CTPOP          , MVT::i8   , Promote);
425  } else {
426    setOperationAction(ISD::CTPOP          , MVT::i8   , Expand);
427    setOperationAction(ISD::CTPOP          , MVT::i16  , Expand);
428    setOperationAction(ISD::CTPOP          , MVT::i32  , Expand);
429    if (Subtarget->is64Bit())
430      setOperationAction(ISD::CTPOP        , MVT::i64  , Expand);
431  }
432
433  setOperationAction(ISD::READCYCLECOUNTER , MVT::i64  , Custom);
434  setOperationAction(ISD::BSWAP            , MVT::i16  , Expand);
435
436  // These should be promoted to a larger select which is supported.
437  setOperationAction(ISD::SELECT          , MVT::i1   , Promote);
438  // X86 wants to expand cmov itself.
439  setOperationAction(ISD::SELECT          , MVT::i8   , Custom);
440  setOperationAction(ISD::SELECT          , MVT::i16  , Custom);
441  setOperationAction(ISD::SELECT          , MVT::i32  , Custom);
442  setOperationAction(ISD::SELECT          , MVT::f32  , Custom);
443  setOperationAction(ISD::SELECT          , MVT::f64  , Custom);
444  setOperationAction(ISD::SELECT          , MVT::f80  , Custom);
445  setOperationAction(ISD::SETCC           , MVT::i8   , Custom);
446  setOperationAction(ISD::SETCC           , MVT::i16  , Custom);
447  setOperationAction(ISD::SETCC           , MVT::i32  , Custom);
448  setOperationAction(ISD::SETCC           , MVT::f32  , Custom);
449  setOperationAction(ISD::SETCC           , MVT::f64  , Custom);
450  setOperationAction(ISD::SETCC           , MVT::f80  , Custom);
451  if (Subtarget->is64Bit()) {
452    setOperationAction(ISD::SELECT        , MVT::i64  , Custom);
453    setOperationAction(ISD::SETCC         , MVT::i64  , Custom);
454  }
455  setOperationAction(ISD::EH_RETURN       , MVT::Other, Custom);
456
457  // Darwin ABI issue.
458  setOperationAction(ISD::ConstantPool    , MVT::i32  , Custom);
459  setOperationAction(ISD::JumpTable       , MVT::i32  , Custom);
460  setOperationAction(ISD::GlobalAddress   , MVT::i32  , Custom);
461  setOperationAction(ISD::GlobalTLSAddress, MVT::i32  , Custom);
462  if (Subtarget->is64Bit())
463    setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
464  setOperationAction(ISD::ExternalSymbol  , MVT::i32  , Custom);
465  setOperationAction(ISD::BlockAddress    , MVT::i32  , Custom);
466  if (Subtarget->is64Bit()) {
467    setOperationAction(ISD::ConstantPool  , MVT::i64  , Custom);
468    setOperationAction(ISD::JumpTable     , MVT::i64  , Custom);
469    setOperationAction(ISD::GlobalAddress , MVT::i64  , Custom);
470    setOperationAction(ISD::ExternalSymbol, MVT::i64  , Custom);
471    setOperationAction(ISD::BlockAddress  , MVT::i64  , Custom);
472  }
473  // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
474  setOperationAction(ISD::SHL_PARTS       , MVT::i32  , Custom);
475  setOperationAction(ISD::SRA_PARTS       , MVT::i32  , Custom);
476  setOperationAction(ISD::SRL_PARTS       , MVT::i32  , Custom);
477  if (Subtarget->is64Bit()) {
478    setOperationAction(ISD::SHL_PARTS     , MVT::i64  , Custom);
479    setOperationAction(ISD::SRA_PARTS     , MVT::i64  , Custom);
480    setOperationAction(ISD::SRL_PARTS     , MVT::i64  , Custom);
481  }
482
483  if (Subtarget->hasSSE1())
484    setOperationAction(ISD::PREFETCH      , MVT::Other, Legal);
485
486  setOperationAction(ISD::MEMBARRIER    , MVT::Other, Custom);
487  setOperationAction(ISD::ATOMIC_FENCE  , MVT::Other, Custom);
488
489  // On X86 and X86-64, atomic operations are lowered to locked instructions.
490  // Locked instructions, in turn, have implicit fence semantics (all memory
491  // operations are flushed before issuing the locked instruction, and they
492  // are not buffered), so we can fold away the common pattern of
493  // fence-atomic-fence.
494  setShouldFoldAtomicFences(true);
495
496  // Expand certain atomics
497  for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
498    MVT VT = IntVTs[i];
499    setOperationAction(ISD::ATOMIC_CMP_SWAP, VT, Custom);
500    setOperationAction(ISD::ATOMIC_LOAD_SUB, VT, Custom);
501    setOperationAction(ISD::ATOMIC_STORE, VT, Custom);
502  }
503
504  if (!Subtarget->is64Bit()) {
505    setOperationAction(ISD::ATOMIC_LOAD, MVT::i64, Custom);
506    setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i64, Custom);
507    setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
508    setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i64, Custom);
509    setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i64, Custom);
510    setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i64, Custom);
511    setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i64, Custom);
512    setOperationAction(ISD::ATOMIC_SWAP, MVT::i64, Custom);
513  }
514
515  if (Subtarget->hasCmpxchg16b()) {
516    setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i128, Custom);
517  }
518
519  // FIXME - use subtarget debug flags
520  if (!Subtarget->isTargetDarwin() &&
521      !Subtarget->isTargetELF() &&
522      !Subtarget->isTargetCygMing()) {
523    setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
524  }
525
526  setOperationAction(ISD::EXCEPTIONADDR, MVT::i64, Expand);
527  setOperationAction(ISD::EHSELECTION,   MVT::i64, Expand);
528  setOperationAction(ISD::EXCEPTIONADDR, MVT::i32, Expand);
529  setOperationAction(ISD::EHSELECTION,   MVT::i32, Expand);
530  if (Subtarget->is64Bit()) {
531    setExceptionPointerRegister(X86::RAX);
532    setExceptionSelectorRegister(X86::RDX);
533  } else {
534    setExceptionPointerRegister(X86::EAX);
535    setExceptionSelectorRegister(X86::EDX);
536  }
537  setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
538  setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
539
540  setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
541  setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
542
543  setOperationAction(ISD::TRAP, MVT::Other, Legal);
544
545  // VASTART needs to be custom lowered to use the VarArgsFrameIndex
546  setOperationAction(ISD::VASTART           , MVT::Other, Custom);
547  setOperationAction(ISD::VAEND             , MVT::Other, Expand);
548  if (Subtarget->is64Bit()) {
549    setOperationAction(ISD::VAARG           , MVT::Other, Custom);
550    setOperationAction(ISD::VACOPY          , MVT::Other, Custom);
551  } else {
552    setOperationAction(ISD::VAARG           , MVT::Other, Expand);
553    setOperationAction(ISD::VACOPY          , MVT::Other, Expand);
554  }
555
556  setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
557  setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
558
559  if (Subtarget->isTargetCOFF() && !Subtarget->isTargetEnvMacho())
560    setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
561                       MVT::i64 : MVT::i32, Custom);
562  else if (TM.Options.EnableSegmentedStacks)
563    setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
564                       MVT::i64 : MVT::i32, Custom);
565  else
566    setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
567                       MVT::i64 : MVT::i32, Expand);
568
569  if (!TM.Options.UseSoftFloat && X86ScalarSSEf64) {
570    // f32 and f64 use SSE.
571    // Set up the FP register classes.
572    addRegisterClass(MVT::f32, &X86::FR32RegClass);
573    addRegisterClass(MVT::f64, &X86::FR64RegClass);
574
575    // Use ANDPD to simulate FABS.
576    setOperationAction(ISD::FABS , MVT::f64, Custom);
577    setOperationAction(ISD::FABS , MVT::f32, Custom);
578
579    // Use XORP to simulate FNEG.
580    setOperationAction(ISD::FNEG , MVT::f64, Custom);
581    setOperationAction(ISD::FNEG , MVT::f32, Custom);
582
583    // Use ANDPD and ORPD to simulate FCOPYSIGN.
584    setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
585    setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
586
587    // Lower this to FGETSIGNx86 plus an AND.
588    setOperationAction(ISD::FGETSIGN, MVT::i64, Custom);
589    setOperationAction(ISD::FGETSIGN, MVT::i32, Custom);
590
591    // We don't support sin/cos/fmod
592    setOperationAction(ISD::FSIN , MVT::f64, Expand);
593    setOperationAction(ISD::FCOS , MVT::f64, Expand);
594    setOperationAction(ISD::FSIN , MVT::f32, Expand);
595    setOperationAction(ISD::FCOS , MVT::f32, Expand);
596
597    // Expand FP immediates into loads from the stack, except for the special
598    // cases we handle.
599    addLegalFPImmediate(APFloat(+0.0)); // xorpd
600    addLegalFPImmediate(APFloat(+0.0f)); // xorps
601  } else if (!TM.Options.UseSoftFloat && X86ScalarSSEf32) {
602    // Use SSE for f32, x87 for f64.
603    // Set up the FP register classes.
604    addRegisterClass(MVT::f32, &X86::FR32RegClass);
605    addRegisterClass(MVT::f64, &X86::RFP64RegClass);
606
607    // Use ANDPS to simulate FABS.
608    setOperationAction(ISD::FABS , MVT::f32, Custom);
609
610    // Use XORP to simulate FNEG.
611    setOperationAction(ISD::FNEG , MVT::f32, Custom);
612
613    setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
614
615    // Use ANDPS and ORPS to simulate FCOPYSIGN.
616    setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
617    setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
618
619    // We don't support sin/cos/fmod
620    setOperationAction(ISD::FSIN , MVT::f32, Expand);
621    setOperationAction(ISD::FCOS , MVT::f32, Expand);
622
623    // Special cases we handle for FP constants.
624    addLegalFPImmediate(APFloat(+0.0f)); // xorps
625    addLegalFPImmediate(APFloat(+0.0)); // FLD0
626    addLegalFPImmediate(APFloat(+1.0)); // FLD1
627    addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
628    addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
629
630    if (!TM.Options.UnsafeFPMath) {
631      setOperationAction(ISD::FSIN           , MVT::f64  , Expand);
632      setOperationAction(ISD::FCOS           , MVT::f64  , Expand);
633    }
634  } else if (!TM.Options.UseSoftFloat) {
635    // f32 and f64 in x87.
636    // Set up the FP register classes.
637    addRegisterClass(MVT::f64, &X86::RFP64RegClass);
638    addRegisterClass(MVT::f32, &X86::RFP32RegClass);
639
640    setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
641    setOperationAction(ISD::UNDEF,     MVT::f32, Expand);
642    setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
643    setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
644
645    if (!TM.Options.UnsafeFPMath) {
646      setOperationAction(ISD::FSIN           , MVT::f64  , Expand);
647      setOperationAction(ISD::FCOS           , MVT::f64  , Expand);
648    }
649    addLegalFPImmediate(APFloat(+0.0)); // FLD0
650    addLegalFPImmediate(APFloat(+1.0)); // FLD1
651    addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
652    addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
653    addLegalFPImmediate(APFloat(+0.0f)); // FLD0
654    addLegalFPImmediate(APFloat(+1.0f)); // FLD1
655    addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
656    addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
657  }
658
659  // We don't support FMA.
660  setOperationAction(ISD::FMA, MVT::f64, Expand);
661  setOperationAction(ISD::FMA, MVT::f32, Expand);
662
663  // Long double always uses X87.
664  if (!TM.Options.UseSoftFloat) {
665    addRegisterClass(MVT::f80, &X86::RFP80RegClass);
666    setOperationAction(ISD::UNDEF,     MVT::f80, Expand);
667    setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
668    {
669      APFloat TmpFlt = APFloat::getZero(APFloat::x87DoubleExtended);
670      addLegalFPImmediate(TmpFlt);  // FLD0
671      TmpFlt.changeSign();
672      addLegalFPImmediate(TmpFlt);  // FLD0/FCHS
673
674      bool ignored;
675      APFloat TmpFlt2(+1.0);
676      TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
677                      &ignored);
678      addLegalFPImmediate(TmpFlt2);  // FLD1
679      TmpFlt2.changeSign();
680      addLegalFPImmediate(TmpFlt2);  // FLD1/FCHS
681    }
682
683    if (!TM.Options.UnsafeFPMath) {
684      setOperationAction(ISD::FSIN           , MVT::f80  , Expand);
685      setOperationAction(ISD::FCOS           , MVT::f80  , Expand);
686    }
687
688    setOperationAction(ISD::FFLOOR, MVT::f80, Expand);
689    setOperationAction(ISD::FCEIL,  MVT::f80, Expand);
690    setOperationAction(ISD::FTRUNC, MVT::f80, Expand);
691    setOperationAction(ISD::FRINT,  MVT::f80, Expand);
692    setOperationAction(ISD::FNEARBYINT, MVT::f80, Expand);
693    setOperationAction(ISD::FMA, MVT::f80, Expand);
694  }
695
696  // Always use a library call for pow.
697  setOperationAction(ISD::FPOW             , MVT::f32  , Expand);
698  setOperationAction(ISD::FPOW             , MVT::f64  , Expand);
699  setOperationAction(ISD::FPOW             , MVT::f80  , Expand);
700
701  setOperationAction(ISD::FLOG, MVT::f80, Expand);
702  setOperationAction(ISD::FLOG2, MVT::f80, Expand);
703  setOperationAction(ISD::FLOG10, MVT::f80, Expand);
704  setOperationAction(ISD::FEXP, MVT::f80, Expand);
705  setOperationAction(ISD::FEXP2, MVT::f80, Expand);
706
707  // First set operation action for all vector types to either promote
708  // (for widening) or expand (for scalarization). Then we will selectively
709  // turn on ones that can be effectively codegen'd.
710  for (int VT = MVT::FIRST_VECTOR_VALUETYPE;
711           VT <= MVT::LAST_VECTOR_VALUETYPE; ++VT) {
712    setOperationAction(ISD::ADD , (MVT::SimpleValueType)VT, Expand);
713    setOperationAction(ISD::SUB , (MVT::SimpleValueType)VT, Expand);
714    setOperationAction(ISD::FADD, (MVT::SimpleValueType)VT, Expand);
715    setOperationAction(ISD::FNEG, (MVT::SimpleValueType)VT, Expand);
716    setOperationAction(ISD::FSUB, (MVT::SimpleValueType)VT, Expand);
717    setOperationAction(ISD::MUL , (MVT::SimpleValueType)VT, Expand);
718    setOperationAction(ISD::FMUL, (MVT::SimpleValueType)VT, Expand);
719    setOperationAction(ISD::SDIV, (MVT::SimpleValueType)VT, Expand);
720    setOperationAction(ISD::UDIV, (MVT::SimpleValueType)VT, Expand);
721    setOperationAction(ISD::FDIV, (MVT::SimpleValueType)VT, Expand);
722    setOperationAction(ISD::SREM, (MVT::SimpleValueType)VT, Expand);
723    setOperationAction(ISD::UREM, (MVT::SimpleValueType)VT, Expand);
724    setOperationAction(ISD::LOAD, (MVT::SimpleValueType)VT, Expand);
725    setOperationAction(ISD::VECTOR_SHUFFLE, (MVT::SimpleValueType)VT, Expand);
726    setOperationAction(ISD::EXTRACT_VECTOR_ELT,(MVT::SimpleValueType)VT,Expand);
727    setOperationAction(ISD::INSERT_VECTOR_ELT,(MVT::SimpleValueType)VT, Expand);
728    setOperationAction(ISD::EXTRACT_SUBVECTOR,(MVT::SimpleValueType)VT,Expand);
729    setOperationAction(ISD::INSERT_SUBVECTOR,(MVT::SimpleValueType)VT,Expand);
730    setOperationAction(ISD::FABS, (MVT::SimpleValueType)VT, Expand);
731    setOperationAction(ISD::FSIN, (MVT::SimpleValueType)VT, Expand);
732    setOperationAction(ISD::FCOS, (MVT::SimpleValueType)VT, Expand);
733    setOperationAction(ISD::FREM, (MVT::SimpleValueType)VT, Expand);
734    setOperationAction(ISD::FMA,  (MVT::SimpleValueType)VT, Expand);
735    setOperationAction(ISD::FPOWI, (MVT::SimpleValueType)VT, Expand);
736    setOperationAction(ISD::FSQRT, (MVT::SimpleValueType)VT, Expand);
737    setOperationAction(ISD::FCOPYSIGN, (MVT::SimpleValueType)VT, Expand);
738    setOperationAction(ISD::SMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
739    setOperationAction(ISD::UMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
740    setOperationAction(ISD::SDIVREM, (MVT::SimpleValueType)VT, Expand);
741    setOperationAction(ISD::UDIVREM, (MVT::SimpleValueType)VT, Expand);
742    setOperationAction(ISD::FPOW, (MVT::SimpleValueType)VT, Expand);
743    setOperationAction(ISD::CTPOP, (MVT::SimpleValueType)VT, Expand);
744    setOperationAction(ISD::CTTZ, (MVT::SimpleValueType)VT, Expand);
745    setOperationAction(ISD::CTTZ_ZERO_UNDEF, (MVT::SimpleValueType)VT, Expand);
746    setOperationAction(ISD::CTLZ, (MVT::SimpleValueType)VT, Expand);
747    setOperationAction(ISD::CTLZ_ZERO_UNDEF, (MVT::SimpleValueType)VT, Expand);
748    setOperationAction(ISD::SHL, (MVT::SimpleValueType)VT, Expand);
749    setOperationAction(ISD::SRA, (MVT::SimpleValueType)VT, Expand);
750    setOperationAction(ISD::SRL, (MVT::SimpleValueType)VT, Expand);
751    setOperationAction(ISD::ROTL, (MVT::SimpleValueType)VT, Expand);
752    setOperationAction(ISD::ROTR, (MVT::SimpleValueType)VT, Expand);
753    setOperationAction(ISD::BSWAP, (MVT::SimpleValueType)VT, Expand);
754    setOperationAction(ISD::SETCC, (MVT::SimpleValueType)VT, Expand);
755    setOperationAction(ISD::FLOG, (MVT::SimpleValueType)VT, Expand);
756    setOperationAction(ISD::FLOG2, (MVT::SimpleValueType)VT, Expand);
757    setOperationAction(ISD::FLOG10, (MVT::SimpleValueType)VT, Expand);
758    setOperationAction(ISD::FEXP, (MVT::SimpleValueType)VT, Expand);
759    setOperationAction(ISD::FEXP2, (MVT::SimpleValueType)VT, Expand);
760    setOperationAction(ISD::FP_TO_UINT, (MVT::SimpleValueType)VT, Expand);
761    setOperationAction(ISD::FP_TO_SINT, (MVT::SimpleValueType)VT, Expand);
762    setOperationAction(ISD::UINT_TO_FP, (MVT::SimpleValueType)VT, Expand);
763    setOperationAction(ISD::SINT_TO_FP, (MVT::SimpleValueType)VT, Expand);
764    setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,Expand);
765    setOperationAction(ISD::TRUNCATE,  (MVT::SimpleValueType)VT, Expand);
766    setOperationAction(ISD::SIGN_EXTEND,  (MVT::SimpleValueType)VT, Expand);
767    setOperationAction(ISD::ZERO_EXTEND,  (MVT::SimpleValueType)VT, Expand);
768    setOperationAction(ISD::ANY_EXTEND,  (MVT::SimpleValueType)VT, Expand);
769    setOperationAction(ISD::VSELECT,  (MVT::SimpleValueType)VT, Expand);
770    for (int InnerVT = MVT::FIRST_VECTOR_VALUETYPE;
771             InnerVT <= MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
772      setTruncStoreAction((MVT::SimpleValueType)VT,
773                          (MVT::SimpleValueType)InnerVT, Expand);
774    setLoadExtAction(ISD::SEXTLOAD, (MVT::SimpleValueType)VT, Expand);
775    setLoadExtAction(ISD::ZEXTLOAD, (MVT::SimpleValueType)VT, Expand);
776    setLoadExtAction(ISD::EXTLOAD, (MVT::SimpleValueType)VT, Expand);
777  }
778
779  // FIXME: In order to prevent SSE instructions being expanded to MMX ones
780  // with -msoft-float, disable use of MMX as well.
781  if (!TM.Options.UseSoftFloat && Subtarget->hasMMX()) {
782    addRegisterClass(MVT::x86mmx, &X86::VR64RegClass);
783    // No operations on x86mmx supported, everything uses intrinsics.
784  }
785
786  // MMX-sized vectors (other than x86mmx) are expected to be expanded
787  // into smaller operations.
788  setOperationAction(ISD::MULHS,              MVT::v8i8,  Expand);
789  setOperationAction(ISD::MULHS,              MVT::v4i16, Expand);
790  setOperationAction(ISD::MULHS,              MVT::v2i32, Expand);
791  setOperationAction(ISD::MULHS,              MVT::v1i64, Expand);
792  setOperationAction(ISD::AND,                MVT::v8i8,  Expand);
793  setOperationAction(ISD::AND,                MVT::v4i16, Expand);
794  setOperationAction(ISD::AND,                MVT::v2i32, Expand);
795  setOperationAction(ISD::AND,                MVT::v1i64, Expand);
796  setOperationAction(ISD::OR,                 MVT::v8i8,  Expand);
797  setOperationAction(ISD::OR,                 MVT::v4i16, Expand);
798  setOperationAction(ISD::OR,                 MVT::v2i32, Expand);
799  setOperationAction(ISD::OR,                 MVT::v1i64, Expand);
800  setOperationAction(ISD::XOR,                MVT::v8i8,  Expand);
801  setOperationAction(ISD::XOR,                MVT::v4i16, Expand);
802  setOperationAction(ISD::XOR,                MVT::v2i32, Expand);
803  setOperationAction(ISD::XOR,                MVT::v1i64, Expand);
804  setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i8,  Expand);
805  setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v4i16, Expand);
806  setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v2i32, Expand);
807  setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v1i64, Expand);
808  setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v1i64, Expand);
809  setOperationAction(ISD::SELECT,             MVT::v8i8,  Expand);
810  setOperationAction(ISD::SELECT,             MVT::v4i16, Expand);
811  setOperationAction(ISD::SELECT,             MVT::v2i32, Expand);
812  setOperationAction(ISD::SELECT,             MVT::v1i64, Expand);
813  setOperationAction(ISD::BITCAST,            MVT::v8i8,  Expand);
814  setOperationAction(ISD::BITCAST,            MVT::v4i16, Expand);
815  setOperationAction(ISD::BITCAST,            MVT::v2i32, Expand);
816  setOperationAction(ISD::BITCAST,            MVT::v1i64, Expand);
817
818  if (!TM.Options.UseSoftFloat && Subtarget->hasSSE1()) {
819    addRegisterClass(MVT::v4f32, &X86::VR128RegClass);
820
821    setOperationAction(ISD::FADD,               MVT::v4f32, Legal);
822    setOperationAction(ISD::FSUB,               MVT::v4f32, Legal);
823    setOperationAction(ISD::FMUL,               MVT::v4f32, Legal);
824    setOperationAction(ISD::FDIV,               MVT::v4f32, Legal);
825    setOperationAction(ISD::FSQRT,              MVT::v4f32, Legal);
826    setOperationAction(ISD::FNEG,               MVT::v4f32, Custom);
827    setOperationAction(ISD::LOAD,               MVT::v4f32, Legal);
828    setOperationAction(ISD::BUILD_VECTOR,       MVT::v4f32, Custom);
829    setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4f32, Custom);
830    setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
831    setOperationAction(ISD::SELECT,             MVT::v4f32, Custom);
832  }
833
834  if (!TM.Options.UseSoftFloat && Subtarget->hasSSE2()) {
835    addRegisterClass(MVT::v2f64, &X86::VR128RegClass);
836
837    // FIXME: Unfortunately -soft-float and -no-implicit-float means XMM
838    // registers cannot be used even for integer operations.
839    addRegisterClass(MVT::v16i8, &X86::VR128RegClass);
840    addRegisterClass(MVT::v8i16, &X86::VR128RegClass);
841    addRegisterClass(MVT::v4i32, &X86::VR128RegClass);
842    addRegisterClass(MVT::v2i64, &X86::VR128RegClass);
843
844    setOperationAction(ISD::ADD,                MVT::v16i8, Legal);
845    setOperationAction(ISD::ADD,                MVT::v8i16, Legal);
846    setOperationAction(ISD::ADD,                MVT::v4i32, Legal);
847    setOperationAction(ISD::ADD,                MVT::v2i64, Legal);
848    setOperationAction(ISD::MUL,                MVT::v2i64, Custom);
849    setOperationAction(ISD::SUB,                MVT::v16i8, Legal);
850    setOperationAction(ISD::SUB,                MVT::v8i16, Legal);
851    setOperationAction(ISD::SUB,                MVT::v4i32, Legal);
852    setOperationAction(ISD::SUB,                MVT::v2i64, Legal);
853    setOperationAction(ISD::MUL,                MVT::v8i16, Legal);
854    setOperationAction(ISD::FADD,               MVT::v2f64, Legal);
855    setOperationAction(ISD::FSUB,               MVT::v2f64, Legal);
856    setOperationAction(ISD::FMUL,               MVT::v2f64, Legal);
857    setOperationAction(ISD::FDIV,               MVT::v2f64, Legal);
858    setOperationAction(ISD::FSQRT,              MVT::v2f64, Legal);
859    setOperationAction(ISD::FNEG,               MVT::v2f64, Custom);
860
861    setOperationAction(ISD::SETCC,              MVT::v2i64, Custom);
862    setOperationAction(ISD::SETCC,              MVT::v16i8, Custom);
863    setOperationAction(ISD::SETCC,              MVT::v8i16, Custom);
864    setOperationAction(ISD::SETCC,              MVT::v4i32, Custom);
865
866    setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v16i8, Custom);
867    setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i16, Custom);
868    setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
869    setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
870    setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
871
872    // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
873    for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
874      MVT VT = (MVT::SimpleValueType)i;
875      // Do not attempt to custom lower non-power-of-2 vectors
876      if (!isPowerOf2_32(VT.getVectorNumElements()))
877        continue;
878      // Do not attempt to custom lower non-128-bit vectors
879      if (!VT.is128BitVector())
880        continue;
881      setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
882      setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
883      setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
884    }
885
886    setOperationAction(ISD::BUILD_VECTOR,       MVT::v2f64, Custom);
887    setOperationAction(ISD::BUILD_VECTOR,       MVT::v2i64, Custom);
888    setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2f64, Custom);
889    setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2i64, Custom);
890    setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2f64, Custom);
891    setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
892
893    if (Subtarget->is64Bit()) {
894      setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
895      setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
896    }
897
898    // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
899    for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
900      MVT VT = (MVT::SimpleValueType)i;
901
902      // Do not attempt to promote non-128-bit vectors
903      if (!VT.is128BitVector())
904        continue;
905
906      setOperationAction(ISD::AND,    VT, Promote);
907      AddPromotedToType (ISD::AND,    VT, MVT::v2i64);
908      setOperationAction(ISD::OR,     VT, Promote);
909      AddPromotedToType (ISD::OR,     VT, MVT::v2i64);
910      setOperationAction(ISD::XOR,    VT, Promote);
911      AddPromotedToType (ISD::XOR,    VT, MVT::v2i64);
912      setOperationAction(ISD::LOAD,   VT, Promote);
913      AddPromotedToType (ISD::LOAD,   VT, MVT::v2i64);
914      setOperationAction(ISD::SELECT, VT, Promote);
915      AddPromotedToType (ISD::SELECT, VT, MVT::v2i64);
916    }
917
918    setTruncStoreAction(MVT::f64, MVT::f32, Expand);
919
920    // Custom lower v2i64 and v2f64 selects.
921    setOperationAction(ISD::LOAD,               MVT::v2f64, Legal);
922    setOperationAction(ISD::LOAD,               MVT::v2i64, Legal);
923    setOperationAction(ISD::SELECT,             MVT::v2f64, Custom);
924    setOperationAction(ISD::SELECT,             MVT::v2i64, Custom);
925
926    setOperationAction(ISD::FP_TO_SINT,         MVT::v4i32, Legal);
927    setOperationAction(ISD::SINT_TO_FP,         MVT::v4i32, Legal);
928  }
929
930  if (Subtarget->hasSSE41()) {
931    setOperationAction(ISD::FFLOOR,             MVT::f32,   Legal);
932    setOperationAction(ISD::FCEIL,              MVT::f32,   Legal);
933    setOperationAction(ISD::FTRUNC,             MVT::f32,   Legal);
934    setOperationAction(ISD::FRINT,              MVT::f32,   Legal);
935    setOperationAction(ISD::FNEARBYINT,         MVT::f32,   Legal);
936    setOperationAction(ISD::FFLOOR,             MVT::f64,   Legal);
937    setOperationAction(ISD::FCEIL,              MVT::f64,   Legal);
938    setOperationAction(ISD::FTRUNC,             MVT::f64,   Legal);
939    setOperationAction(ISD::FRINT,              MVT::f64,   Legal);
940    setOperationAction(ISD::FNEARBYINT,         MVT::f64,   Legal);
941
942    // FIXME: Do we need to handle scalar-to-vector here?
943    setOperationAction(ISD::MUL,                MVT::v4i32, Legal);
944
945    setOperationAction(ISD::VSELECT,            MVT::v2f64, Legal);
946    setOperationAction(ISD::VSELECT,            MVT::v2i64, Legal);
947    setOperationAction(ISD::VSELECT,            MVT::v16i8, Legal);
948    setOperationAction(ISD::VSELECT,            MVT::v4i32, Legal);
949    setOperationAction(ISD::VSELECT,            MVT::v4f32, Legal);
950
951    // i8 and i16 vectors are custom , because the source register and source
952    // source memory operand types are not the same width.  f32 vectors are
953    // custom since the immediate controlling the insert encodes additional
954    // information.
955    setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i8, Custom);
956    setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
957    setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
958    setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
959
960    setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
961    setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
962    setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
963    setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
964
965    // FIXME: these should be Legal but thats only for the case where
966    // the index is constant.  For now custom expand to deal with that.
967    if (Subtarget->is64Bit()) {
968      setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
969      setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
970    }
971  }
972
973  if (Subtarget->hasSSE2()) {
974    setOperationAction(ISD::SRL,               MVT::v8i16, Custom);
975    setOperationAction(ISD::SRL,               MVT::v16i8, Custom);
976
977    setOperationAction(ISD::SHL,               MVT::v8i16, Custom);
978    setOperationAction(ISD::SHL,               MVT::v16i8, Custom);
979
980    setOperationAction(ISD::SRA,               MVT::v8i16, Custom);
981    setOperationAction(ISD::SRA,               MVT::v16i8, Custom);
982
983    if (Subtarget->hasAVX2()) {
984      setOperationAction(ISD::SRL,             MVT::v2i64, Legal);
985      setOperationAction(ISD::SRL,             MVT::v4i32, Legal);
986
987      setOperationAction(ISD::SHL,             MVT::v2i64, Legal);
988      setOperationAction(ISD::SHL,             MVT::v4i32, Legal);
989
990      setOperationAction(ISD::SRA,             MVT::v4i32, Legal);
991    } else {
992      setOperationAction(ISD::SRL,             MVT::v2i64, Custom);
993      setOperationAction(ISD::SRL,             MVT::v4i32, Custom);
994
995      setOperationAction(ISD::SHL,             MVT::v2i64, Custom);
996      setOperationAction(ISD::SHL,             MVT::v4i32, Custom);
997
998      setOperationAction(ISD::SRA,             MVT::v4i32, Custom);
999    }
1000  }
1001
1002  if (!TM.Options.UseSoftFloat && Subtarget->hasAVX()) {
1003    addRegisterClass(MVT::v32i8,  &X86::VR256RegClass);
1004    addRegisterClass(MVT::v16i16, &X86::VR256RegClass);
1005    addRegisterClass(MVT::v8i32,  &X86::VR256RegClass);
1006    addRegisterClass(MVT::v8f32,  &X86::VR256RegClass);
1007    addRegisterClass(MVT::v4i64,  &X86::VR256RegClass);
1008    addRegisterClass(MVT::v4f64,  &X86::VR256RegClass);
1009
1010    setOperationAction(ISD::LOAD,               MVT::v8f32, Legal);
1011    setOperationAction(ISD::LOAD,               MVT::v4f64, Legal);
1012    setOperationAction(ISD::LOAD,               MVT::v4i64, Legal);
1013
1014    setOperationAction(ISD::FADD,               MVT::v8f32, Legal);
1015    setOperationAction(ISD::FSUB,               MVT::v8f32, Legal);
1016    setOperationAction(ISD::FMUL,               MVT::v8f32, Legal);
1017    setOperationAction(ISD::FDIV,               MVT::v8f32, Legal);
1018    setOperationAction(ISD::FSQRT,              MVT::v8f32, Legal);
1019    setOperationAction(ISD::FNEG,               MVT::v8f32, Custom);
1020
1021    setOperationAction(ISD::FADD,               MVT::v4f64, Legal);
1022    setOperationAction(ISD::FSUB,               MVT::v4f64, Legal);
1023    setOperationAction(ISD::FMUL,               MVT::v4f64, Legal);
1024    setOperationAction(ISD::FDIV,               MVT::v4f64, Legal);
1025    setOperationAction(ISD::FSQRT,              MVT::v4f64, Legal);
1026    setOperationAction(ISD::FNEG,               MVT::v4f64, Custom);
1027
1028    setOperationAction(ISD::FP_TO_SINT,         MVT::v8i32, Legal);
1029    setOperationAction(ISD::SINT_TO_FP,         MVT::v8i32, Legal);
1030    setOperationAction(ISD::FP_ROUND,           MVT::v4f32, Legal);
1031
1032    setOperationAction(ISD::SRL,               MVT::v16i16, Custom);
1033    setOperationAction(ISD::SRL,               MVT::v32i8, Custom);
1034
1035    setOperationAction(ISD::SHL,               MVT::v16i16, Custom);
1036    setOperationAction(ISD::SHL,               MVT::v32i8, Custom);
1037
1038    setOperationAction(ISD::SRA,               MVT::v16i16, Custom);
1039    setOperationAction(ISD::SRA,               MVT::v32i8, Custom);
1040
1041    setOperationAction(ISD::SETCC,             MVT::v32i8, Custom);
1042    setOperationAction(ISD::SETCC,             MVT::v16i16, Custom);
1043    setOperationAction(ISD::SETCC,             MVT::v8i32, Custom);
1044    setOperationAction(ISD::SETCC,             MVT::v4i64, Custom);
1045
1046    setOperationAction(ISD::SELECT,            MVT::v4f64, Custom);
1047    setOperationAction(ISD::SELECT,            MVT::v4i64, Custom);
1048    setOperationAction(ISD::SELECT,            MVT::v8f32, Custom);
1049
1050    setOperationAction(ISD::VSELECT,           MVT::v4f64, Legal);
1051    setOperationAction(ISD::VSELECT,           MVT::v4i64, Legal);
1052    setOperationAction(ISD::VSELECT,           MVT::v8i32, Legal);
1053    setOperationAction(ISD::VSELECT,           MVT::v8f32, Legal);
1054
1055    if (Subtarget->hasFMA() || Subtarget->hasFMA4()) {
1056      setOperationAction(ISD::FMA,             MVT::v8f32, Custom);
1057      setOperationAction(ISD::FMA,             MVT::v4f64, Custom);
1058      setOperationAction(ISD::FMA,             MVT::v4f32, Custom);
1059      setOperationAction(ISD::FMA,             MVT::v2f64, Custom);
1060      setOperationAction(ISD::FMA,             MVT::f32, Custom);
1061      setOperationAction(ISD::FMA,             MVT::f64, Custom);
1062    }
1063
1064    if (Subtarget->hasAVX2()) {
1065      setOperationAction(ISD::ADD,             MVT::v4i64, Legal);
1066      setOperationAction(ISD::ADD,             MVT::v8i32, Legal);
1067      setOperationAction(ISD::ADD,             MVT::v16i16, Legal);
1068      setOperationAction(ISD::ADD,             MVT::v32i8, Legal);
1069
1070      setOperationAction(ISD::SUB,             MVT::v4i64, Legal);
1071      setOperationAction(ISD::SUB,             MVT::v8i32, Legal);
1072      setOperationAction(ISD::SUB,             MVT::v16i16, Legal);
1073      setOperationAction(ISD::SUB,             MVT::v32i8, Legal);
1074
1075      setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1076      setOperationAction(ISD::MUL,             MVT::v8i32, Legal);
1077      setOperationAction(ISD::MUL,             MVT::v16i16, Legal);
1078      // Don't lower v32i8 because there is no 128-bit byte mul
1079
1080      setOperationAction(ISD::VSELECT,         MVT::v32i8, Legal);
1081
1082      setOperationAction(ISD::SRL,             MVT::v4i64, Legal);
1083      setOperationAction(ISD::SRL,             MVT::v8i32, Legal);
1084
1085      setOperationAction(ISD::SHL,             MVT::v4i64, Legal);
1086      setOperationAction(ISD::SHL,             MVT::v8i32, Legal);
1087
1088      setOperationAction(ISD::SRA,             MVT::v8i32, Legal);
1089    } else {
1090      setOperationAction(ISD::ADD,             MVT::v4i64, Custom);
1091      setOperationAction(ISD::ADD,             MVT::v8i32, Custom);
1092      setOperationAction(ISD::ADD,             MVT::v16i16, Custom);
1093      setOperationAction(ISD::ADD,             MVT::v32i8, Custom);
1094
1095      setOperationAction(ISD::SUB,             MVT::v4i64, Custom);
1096      setOperationAction(ISD::SUB,             MVT::v8i32, Custom);
1097      setOperationAction(ISD::SUB,             MVT::v16i16, Custom);
1098      setOperationAction(ISD::SUB,             MVT::v32i8, Custom);
1099
1100      setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1101      setOperationAction(ISD::MUL,             MVT::v8i32, Custom);
1102      setOperationAction(ISD::MUL,             MVT::v16i16, Custom);
1103      // Don't lower v32i8 because there is no 128-bit byte mul
1104
1105      setOperationAction(ISD::SRL,             MVT::v4i64, Custom);
1106      setOperationAction(ISD::SRL,             MVT::v8i32, Custom);
1107
1108      setOperationAction(ISD::SHL,             MVT::v4i64, Custom);
1109      setOperationAction(ISD::SHL,             MVT::v8i32, Custom);
1110
1111      setOperationAction(ISD::SRA,             MVT::v8i32, Custom);
1112    }
1113
1114    // Custom lower several nodes for 256-bit types.
1115    for (int i = MVT::FIRST_VECTOR_VALUETYPE;
1116             i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
1117      MVT VT = (MVT::SimpleValueType)i;
1118
1119      // Extract subvector is special because the value type
1120      // (result) is 128-bit but the source is 256-bit wide.
1121      if (VT.is128BitVector())
1122        setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1123
1124      // Do not attempt to custom lower other non-256-bit vectors
1125      if (!VT.is256BitVector())
1126        continue;
1127
1128      setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
1129      setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
1130      setOperationAction(ISD::INSERT_VECTOR_ELT,  VT, Custom);
1131      setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1132      setOperationAction(ISD::SCALAR_TO_VECTOR,   VT, Custom);
1133      setOperationAction(ISD::INSERT_SUBVECTOR,   VT, Custom);
1134      setOperationAction(ISD::CONCAT_VECTORS,     VT, Custom);
1135    }
1136
1137    // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
1138    for (int i = MVT::v32i8; i != MVT::v4i64; ++i) {
1139      MVT VT = (MVT::SimpleValueType)i;
1140
1141      // Do not attempt to promote non-256-bit vectors
1142      if (!VT.is256BitVector())
1143        continue;
1144
1145      setOperationAction(ISD::AND,    VT, Promote);
1146      AddPromotedToType (ISD::AND,    VT, MVT::v4i64);
1147      setOperationAction(ISD::OR,     VT, Promote);
1148      AddPromotedToType (ISD::OR,     VT, MVT::v4i64);
1149      setOperationAction(ISD::XOR,    VT, Promote);
1150      AddPromotedToType (ISD::XOR,    VT, MVT::v4i64);
1151      setOperationAction(ISD::LOAD,   VT, Promote);
1152      AddPromotedToType (ISD::LOAD,   VT, MVT::v4i64);
1153      setOperationAction(ISD::SELECT, VT, Promote);
1154      AddPromotedToType (ISD::SELECT, VT, MVT::v4i64);
1155    }
1156  }
1157
1158  // SIGN_EXTEND_INREGs are evaluated by the extend type. Handle the expansion
1159  // of this type with custom code.
1160  for (int VT = MVT::FIRST_VECTOR_VALUETYPE;
1161           VT != MVT::LAST_VECTOR_VALUETYPE; VT++) {
1162    setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,
1163                       Custom);
1164  }
1165
1166  // We want to custom lower some of our intrinsics.
1167  setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1168  setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
1169
1170
1171  // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1172  // handle type legalization for these operations here.
1173  //
1174  // FIXME: We really should do custom legalization for addition and
1175  // subtraction on x86-32 once PR3203 is fixed.  We really can't do much better
1176  // than generic legalization for 64-bit multiplication-with-overflow, though.
1177  for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) {
1178    // Add/Sub/Mul with overflow operations are custom lowered.
1179    MVT VT = IntVTs[i];
1180    setOperationAction(ISD::SADDO, VT, Custom);
1181    setOperationAction(ISD::UADDO, VT, Custom);
1182    setOperationAction(ISD::SSUBO, VT, Custom);
1183    setOperationAction(ISD::USUBO, VT, Custom);
1184    setOperationAction(ISD::SMULO, VT, Custom);
1185    setOperationAction(ISD::UMULO, VT, Custom);
1186  }
1187
1188  // There are no 8-bit 3-address imul/mul instructions
1189  setOperationAction(ISD::SMULO, MVT::i8, Expand);
1190  setOperationAction(ISD::UMULO, MVT::i8, Expand);
1191
1192  if (!Subtarget->is64Bit()) {
1193    // These libcalls are not available in 32-bit.
1194    setLibcallName(RTLIB::SHL_I128, 0);
1195    setLibcallName(RTLIB::SRL_I128, 0);
1196    setLibcallName(RTLIB::SRA_I128, 0);
1197  }
1198
1199  // We have target-specific dag combine patterns for the following nodes:
1200  setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1201  setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1202  setTargetDAGCombine(ISD::VSELECT);
1203  setTargetDAGCombine(ISD::SELECT);
1204  setTargetDAGCombine(ISD::SHL);
1205  setTargetDAGCombine(ISD::SRA);
1206  setTargetDAGCombine(ISD::SRL);
1207  setTargetDAGCombine(ISD::OR);
1208  setTargetDAGCombine(ISD::AND);
1209  setTargetDAGCombine(ISD::ADD);
1210  setTargetDAGCombine(ISD::FADD);
1211  setTargetDAGCombine(ISD::FSUB);
1212  setTargetDAGCombine(ISD::FMA);
1213  setTargetDAGCombine(ISD::SUB);
1214  setTargetDAGCombine(ISD::LOAD);
1215  setTargetDAGCombine(ISD::STORE);
1216  setTargetDAGCombine(ISD::ZERO_EXTEND);
1217  setTargetDAGCombine(ISD::ANY_EXTEND);
1218  setTargetDAGCombine(ISD::SIGN_EXTEND);
1219  setTargetDAGCombine(ISD::TRUNCATE);
1220  setTargetDAGCombine(ISD::UINT_TO_FP);
1221  setTargetDAGCombine(ISD::SINT_TO_FP);
1222  setTargetDAGCombine(ISD::SETCC);
1223  setTargetDAGCombine(ISD::FP_TO_SINT);
1224  if (Subtarget->is64Bit())
1225    setTargetDAGCombine(ISD::MUL);
1226  setTargetDAGCombine(ISD::XOR);
1227
1228  computeRegisterProperties();
1229
1230  // On Darwin, -Os means optimize for size without hurting performance,
1231  // do not reduce the limit.
1232  maxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1233  maxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 16 : 8;
1234  maxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1235  maxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1236  maxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1237  maxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1238  setPrefLoopAlignment(4); // 2^4 bytes.
1239  benefitFromCodePlacementOpt = true;
1240
1241  // Predictable cmov don't hurt on atom because it's in-order.
1242  predictableSelectIsExpensive = !Subtarget->isAtom();
1243
1244  setPrefFunctionAlignment(4); // 2^4 bytes.
1245}
1246
1247
1248EVT X86TargetLowering::getSetCCResultType(EVT VT) const {
1249  if (!VT.isVector()) return MVT::i8;
1250  return VT.changeVectorElementTypeToInteger();
1251}
1252
1253
1254/// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1255/// the desired ByVal argument alignment.
1256static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
1257  if (MaxAlign == 16)
1258    return;
1259  if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1260    if (VTy->getBitWidth() == 128)
1261      MaxAlign = 16;
1262  } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1263    unsigned EltAlign = 0;
1264    getMaxByValAlign(ATy->getElementType(), EltAlign);
1265    if (EltAlign > MaxAlign)
1266      MaxAlign = EltAlign;
1267  } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1268    for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1269      unsigned EltAlign = 0;
1270      getMaxByValAlign(STy->getElementType(i), EltAlign);
1271      if (EltAlign > MaxAlign)
1272        MaxAlign = EltAlign;
1273      if (MaxAlign == 16)
1274        break;
1275    }
1276  }
1277}
1278
1279/// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1280/// function arguments in the caller parameter area. For X86, aggregates
1281/// that contain SSE vectors are placed at 16-byte boundaries while the rest
1282/// are at 4-byte boundaries.
1283unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty) const {
1284  if (Subtarget->is64Bit()) {
1285    // Max of 8 and alignment of type.
1286    unsigned TyAlign = TD->getABITypeAlignment(Ty);
1287    if (TyAlign > 8)
1288      return TyAlign;
1289    return 8;
1290  }
1291
1292  unsigned Align = 4;
1293  if (Subtarget->hasSSE1())
1294    getMaxByValAlign(Ty, Align);
1295  return Align;
1296}
1297
1298/// getOptimalMemOpType - Returns the target specific optimal type for load
1299/// and store operations as a result of memset, memcpy, and memmove
1300/// lowering. If DstAlign is zero that means it's safe to destination
1301/// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1302/// means there isn't a need to check it against alignment requirement,
1303/// probably because the source does not need to be loaded. If
1304/// 'IsZeroVal' is true, that means it's safe to return a
1305/// non-scalar-integer type, e.g. empty string source, constant, or loaded
1306/// from memory. 'MemcpyStrSrc' indicates whether the memcpy source is
1307/// constant so it does not need to be loaded.
1308/// It returns EVT::Other if the type should be determined using generic
1309/// target-independent logic.
1310EVT
1311X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1312                                       unsigned DstAlign, unsigned SrcAlign,
1313                                       bool IsZeroVal,
1314                                       bool MemcpyStrSrc,
1315                                       MachineFunction &MF) const {
1316  // FIXME: This turns off use of xmm stores for memset/memcpy on targets like
1317  // linux.  This is because the stack realignment code can't handle certain
1318  // cases like PR2962.  This should be removed when PR2962 is fixed.
1319  const Function *F = MF.getFunction();
1320  if (IsZeroVal &&
1321      !F->hasFnAttr(Attribute::NoImplicitFloat)) {
1322    if (Size >= 16 &&
1323        (Subtarget->isUnalignedMemAccessFast() ||
1324         ((DstAlign == 0 || DstAlign >= 16) &&
1325          (SrcAlign == 0 || SrcAlign >= 16))) &&
1326        Subtarget->getStackAlignment() >= 16) {
1327      if (Subtarget->getStackAlignment() >= 32) {
1328        if (Subtarget->hasAVX2())
1329          return MVT::v8i32;
1330        if (Subtarget->hasAVX())
1331          return MVT::v8f32;
1332      }
1333      if (Subtarget->hasSSE2())
1334        return MVT::v4i32;
1335      if (Subtarget->hasSSE1())
1336        return MVT::v4f32;
1337    } else if (!MemcpyStrSrc && Size >= 8 &&
1338               !Subtarget->is64Bit() &&
1339               Subtarget->getStackAlignment() >= 8 &&
1340               Subtarget->hasSSE2()) {
1341      // Do not use f64 to lower memcpy if source is string constant. It's
1342      // better to use i32 to avoid the loads.
1343      return MVT::f64;
1344    }
1345  }
1346  if (Subtarget->is64Bit() && Size >= 8)
1347    return MVT::i64;
1348  return MVT::i32;
1349}
1350
1351/// getJumpTableEncoding - Return the entry encoding for a jump table in the
1352/// current function.  The returned value is a member of the
1353/// MachineJumpTableInfo::JTEntryKind enum.
1354unsigned X86TargetLowering::getJumpTableEncoding() const {
1355  // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1356  // symbol.
1357  if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1358      Subtarget->isPICStyleGOT())
1359    return MachineJumpTableInfo::EK_Custom32;
1360
1361  // Otherwise, use the normal jump table encoding heuristics.
1362  return TargetLowering::getJumpTableEncoding();
1363}
1364
1365const MCExpr *
1366X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1367                                             const MachineBasicBlock *MBB,
1368                                             unsigned uid,MCContext &Ctx) const{
1369  assert(getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1370         Subtarget->isPICStyleGOT());
1371  // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1372  // entries.
1373  return MCSymbolRefExpr::Create(MBB->getSymbol(),
1374                                 MCSymbolRefExpr::VK_GOTOFF, Ctx);
1375}
1376
1377/// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
1378/// jumptable.
1379SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1380                                                    SelectionDAG &DAG) const {
1381  if (!Subtarget->is64Bit())
1382    // This doesn't have DebugLoc associated with it, but is not really the
1383    // same as a Register.
1384    return DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), getPointerTy());
1385  return Table;
1386}
1387
1388/// getPICJumpTableRelocBaseExpr - This returns the relocation base for the
1389/// given PIC jumptable, the same as getPICJumpTableRelocBase, but as an
1390/// MCExpr.
1391const MCExpr *X86TargetLowering::
1392getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1393                             MCContext &Ctx) const {
1394  // X86-64 uses RIP relative addressing based on the jump table label.
1395  if (Subtarget->isPICStyleRIPRel())
1396    return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1397
1398  // Otherwise, the reference is relative to the PIC base.
1399  return MCSymbolRefExpr::Create(MF->getPICBaseSymbol(), Ctx);
1400}
1401
1402// FIXME: Why this routine is here? Move to RegInfo!
1403std::pair<const TargetRegisterClass*, uint8_t>
1404X86TargetLowering::findRepresentativeClass(EVT VT) const{
1405  const TargetRegisterClass *RRC = 0;
1406  uint8_t Cost = 1;
1407  switch (VT.getSimpleVT().SimpleTy) {
1408  default:
1409    return TargetLowering::findRepresentativeClass(VT);
1410  case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1411    RRC = Subtarget->is64Bit() ?
1412      (const TargetRegisterClass*)&X86::GR64RegClass :
1413      (const TargetRegisterClass*)&X86::GR32RegClass;
1414    break;
1415  case MVT::x86mmx:
1416    RRC = &X86::VR64RegClass;
1417    break;
1418  case MVT::f32: case MVT::f64:
1419  case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1420  case MVT::v4f32: case MVT::v2f64:
1421  case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
1422  case MVT::v4f64:
1423    RRC = &X86::VR128RegClass;
1424    break;
1425  }
1426  return std::make_pair(RRC, Cost);
1427}
1428
1429bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
1430                                               unsigned &Offset) const {
1431  if (!Subtarget->isTargetLinux())
1432    return false;
1433
1434  if (Subtarget->is64Bit()) {
1435    // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
1436    Offset = 0x28;
1437    if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
1438      AddressSpace = 256;
1439    else
1440      AddressSpace = 257;
1441  } else {
1442    // %gs:0x14 on i386
1443    Offset = 0x14;
1444    AddressSpace = 256;
1445  }
1446  return true;
1447}
1448
1449
1450//===----------------------------------------------------------------------===//
1451//               Return Value Calling Convention Implementation
1452//===----------------------------------------------------------------------===//
1453
1454#include "X86GenCallingConv.inc"
1455
1456bool
1457X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv,
1458                                  MachineFunction &MF, bool isVarArg,
1459                        const SmallVectorImpl<ISD::OutputArg> &Outs,
1460                        LLVMContext &Context) const {
1461  SmallVector<CCValAssign, 16> RVLocs;
1462  CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1463                 RVLocs, Context);
1464  return CCInfo.CheckReturn(Outs, RetCC_X86);
1465}
1466
1467SDValue
1468X86TargetLowering::LowerReturn(SDValue Chain,
1469                               CallingConv::ID CallConv, bool isVarArg,
1470                               const SmallVectorImpl<ISD::OutputArg> &Outs,
1471                               const SmallVectorImpl<SDValue> &OutVals,
1472                               DebugLoc dl, SelectionDAG &DAG) const {
1473  MachineFunction &MF = DAG.getMachineFunction();
1474  X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1475
1476  SmallVector<CCValAssign, 16> RVLocs;
1477  CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1478                 RVLocs, *DAG.getContext());
1479  CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1480
1481  // Add the regs to the liveout set for the function.
1482  MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
1483  for (unsigned i = 0; i != RVLocs.size(); ++i)
1484    if (RVLocs[i].isRegLoc() && !MRI.isLiveOut(RVLocs[i].getLocReg()))
1485      MRI.addLiveOut(RVLocs[i].getLocReg());
1486
1487  SDValue Flag;
1488
1489  SmallVector<SDValue, 6> RetOps;
1490  RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1491  // Operand #1 = Bytes To Pop
1492  RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(),
1493                   MVT::i16));
1494
1495  // Copy the result values into the output registers.
1496  for (unsigned i = 0; i != RVLocs.size(); ++i) {
1497    CCValAssign &VA = RVLocs[i];
1498    assert(VA.isRegLoc() && "Can only return in registers!");
1499    SDValue ValToCopy = OutVals[i];
1500    EVT ValVT = ValToCopy.getValueType();
1501
1502    // Promote values to the appropriate types
1503    if (VA.getLocInfo() == CCValAssign::SExt)
1504      ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
1505    else if (VA.getLocInfo() == CCValAssign::ZExt)
1506      ValToCopy = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), ValToCopy);
1507    else if (VA.getLocInfo() == CCValAssign::AExt)
1508      ValToCopy = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), ValToCopy);
1509    else if (VA.getLocInfo() == CCValAssign::BCvt)
1510      ValToCopy = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), ValToCopy);
1511
1512    // If this is x86-64, and we disabled SSE, we can't return FP values,
1513    // or SSE or MMX vectors.
1514    if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
1515         VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
1516          (Subtarget->is64Bit() && !Subtarget->hasSSE1())) {
1517      report_fatal_error("SSE register return with SSE disabled");
1518    }
1519    // Likewise we can't return F64 values with SSE1 only.  gcc does so, but
1520    // llvm-gcc has never done it right and no one has noticed, so this
1521    // should be OK for now.
1522    if (ValVT == MVT::f64 &&
1523        (Subtarget->is64Bit() && !Subtarget->hasSSE2()))
1524      report_fatal_error("SSE2 register return with SSE2 disabled");
1525
1526    // Returns in ST0/ST1 are handled specially: these are pushed as operands to
1527    // the RET instruction and handled by the FP Stackifier.
1528    if (VA.getLocReg() == X86::ST0 ||
1529        VA.getLocReg() == X86::ST1) {
1530      // If this is a copy from an xmm register to ST(0), use an FPExtend to
1531      // change the value to the FP stack register class.
1532      if (isScalarFPTypeInSSEReg(VA.getValVT()))
1533        ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
1534      RetOps.push_back(ValToCopy);
1535      // Don't emit a copytoreg.
1536      continue;
1537    }
1538
1539    // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
1540    // which is returned in RAX / RDX.
1541    if (Subtarget->is64Bit()) {
1542      if (ValVT == MVT::x86mmx) {
1543        if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1544          ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ValToCopy);
1545          ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
1546                                  ValToCopy);
1547          // If we don't have SSE2 available, convert to v4f32 so the generated
1548          // register is legal.
1549          if (!Subtarget->hasSSE2())
1550            ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32,ValToCopy);
1551        }
1552      }
1553    }
1554
1555    Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
1556    Flag = Chain.getValue(1);
1557  }
1558
1559  // The x86-64 ABI for returning structs by value requires that we copy
1560  // the sret argument into %rax for the return. We saved the argument into
1561  // a virtual register in the entry block, so now we copy the value out
1562  // and into %rax.
1563  if (Subtarget->is64Bit() &&
1564      DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
1565    MachineFunction &MF = DAG.getMachineFunction();
1566    X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1567    unsigned Reg = FuncInfo->getSRetReturnReg();
1568    assert(Reg &&
1569           "SRetReturnReg should have been set in LowerFormalArguments().");
1570    SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
1571
1572    Chain = DAG.getCopyToReg(Chain, dl, X86::RAX, Val, Flag);
1573    Flag = Chain.getValue(1);
1574
1575    // RAX now acts like a return value.
1576    MRI.addLiveOut(X86::RAX);
1577  }
1578
1579  RetOps[0] = Chain;  // Update chain.
1580
1581  // Add the flag if we have it.
1582  if (Flag.getNode())
1583    RetOps.push_back(Flag);
1584
1585  return DAG.getNode(X86ISD::RET_FLAG, dl,
1586                     MVT::Other, &RetOps[0], RetOps.size());
1587}
1588
1589bool X86TargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
1590  if (N->getNumValues() != 1)
1591    return false;
1592  if (!N->hasNUsesOfValue(1, 0))
1593    return false;
1594
1595  SDValue TCChain = Chain;
1596  SDNode *Copy = *N->use_begin();
1597  if (Copy->getOpcode() == ISD::CopyToReg) {
1598    // If the copy has a glue operand, we conservatively assume it isn't safe to
1599    // perform a tail call.
1600    if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
1601      return false;
1602    TCChain = Copy->getOperand(0);
1603  } else if (Copy->getOpcode() != ISD::FP_EXTEND)
1604    return false;
1605
1606  bool HasRet = false;
1607  for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
1608       UI != UE; ++UI) {
1609    if (UI->getOpcode() != X86ISD::RET_FLAG)
1610      return false;
1611    HasRet = true;
1612  }
1613
1614  if (!HasRet)
1615    return false;
1616
1617  Chain = TCChain;
1618  return true;
1619}
1620
1621EVT
1622X86TargetLowering::getTypeForExtArgOrReturn(LLVMContext &Context, EVT VT,
1623                                            ISD::NodeType ExtendKind) const {
1624  MVT ReturnMVT;
1625  // TODO: Is this also valid on 32-bit?
1626  if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
1627    ReturnMVT = MVT::i8;
1628  else
1629    ReturnMVT = MVT::i32;
1630
1631  EVT MinVT = getRegisterType(Context, ReturnMVT);
1632  return VT.bitsLT(MinVT) ? MinVT : VT;
1633}
1634
1635/// LowerCallResult - Lower the result values of a call into the
1636/// appropriate copies out of appropriate physical registers.
1637///
1638SDValue
1639X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1640                                   CallingConv::ID CallConv, bool isVarArg,
1641                                   const SmallVectorImpl<ISD::InputArg> &Ins,
1642                                   DebugLoc dl, SelectionDAG &DAG,
1643                                   SmallVectorImpl<SDValue> &InVals) const {
1644
1645  // Assign locations to each value returned by this call.
1646  SmallVector<CCValAssign, 16> RVLocs;
1647  bool Is64Bit = Subtarget->is64Bit();
1648  CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1649                 getTargetMachine(), RVLocs, *DAG.getContext());
1650  CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
1651
1652  // Copy all of the result registers out of their specified physreg.
1653  for (unsigned i = 0; i != RVLocs.size(); ++i) {
1654    CCValAssign &VA = RVLocs[i];
1655    EVT CopyVT = VA.getValVT();
1656
1657    // If this is x86-64, and we disabled SSE, we can't return FP values
1658    if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
1659        ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
1660      report_fatal_error("SSE register return with SSE disabled");
1661    }
1662
1663    SDValue Val;
1664
1665    // If this is a call to a function that returns an fp value on the floating
1666    // point stack, we must guarantee the value is popped from the stack, so
1667    // a CopyFromReg is not good enough - the copy instruction may be eliminated
1668    // if the return value is not used. We use the FpPOP_RETVAL instruction
1669    // instead.
1670    if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1) {
1671      // If we prefer to use the value in xmm registers, copy it out as f80 and
1672      // use a truncate to move it from fp stack reg to xmm reg.
1673      if (isScalarFPTypeInSSEReg(VA.getValVT())) CopyVT = MVT::f80;
1674      SDValue Ops[] = { Chain, InFlag };
1675      Chain = SDValue(DAG.getMachineNode(X86::FpPOP_RETVAL, dl, CopyVT,
1676                                         MVT::Other, MVT::Glue, Ops, 2), 1);
1677      Val = Chain.getValue(0);
1678
1679      // Round the f80 to the right size, which also moves it to the appropriate
1680      // xmm register.
1681      if (CopyVT != VA.getValVT())
1682        Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
1683                          // This truncation won't change the value.
1684                          DAG.getIntPtrConstant(1));
1685    } else {
1686      Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1687                                 CopyVT, InFlag).getValue(1);
1688      Val = Chain.getValue(0);
1689    }
1690    InFlag = Chain.getValue(2);
1691    InVals.push_back(Val);
1692  }
1693
1694  return Chain;
1695}
1696
1697
1698//===----------------------------------------------------------------------===//
1699//                C & StdCall & Fast Calling Convention implementation
1700//===----------------------------------------------------------------------===//
1701//  StdCall calling convention seems to be standard for many Windows' API
1702//  routines and around. It differs from C calling convention just a little:
1703//  callee should clean up the stack, not caller. Symbols should be also
1704//  decorated in some fancy way :) It doesn't support any vector arguments.
1705//  For info on fast calling convention see Fast Calling Convention (tail call)
1706//  implementation LowerX86_32FastCCCallTo.
1707
1708/// CallIsStructReturn - Determines whether a call uses struct return
1709/// semantics.
1710enum StructReturnType {
1711  NotStructReturn,
1712  RegStructReturn,
1713  StackStructReturn
1714};
1715static StructReturnType
1716callIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
1717  if (Outs.empty())
1718    return NotStructReturn;
1719
1720  const ISD::ArgFlagsTy &Flags = Outs[0].Flags;
1721  if (!Flags.isSRet())
1722    return NotStructReturn;
1723  if (Flags.isInReg())
1724    return RegStructReturn;
1725  return StackStructReturn;
1726}
1727
1728/// ArgsAreStructReturn - Determines whether a function uses struct
1729/// return semantics.
1730static StructReturnType
1731argsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
1732  if (Ins.empty())
1733    return NotStructReturn;
1734
1735  const ISD::ArgFlagsTy &Flags = Ins[0].Flags;
1736  if (!Flags.isSRet())
1737    return NotStructReturn;
1738  if (Flags.isInReg())
1739    return RegStructReturn;
1740  return StackStructReturn;
1741}
1742
1743/// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
1744/// by "Src" to address "Dst" with size and alignment information specified by
1745/// the specific parameter attribute. The copy will be passed as a byval
1746/// function parameter.
1747static SDValue
1748CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
1749                          ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
1750                          DebugLoc dl) {
1751  SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
1752
1753  return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
1754                       /*isVolatile*/false, /*AlwaysInline=*/true,
1755                       MachinePointerInfo(), MachinePointerInfo());
1756}
1757
1758/// IsTailCallConvention - Return true if the calling convention is one that
1759/// supports tail call optimization.
1760static bool IsTailCallConvention(CallingConv::ID CC) {
1761  return (CC == CallingConv::Fast || CC == CallingConv::GHC);
1762}
1763
1764bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
1765  if (!CI->isTailCall() || getTargetMachine().Options.DisableTailCalls)
1766    return false;
1767
1768  CallSite CS(CI);
1769  CallingConv::ID CalleeCC = CS.getCallingConv();
1770  if (!IsTailCallConvention(CalleeCC) && CalleeCC != CallingConv::C)
1771    return false;
1772
1773  return true;
1774}
1775
1776/// FuncIsMadeTailCallSafe - Return true if the function is being made into
1777/// a tailcall target by changing its ABI.
1778static bool FuncIsMadeTailCallSafe(CallingConv::ID CC,
1779                                   bool GuaranteedTailCallOpt) {
1780  return GuaranteedTailCallOpt && IsTailCallConvention(CC);
1781}
1782
1783SDValue
1784X86TargetLowering::LowerMemArgument(SDValue Chain,
1785                                    CallingConv::ID CallConv,
1786                                    const SmallVectorImpl<ISD::InputArg> &Ins,
1787                                    DebugLoc dl, SelectionDAG &DAG,
1788                                    const CCValAssign &VA,
1789                                    MachineFrameInfo *MFI,
1790                                    unsigned i) const {
1791  // Create the nodes corresponding to a load from this parameter slot.
1792  ISD::ArgFlagsTy Flags = Ins[i].Flags;
1793  bool AlwaysUseMutable = FuncIsMadeTailCallSafe(CallConv,
1794                              getTargetMachine().Options.GuaranteedTailCallOpt);
1795  bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
1796  EVT ValVT;
1797
1798  // If value is passed by pointer we have address passed instead of the value
1799  // itself.
1800  if (VA.getLocInfo() == CCValAssign::Indirect)
1801    ValVT = VA.getLocVT();
1802  else
1803    ValVT = VA.getValVT();
1804
1805  // FIXME: For now, all byval parameter objects are marked mutable. This can be
1806  // changed with more analysis.
1807  // In case of tail call optimization mark all arguments mutable. Since they
1808  // could be overwritten by lowering of arguments in case of a tail call.
1809  if (Flags.isByVal()) {
1810    unsigned Bytes = Flags.getByValSize();
1811    if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
1812    int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
1813    return DAG.getFrameIndex(FI, getPointerTy());
1814  } else {
1815    int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
1816                                    VA.getLocMemOffset(), isImmutable);
1817    SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
1818    return DAG.getLoad(ValVT, dl, Chain, FIN,
1819                       MachinePointerInfo::getFixedStack(FI),
1820                       false, false, false, 0);
1821  }
1822}
1823
1824SDValue
1825X86TargetLowering::LowerFormalArguments(SDValue Chain,
1826                                        CallingConv::ID CallConv,
1827                                        bool isVarArg,
1828                                      const SmallVectorImpl<ISD::InputArg> &Ins,
1829                                        DebugLoc dl,
1830                                        SelectionDAG &DAG,
1831                                        SmallVectorImpl<SDValue> &InVals)
1832                                          const {
1833  MachineFunction &MF = DAG.getMachineFunction();
1834  X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1835
1836  const Function* Fn = MF.getFunction();
1837  if (Fn->hasExternalLinkage() &&
1838      Subtarget->isTargetCygMing() &&
1839      Fn->getName() == "main")
1840    FuncInfo->setForceFramePointer(true);
1841
1842  MachineFrameInfo *MFI = MF.getFrameInfo();
1843  bool Is64Bit = Subtarget->is64Bit();
1844  bool IsWindows = Subtarget->isTargetWindows();
1845  bool IsWin64 = Subtarget->isTargetWin64();
1846
1847  assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
1848         "Var args not supported with calling convention fastcc or ghc");
1849
1850  // Assign locations to all of the incoming arguments.
1851  SmallVector<CCValAssign, 16> ArgLocs;
1852  CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1853                 ArgLocs, *DAG.getContext());
1854
1855  // Allocate shadow area for Win64
1856  if (IsWin64) {
1857    CCInfo.AllocateStack(32, 8);
1858  }
1859
1860  CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
1861
1862  unsigned LastVal = ~0U;
1863  SDValue ArgValue;
1864  for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1865    CCValAssign &VA = ArgLocs[i];
1866    // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
1867    // places.
1868    assert(VA.getValNo() != LastVal &&
1869           "Don't support value assigned to multiple locs yet");
1870    (void)LastVal;
1871    LastVal = VA.getValNo();
1872
1873    if (VA.isRegLoc()) {
1874      EVT RegVT = VA.getLocVT();
1875      const TargetRegisterClass *RC;
1876      if (RegVT == MVT::i32)
1877        RC = &X86::GR32RegClass;
1878      else if (Is64Bit && RegVT == MVT::i64)
1879        RC = &X86::GR64RegClass;
1880      else if (RegVT == MVT::f32)
1881        RC = &X86::FR32RegClass;
1882      else if (RegVT == MVT::f64)
1883        RC = &X86::FR64RegClass;
1884      else if (RegVT.is256BitVector())
1885        RC = &X86::VR256RegClass;
1886      else if (RegVT.is128BitVector())
1887        RC = &X86::VR128RegClass;
1888      else if (RegVT == MVT::x86mmx)
1889        RC = &X86::VR64RegClass;
1890      else
1891        llvm_unreachable("Unknown argument type!");
1892
1893      unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
1894      ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
1895
1896      // If this is an 8 or 16-bit value, it is really passed promoted to 32
1897      // bits.  Insert an assert[sz]ext to capture this, then truncate to the
1898      // right size.
1899      if (VA.getLocInfo() == CCValAssign::SExt)
1900        ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
1901                               DAG.getValueType(VA.getValVT()));
1902      else if (VA.getLocInfo() == CCValAssign::ZExt)
1903        ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
1904                               DAG.getValueType(VA.getValVT()));
1905      else if (VA.getLocInfo() == CCValAssign::BCvt)
1906        ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
1907
1908      if (VA.isExtInLoc()) {
1909        // Handle MMX values passed in XMM regs.
1910        if (RegVT.isVector()) {
1911          ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(),
1912                                 ArgValue);
1913        } else
1914          ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
1915      }
1916    } else {
1917      assert(VA.isMemLoc());
1918      ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
1919    }
1920
1921    // If value is passed via pointer - do a load.
1922    if (VA.getLocInfo() == CCValAssign::Indirect)
1923      ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
1924                             MachinePointerInfo(), false, false, false, 0);
1925
1926    InVals.push_back(ArgValue);
1927  }
1928
1929  // The x86-64 ABI for returning structs by value requires that we copy
1930  // the sret argument into %rax for the return. Save the argument into
1931  // a virtual register so that we can access it from the return points.
1932  if (Is64Bit && MF.getFunction()->hasStructRetAttr()) {
1933    X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1934    unsigned Reg = FuncInfo->getSRetReturnReg();
1935    if (!Reg) {
1936      Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(MVT::i64));
1937      FuncInfo->setSRetReturnReg(Reg);
1938    }
1939    SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[0]);
1940    Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
1941  }
1942
1943  unsigned StackSize = CCInfo.getNextStackOffset();
1944  // Align stack specially for tail calls.
1945  if (FuncIsMadeTailCallSafe(CallConv,
1946                             MF.getTarget().Options.GuaranteedTailCallOpt))
1947    StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
1948
1949  // If the function takes variable number of arguments, make a frame index for
1950  // the start of the first vararg value... for expansion of llvm.va_start.
1951  if (isVarArg) {
1952    if (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
1953                    CallConv != CallingConv::X86_ThisCall)) {
1954      FuncInfo->setVarArgsFrameIndex(MFI->CreateFixedObject(1, StackSize,true));
1955    }
1956    if (Is64Bit) {
1957      unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
1958
1959      // FIXME: We should really autogenerate these arrays
1960      static const uint16_t GPR64ArgRegsWin64[] = {
1961        X86::RCX, X86::RDX, X86::R8,  X86::R9
1962      };
1963      static const uint16_t GPR64ArgRegs64Bit[] = {
1964        X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
1965      };
1966      static const uint16_t XMMArgRegs64Bit[] = {
1967        X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
1968        X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
1969      };
1970      const uint16_t *GPR64ArgRegs;
1971      unsigned NumXMMRegs = 0;
1972
1973      if (IsWin64) {
1974        // The XMM registers which might contain var arg parameters are shadowed
1975        // in their paired GPR.  So we only need to save the GPR to their home
1976        // slots.
1977        TotalNumIntRegs = 4;
1978        GPR64ArgRegs = GPR64ArgRegsWin64;
1979      } else {
1980        TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
1981        GPR64ArgRegs = GPR64ArgRegs64Bit;
1982
1983        NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs64Bit,
1984                                                TotalNumXMMRegs);
1985      }
1986      unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
1987                                                       TotalNumIntRegs);
1988
1989      bool NoImplicitFloatOps = Fn->hasFnAttr(Attribute::NoImplicitFloat);
1990      assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
1991             "SSE register cannot be used when SSE is disabled!");
1992      assert(!(NumXMMRegs && MF.getTarget().Options.UseSoftFloat &&
1993               NoImplicitFloatOps) &&
1994             "SSE register cannot be used when SSE is disabled!");
1995      if (MF.getTarget().Options.UseSoftFloat || NoImplicitFloatOps ||
1996          !Subtarget->hasSSE1())
1997        // Kernel mode asks for SSE to be disabled, so don't push them
1998        // on the stack.
1999        TotalNumXMMRegs = 0;
2000
2001      if (IsWin64) {
2002        const TargetFrameLowering &TFI = *getTargetMachine().getFrameLowering();
2003        // Get to the caller-allocated home save location.  Add 8 to account
2004        // for the return address.
2005        int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2006        FuncInfo->setRegSaveFrameIndex(
2007          MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
2008        // Fixup to set vararg frame on shadow area (4 x i64).
2009        if (NumIntRegs < 4)
2010          FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
2011      } else {
2012        // For X86-64, if there are vararg parameters that are passed via
2013        // registers, then we must store them to their spots on the stack so
2014        // they may be loaded by deferencing the result of va_next.
2015        FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
2016        FuncInfo->setVarArgsFPOffset(TotalNumIntRegs * 8 + NumXMMRegs * 16);
2017        FuncInfo->setRegSaveFrameIndex(
2018          MFI->CreateStackObject(TotalNumIntRegs * 8 + TotalNumXMMRegs * 16, 16,
2019                               false));
2020      }
2021
2022      // Store the integer parameter registers.
2023      SmallVector<SDValue, 8> MemOps;
2024      SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
2025                                        getPointerTy());
2026      unsigned Offset = FuncInfo->getVarArgsGPOffset();
2027      for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
2028        SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
2029                                  DAG.getIntPtrConstant(Offset));
2030        unsigned VReg = MF.addLiveIn(GPR64ArgRegs[NumIntRegs],
2031                                     &X86::GR64RegClass);
2032        SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
2033        SDValue Store =
2034          DAG.getStore(Val.getValue(1), dl, Val, FIN,
2035                       MachinePointerInfo::getFixedStack(
2036                         FuncInfo->getRegSaveFrameIndex(), Offset),
2037                       false, false, 0);
2038        MemOps.push_back(Store);
2039        Offset += 8;
2040      }
2041
2042      if (TotalNumXMMRegs != 0 && NumXMMRegs != TotalNumXMMRegs) {
2043        // Now store the XMM (fp + vector) parameter registers.
2044        SmallVector<SDValue, 11> SaveXMMOps;
2045        SaveXMMOps.push_back(Chain);
2046
2047        unsigned AL = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2048        SDValue ALVal = DAG.getCopyFromReg(DAG.getEntryNode(), dl, AL, MVT::i8);
2049        SaveXMMOps.push_back(ALVal);
2050
2051        SaveXMMOps.push_back(DAG.getIntPtrConstant(
2052                               FuncInfo->getRegSaveFrameIndex()));
2053        SaveXMMOps.push_back(DAG.getIntPtrConstant(
2054                               FuncInfo->getVarArgsFPOffset()));
2055
2056        for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
2057          unsigned VReg = MF.addLiveIn(XMMArgRegs64Bit[NumXMMRegs],
2058                                       &X86::VR128RegClass);
2059          SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::v4f32);
2060          SaveXMMOps.push_back(Val);
2061        }
2062        MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
2063                                     MVT::Other,
2064                                     &SaveXMMOps[0], SaveXMMOps.size()));
2065      }
2066
2067      if (!MemOps.empty())
2068        Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2069                            &MemOps[0], MemOps.size());
2070    }
2071  }
2072
2073  // Some CCs need callee pop.
2074  if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2075                       MF.getTarget().Options.GuaranteedTailCallOpt)) {
2076    FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
2077  } else {
2078    FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
2079    // If this is an sret function, the return should pop the hidden pointer.
2080    if (!Is64Bit && !IsTailCallConvention(CallConv) && !IsWindows &&
2081        argsAreStructReturn(Ins) == StackStructReturn)
2082      FuncInfo->setBytesToPopOnReturn(4);
2083  }
2084
2085  if (!Is64Bit) {
2086    // RegSaveFrameIndex is X86-64 only.
2087    FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
2088    if (CallConv == CallingConv::X86_FastCall ||
2089        CallConv == CallingConv::X86_ThisCall)
2090      // fastcc functions can't have varargs.
2091      FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
2092  }
2093
2094  FuncInfo->setArgumentStackSize(StackSize);
2095
2096  return Chain;
2097}
2098
2099SDValue
2100X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
2101                                    SDValue StackPtr, SDValue Arg,
2102                                    DebugLoc dl, SelectionDAG &DAG,
2103                                    const CCValAssign &VA,
2104                                    ISD::ArgFlagsTy Flags) const {
2105  unsigned LocMemOffset = VA.getLocMemOffset();
2106  SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
2107  PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
2108  if (Flags.isByVal())
2109    return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
2110
2111  return DAG.getStore(Chain, dl, Arg, PtrOff,
2112                      MachinePointerInfo::getStack(LocMemOffset),
2113                      false, false, 0);
2114}
2115
2116/// EmitTailCallLoadRetAddr - Emit a load of return address if tail call
2117/// optimization is performed and it is required.
2118SDValue
2119X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
2120                                           SDValue &OutRetAddr, SDValue Chain,
2121                                           bool IsTailCall, bool Is64Bit,
2122                                           int FPDiff, DebugLoc dl) const {
2123  // Adjust the Return address stack slot.
2124  EVT VT = getPointerTy();
2125  OutRetAddr = getReturnAddressFrameIndex(DAG);
2126
2127  // Load the "old" Return address.
2128  OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
2129                           false, false, false, 0);
2130  return SDValue(OutRetAddr.getNode(), 1);
2131}
2132
2133/// EmitTailCallStoreRetAddr - Emit a store of the return address if tail call
2134/// optimization is performed and it is required (FPDiff!=0).
2135static SDValue
2136EmitTailCallStoreRetAddr(SelectionDAG & DAG, MachineFunction &MF,
2137                         SDValue Chain, SDValue RetAddrFrIdx,
2138                         bool Is64Bit, int FPDiff, DebugLoc dl) {
2139  // Store the return address to the appropriate stack slot.
2140  if (!FPDiff) return Chain;
2141  // Calculate the new stack slot for the return address.
2142  int SlotSize = Is64Bit ? 8 : 4;
2143  int NewReturnAddrFI =
2144    MF.getFrameInfo()->CreateFixedObject(SlotSize, FPDiff-SlotSize, false);
2145  EVT VT = Is64Bit ? MVT::i64 : MVT::i32;
2146  SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, VT);
2147  Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
2148                       MachinePointerInfo::getFixedStack(NewReturnAddrFI),
2149                       false, false, 0);
2150  return Chain;
2151}
2152
2153SDValue
2154X86TargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2155                             SmallVectorImpl<SDValue> &InVals) const {
2156  SelectionDAG &DAG                     = CLI.DAG;
2157  DebugLoc &dl                          = CLI.DL;
2158  SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs;
2159  SmallVector<SDValue, 32> &OutVals     = CLI.OutVals;
2160  SmallVector<ISD::InputArg, 32> &Ins   = CLI.Ins;
2161  SDValue Chain                         = CLI.Chain;
2162  SDValue Callee                        = CLI.Callee;
2163  CallingConv::ID CallConv              = CLI.CallConv;
2164  bool &isTailCall                      = CLI.IsTailCall;
2165  bool isVarArg                         = CLI.IsVarArg;
2166
2167  MachineFunction &MF = DAG.getMachineFunction();
2168  bool Is64Bit        = Subtarget->is64Bit();
2169  bool IsWin64        = Subtarget->isTargetWin64();
2170  bool IsWindows      = Subtarget->isTargetWindows();
2171  StructReturnType SR = callIsStructReturn(Outs);
2172  bool IsSibcall      = false;
2173
2174  if (MF.getTarget().Options.DisableTailCalls)
2175    isTailCall = false;
2176
2177  if (isTailCall) {
2178    // Check if it's really possible to do a tail call.
2179    isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
2180                    isVarArg, SR != NotStructReturn,
2181                    MF.getFunction()->hasStructRetAttr(),
2182                    Outs, OutVals, Ins, DAG);
2183
2184    // Sibcalls are automatically detected tailcalls which do not require
2185    // ABI changes.
2186    if (!MF.getTarget().Options.GuaranteedTailCallOpt && isTailCall)
2187      IsSibcall = true;
2188
2189    if (isTailCall)
2190      ++NumTailCalls;
2191  }
2192
2193  assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2194         "Var args not supported with calling convention fastcc or ghc");
2195
2196  // Analyze operands of the call, assigning locations to each operand.
2197  SmallVector<CCValAssign, 16> ArgLocs;
2198  CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
2199                 ArgLocs, *DAG.getContext());
2200
2201  // Allocate shadow area for Win64
2202  if (IsWin64) {
2203    CCInfo.AllocateStack(32, 8);
2204  }
2205
2206  CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2207
2208  // Get a count of how many bytes are to be pushed on the stack.
2209  unsigned NumBytes = CCInfo.getNextStackOffset();
2210  if (IsSibcall)
2211    // This is a sibcall. The memory operands are available in caller's
2212    // own caller's stack.
2213    NumBytes = 0;
2214  else if (getTargetMachine().Options.GuaranteedTailCallOpt &&
2215           IsTailCallConvention(CallConv))
2216    NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
2217
2218  int FPDiff = 0;
2219  if (isTailCall && !IsSibcall) {
2220    // Lower arguments at fp - stackoffset + fpdiff.
2221    unsigned NumBytesCallerPushed =
2222      MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn();
2223    FPDiff = NumBytesCallerPushed - NumBytes;
2224
2225    // Set the delta of movement of the returnaddr stackslot.
2226    // But only set if delta is greater than previous delta.
2227    if (FPDiff < (MF.getInfo<X86MachineFunctionInfo>()->getTCReturnAddrDelta()))
2228      MF.getInfo<X86MachineFunctionInfo>()->setTCReturnAddrDelta(FPDiff);
2229  }
2230
2231  if (!IsSibcall)
2232    Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true));
2233
2234  SDValue RetAddrFrIdx;
2235  // Load return address for tail calls.
2236  if (isTailCall && FPDiff)
2237    Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
2238                                    Is64Bit, FPDiff, dl);
2239
2240  SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2241  SmallVector<SDValue, 8> MemOpChains;
2242  SDValue StackPtr;
2243
2244  // Walk the register/memloc assignments, inserting copies/loads.  In the case
2245  // of tail call optimization arguments are handle later.
2246  for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2247    CCValAssign &VA = ArgLocs[i];
2248    EVT RegVT = VA.getLocVT();
2249    SDValue Arg = OutVals[i];
2250    ISD::ArgFlagsTy Flags = Outs[i].Flags;
2251    bool isByVal = Flags.isByVal();
2252
2253    // Promote the value if needed.
2254    switch (VA.getLocInfo()) {
2255    default: llvm_unreachable("Unknown loc info!");
2256    case CCValAssign::Full: break;
2257    case CCValAssign::SExt:
2258      Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
2259      break;
2260    case CCValAssign::ZExt:
2261      Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
2262      break;
2263    case CCValAssign::AExt:
2264      if (RegVT.is128BitVector()) {
2265        // Special case: passing MMX values in XMM registers.
2266        Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
2267        Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
2268        Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
2269      } else
2270        Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
2271      break;
2272    case CCValAssign::BCvt:
2273      Arg = DAG.getNode(ISD::BITCAST, dl, RegVT, Arg);
2274      break;
2275    case CCValAssign::Indirect: {
2276      // Store the argument.
2277      SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
2278      int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
2279      Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
2280                           MachinePointerInfo::getFixedStack(FI),
2281                           false, false, 0);
2282      Arg = SpillSlot;
2283      break;
2284    }
2285    }
2286
2287    if (VA.isRegLoc()) {
2288      RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2289      if (isVarArg && IsWin64) {
2290        // Win64 ABI requires argument XMM reg to be copied to the corresponding
2291        // shadow reg if callee is a varargs function.
2292        unsigned ShadowReg = 0;
2293        switch (VA.getLocReg()) {
2294        case X86::XMM0: ShadowReg = X86::RCX; break;
2295        case X86::XMM1: ShadowReg = X86::RDX; break;
2296        case X86::XMM2: ShadowReg = X86::R8; break;
2297        case X86::XMM3: ShadowReg = X86::R9; break;
2298        }
2299        if (ShadowReg)
2300          RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
2301      }
2302    } else if (!IsSibcall && (!isTailCall || isByVal)) {
2303      assert(VA.isMemLoc());
2304      if (StackPtr.getNode() == 0)
2305        StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr, getPointerTy());
2306      MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
2307                                             dl, DAG, VA, Flags));
2308    }
2309  }
2310
2311  if (!MemOpChains.empty())
2312    Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2313                        &MemOpChains[0], MemOpChains.size());
2314
2315  if (Subtarget->isPICStyleGOT()) {
2316    // ELF / PIC requires GOT in the EBX register before function calls via PLT
2317    // GOT pointer.
2318    if (!isTailCall) {
2319      RegsToPass.push_back(std::make_pair(unsigned(X86::EBX),
2320               DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), getPointerTy())));
2321    } else {
2322      // If we are tail calling and generating PIC/GOT style code load the
2323      // address of the callee into ECX. The value in ecx is used as target of
2324      // the tail jump. This is done to circumvent the ebx/callee-saved problem
2325      // for tail calls on PIC/GOT architectures. Normally we would just put the
2326      // address of GOT into ebx and then call target@PLT. But for tail calls
2327      // ebx would be restored (since ebx is callee saved) before jumping to the
2328      // target@PLT.
2329
2330      // Note: The actual moving to ECX is done further down.
2331      GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2332      if (G && !G->getGlobal()->hasHiddenVisibility() &&
2333          !G->getGlobal()->hasProtectedVisibility())
2334        Callee = LowerGlobalAddress(Callee, DAG);
2335      else if (isa<ExternalSymbolSDNode>(Callee))
2336        Callee = LowerExternalSymbol(Callee, DAG);
2337    }
2338  }
2339
2340  if (Is64Bit && isVarArg && !IsWin64) {
2341    // From AMD64 ABI document:
2342    // For calls that may call functions that use varargs or stdargs
2343    // (prototype-less calls or calls to functions containing ellipsis (...) in
2344    // the declaration) %al is used as hidden argument to specify the number
2345    // of SSE registers used. The contents of %al do not need to match exactly
2346    // the number of registers, but must be an ubound on the number of SSE
2347    // registers used and is in the range 0 - 8 inclusive.
2348
2349    // Count the number of XMM registers allocated.
2350    static const uint16_t XMMArgRegs[] = {
2351      X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2352      X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2353    };
2354    unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
2355    assert((Subtarget->hasSSE1() || !NumXMMRegs)
2356           && "SSE registers cannot be used when SSE is disabled");
2357
2358    RegsToPass.push_back(std::make_pair(unsigned(X86::AL),
2359                                        DAG.getConstant(NumXMMRegs, MVT::i8)));
2360  }
2361
2362  // For tail calls lower the arguments to the 'real' stack slot.
2363  if (isTailCall) {
2364    // Force all the incoming stack arguments to be loaded from the stack
2365    // before any new outgoing arguments are stored to the stack, because the
2366    // outgoing stack slots may alias the incoming argument stack slots, and
2367    // the alias isn't otherwise explicit. This is slightly more conservative
2368    // than necessary, because it means that each store effectively depends
2369    // on every argument instead of just those arguments it would clobber.
2370    SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
2371
2372    SmallVector<SDValue, 8> MemOpChains2;
2373    SDValue FIN;
2374    int FI = 0;
2375    if (getTargetMachine().Options.GuaranteedTailCallOpt) {
2376      for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2377        CCValAssign &VA = ArgLocs[i];
2378        if (VA.isRegLoc())
2379          continue;
2380        assert(VA.isMemLoc());
2381        SDValue Arg = OutVals[i];
2382        ISD::ArgFlagsTy Flags = Outs[i].Flags;
2383        // Create frame index.
2384        int32_t Offset = VA.getLocMemOffset()+FPDiff;
2385        uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
2386        FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
2387        FIN = DAG.getFrameIndex(FI, getPointerTy());
2388
2389        if (Flags.isByVal()) {
2390          // Copy relative to framepointer.
2391          SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
2392          if (StackPtr.getNode() == 0)
2393            StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr,
2394                                          getPointerTy());
2395          Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
2396
2397          MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
2398                                                           ArgChain,
2399                                                           Flags, DAG, dl));
2400        } else {
2401          // Store relative to framepointer.
2402          MemOpChains2.push_back(
2403            DAG.getStore(ArgChain, dl, Arg, FIN,
2404                         MachinePointerInfo::getFixedStack(FI),
2405                         false, false, 0));
2406        }
2407      }
2408    }
2409
2410    if (!MemOpChains2.empty())
2411      Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2412                          &MemOpChains2[0], MemOpChains2.size());
2413
2414    // Store the return address to the appropriate stack slot.
2415    Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx, Is64Bit,
2416                                     FPDiff, dl);
2417  }
2418
2419  // Build a sequence of copy-to-reg nodes chained together with token chain
2420  // and flag operands which copy the outgoing args into registers.
2421  SDValue InFlag;
2422  for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2423    Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2424                             RegsToPass[i].second, InFlag);
2425    InFlag = Chain.getValue(1);
2426  }
2427
2428  if (getTargetMachine().getCodeModel() == CodeModel::Large) {
2429    assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
2430    // In the 64-bit large code model, we have to make all calls
2431    // through a register, since the call instruction's 32-bit
2432    // pc-relative offset may not be large enough to hold the whole
2433    // address.
2434  } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2435    // If the callee is a GlobalAddress node (quite common, every direct call
2436    // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
2437    // it.
2438
2439    // We should use extra load for direct calls to dllimported functions in
2440    // non-JIT mode.
2441    const GlobalValue *GV = G->getGlobal();
2442    if (!GV->hasDLLImportLinkage()) {
2443      unsigned char OpFlags = 0;
2444      bool ExtraLoad = false;
2445      unsigned WrapperKind = ISD::DELETED_NODE;
2446
2447      // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
2448      // external symbols most go through the PLT in PIC mode.  If the symbol
2449      // has hidden or protected visibility, or if it is static or local, then
2450      // we don't need to use the PLT - we can directly call it.
2451      if (Subtarget->isTargetELF() &&
2452          getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
2453          GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
2454        OpFlags = X86II::MO_PLT;
2455      } else if (Subtarget->isPICStyleStubAny() &&
2456                 (GV->isDeclaration() || GV->isWeakForLinker()) &&
2457                 (!Subtarget->getTargetTriple().isMacOSX() ||
2458                  Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2459        // PC-relative references to external symbols should go through $stub,
2460        // unless we're building with the leopard linker or later, which
2461        // automatically synthesizes these stubs.
2462        OpFlags = X86II::MO_DARWIN_STUB;
2463      } else if (Subtarget->isPICStyleRIPRel() &&
2464                 isa<Function>(GV) &&
2465                 cast<Function>(GV)->hasFnAttr(Attribute::NonLazyBind)) {
2466        // If the function is marked as non-lazy, generate an indirect call
2467        // which loads from the GOT directly. This avoids runtime overhead
2468        // at the cost of eager binding (and one extra byte of encoding).
2469        OpFlags = X86II::MO_GOTPCREL;
2470        WrapperKind = X86ISD::WrapperRIP;
2471        ExtraLoad = true;
2472      }
2473
2474      Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
2475                                          G->getOffset(), OpFlags);
2476
2477      // Add a wrapper if needed.
2478      if (WrapperKind != ISD::DELETED_NODE)
2479        Callee = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Callee);
2480      // Add extra indirection if needed.
2481      if (ExtraLoad)
2482        Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Callee,
2483                             MachinePointerInfo::getGOT(),
2484                             false, false, false, 0);
2485    }
2486  } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2487    unsigned char OpFlags = 0;
2488
2489    // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
2490    // external symbols should go through the PLT.
2491    if (Subtarget->isTargetELF() &&
2492        getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2493      OpFlags = X86II::MO_PLT;
2494    } else if (Subtarget->isPICStyleStubAny() &&
2495               (!Subtarget->getTargetTriple().isMacOSX() ||
2496                Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2497      // PC-relative references to external symbols should go through $stub,
2498      // unless we're building with the leopard linker or later, which
2499      // automatically synthesizes these stubs.
2500      OpFlags = X86II::MO_DARWIN_STUB;
2501    }
2502
2503    Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
2504                                         OpFlags);
2505  }
2506
2507  // Returns a chain & a flag for retval copy to use.
2508  SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2509  SmallVector<SDValue, 8> Ops;
2510
2511  if (!IsSibcall && isTailCall) {
2512    Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
2513                           DAG.getIntPtrConstant(0, true), InFlag);
2514    InFlag = Chain.getValue(1);
2515  }
2516
2517  Ops.push_back(Chain);
2518  Ops.push_back(Callee);
2519
2520  if (isTailCall)
2521    Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
2522
2523  // Add argument registers to the end of the list so that they are known live
2524  // into the call.
2525  for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2526    Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2527                                  RegsToPass[i].second.getValueType()));
2528
2529  // Add a register mask operand representing the call-preserved registers.
2530  const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
2531  const uint32_t *Mask = TRI->getCallPreservedMask(CallConv);
2532  assert(Mask && "Missing call preserved mask for calling convention");
2533  Ops.push_back(DAG.getRegisterMask(Mask));
2534
2535  if (InFlag.getNode())
2536    Ops.push_back(InFlag);
2537
2538  if (isTailCall) {
2539    // We used to do:
2540    //// If this is the first return lowered for this function, add the regs
2541    //// to the liveout set for the function.
2542    // This isn't right, although it's probably harmless on x86; liveouts
2543    // should be computed from returns not tail calls.  Consider a void
2544    // function making a tail call to a function returning int.
2545    return DAG.getNode(X86ISD::TC_RETURN, dl,
2546                       NodeTys, &Ops[0], Ops.size());
2547  }
2548
2549  Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, &Ops[0], Ops.size());
2550  InFlag = Chain.getValue(1);
2551
2552  // Create the CALLSEQ_END node.
2553  unsigned NumBytesForCalleeToPush;
2554  if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2555                       getTargetMachine().Options.GuaranteedTailCallOpt))
2556    NumBytesForCalleeToPush = NumBytes;    // Callee pops everything
2557  else if (!Is64Bit && !IsTailCallConvention(CallConv) && !IsWindows &&
2558           SR == StackStructReturn)
2559    // If this is a call to a struct-return function, the callee
2560    // pops the hidden struct pointer, so we have to push it back.
2561    // This is common for Darwin/X86, Linux & Mingw32 targets.
2562    // For MSVC Win32 targets, the caller pops the hidden struct pointer.
2563    NumBytesForCalleeToPush = 4;
2564  else
2565    NumBytesForCalleeToPush = 0;  // Callee pops nothing.
2566
2567  // Returns a flag for retval copy to use.
2568  if (!IsSibcall) {
2569    Chain = DAG.getCALLSEQ_END(Chain,
2570                               DAG.getIntPtrConstant(NumBytes, true),
2571                               DAG.getIntPtrConstant(NumBytesForCalleeToPush,
2572                                                     true),
2573                               InFlag);
2574    InFlag = Chain.getValue(1);
2575  }
2576
2577  // Handle result values, copying them out of physregs into vregs that we
2578  // return.
2579  return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
2580                         Ins, dl, DAG, InVals);
2581}
2582
2583
2584//===----------------------------------------------------------------------===//
2585//                Fast Calling Convention (tail call) implementation
2586//===----------------------------------------------------------------------===//
2587
2588//  Like std call, callee cleans arguments, convention except that ECX is
2589//  reserved for storing the tail called function address. Only 2 registers are
2590//  free for argument passing (inreg). Tail call optimization is performed
2591//  provided:
2592//                * tailcallopt is enabled
2593//                * caller/callee are fastcc
2594//  On X86_64 architecture with GOT-style position independent code only local
2595//  (within module) calls are supported at the moment.
2596//  To keep the stack aligned according to platform abi the function
2597//  GetAlignedArgumentStackSize ensures that argument delta is always multiples
2598//  of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
2599//  If a tail called function callee has more arguments than the caller the
2600//  caller needs to make sure that there is room to move the RETADDR to. This is
2601//  achieved by reserving an area the size of the argument delta right after the
2602//  original REtADDR, but before the saved framepointer or the spilled registers
2603//  e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
2604//  stack layout:
2605//    arg1
2606//    arg2
2607//    RETADDR
2608//    [ new RETADDR
2609//      move area ]
2610//    (possible EBP)
2611//    ESI
2612//    EDI
2613//    local1 ..
2614
2615/// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
2616/// for a 16 byte align requirement.
2617unsigned
2618X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
2619                                               SelectionDAG& DAG) const {
2620  MachineFunction &MF = DAG.getMachineFunction();
2621  const TargetMachine &TM = MF.getTarget();
2622  const TargetFrameLowering &TFI = *TM.getFrameLowering();
2623  unsigned StackAlignment = TFI.getStackAlignment();
2624  uint64_t AlignMask = StackAlignment - 1;
2625  int64_t Offset = StackSize;
2626  uint64_t SlotSize = TD->getPointerSize();
2627  if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
2628    // Number smaller than 12 so just add the difference.
2629    Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
2630  } else {
2631    // Mask out lower bits, add stackalignment once plus the 12 bytes.
2632    Offset = ((~AlignMask) & Offset) + StackAlignment +
2633      (StackAlignment-SlotSize);
2634  }
2635  return Offset;
2636}
2637
2638/// MatchingStackOffset - Return true if the given stack call argument is
2639/// already available in the same position (relatively) of the caller's
2640/// incoming argument stack.
2641static
2642bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
2643                         MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
2644                         const X86InstrInfo *TII) {
2645  unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
2646  int FI = INT_MAX;
2647  if (Arg.getOpcode() == ISD::CopyFromReg) {
2648    unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
2649    if (!TargetRegisterInfo::isVirtualRegister(VR))
2650      return false;
2651    MachineInstr *Def = MRI->getVRegDef(VR);
2652    if (!Def)
2653      return false;
2654    if (!Flags.isByVal()) {
2655      if (!TII->isLoadFromStackSlot(Def, FI))
2656        return false;
2657    } else {
2658      unsigned Opcode = Def->getOpcode();
2659      if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r) &&
2660          Def->getOperand(1).isFI()) {
2661        FI = Def->getOperand(1).getIndex();
2662        Bytes = Flags.getByValSize();
2663      } else
2664        return false;
2665    }
2666  } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
2667    if (Flags.isByVal())
2668      // ByVal argument is passed in as a pointer but it's now being
2669      // dereferenced. e.g.
2670      // define @foo(%struct.X* %A) {
2671      //   tail call @bar(%struct.X* byval %A)
2672      // }
2673      return false;
2674    SDValue Ptr = Ld->getBasePtr();
2675    FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
2676    if (!FINode)
2677      return false;
2678    FI = FINode->getIndex();
2679  } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
2680    FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
2681    FI = FINode->getIndex();
2682    Bytes = Flags.getByValSize();
2683  } else
2684    return false;
2685
2686  assert(FI != INT_MAX);
2687  if (!MFI->isFixedObjectIndex(FI))
2688    return false;
2689  return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
2690}
2691
2692/// IsEligibleForTailCallOptimization - Check whether the call is eligible
2693/// for tail call optimization. Targets which want to do tail call
2694/// optimization should implement this function.
2695bool
2696X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
2697                                                     CallingConv::ID CalleeCC,
2698                                                     bool isVarArg,
2699                                                     bool isCalleeStructRet,
2700                                                     bool isCallerStructRet,
2701                                    const SmallVectorImpl<ISD::OutputArg> &Outs,
2702                                    const SmallVectorImpl<SDValue> &OutVals,
2703                                    const SmallVectorImpl<ISD::InputArg> &Ins,
2704                                                     SelectionDAG& DAG) const {
2705  if (!IsTailCallConvention(CalleeCC) &&
2706      CalleeCC != CallingConv::C)
2707    return false;
2708
2709  // If -tailcallopt is specified, make fastcc functions tail-callable.
2710  const MachineFunction &MF = DAG.getMachineFunction();
2711  const Function *CallerF = DAG.getMachineFunction().getFunction();
2712  CallingConv::ID CallerCC = CallerF->getCallingConv();
2713  bool CCMatch = CallerCC == CalleeCC;
2714
2715  if (getTargetMachine().Options.GuaranteedTailCallOpt) {
2716    if (IsTailCallConvention(CalleeCC) && CCMatch)
2717      return true;
2718    return false;
2719  }
2720
2721  // Look for obvious safe cases to perform tail call optimization that do not
2722  // require ABI changes. This is what gcc calls sibcall.
2723
2724  // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
2725  // emit a special epilogue.
2726  if (RegInfo->needsStackRealignment(MF))
2727    return false;
2728
2729  // Also avoid sibcall optimization if either caller or callee uses struct
2730  // return semantics.
2731  if (isCalleeStructRet || isCallerStructRet)
2732    return false;
2733
2734  // An stdcall caller is expected to clean up its arguments; the callee
2735  // isn't going to do that.
2736  if (!CCMatch && CallerCC==CallingConv::X86_StdCall)
2737    return false;
2738
2739  // Do not sibcall optimize vararg calls unless all arguments are passed via
2740  // registers.
2741  if (isVarArg && !Outs.empty()) {
2742
2743    // Optimizing for varargs on Win64 is unlikely to be safe without
2744    // additional testing.
2745    if (Subtarget->isTargetWin64())
2746      return false;
2747
2748    SmallVector<CCValAssign, 16> ArgLocs;
2749    CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
2750                   getTargetMachine(), ArgLocs, *DAG.getContext());
2751
2752    CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2753    for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
2754      if (!ArgLocs[i].isRegLoc())
2755        return false;
2756  }
2757
2758  // If the call result is in ST0 / ST1, it needs to be popped off the x87
2759  // stack.  Therefore, if it's not used by the call it is not safe to optimize
2760  // this into a sibcall.
2761  bool Unused = false;
2762  for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
2763    if (!Ins[i].Used) {
2764      Unused = true;
2765      break;
2766    }
2767  }
2768  if (Unused) {
2769    SmallVector<CCValAssign, 16> RVLocs;
2770    CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(),
2771                   getTargetMachine(), RVLocs, *DAG.getContext());
2772    CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2773    for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2774      CCValAssign &VA = RVLocs[i];
2775      if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1)
2776        return false;
2777    }
2778  }
2779
2780  // If the calling conventions do not match, then we'd better make sure the
2781  // results are returned in the same way as what the caller expects.
2782  if (!CCMatch) {
2783    SmallVector<CCValAssign, 16> RVLocs1;
2784    CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(),
2785                    getTargetMachine(), RVLocs1, *DAG.getContext());
2786    CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
2787
2788    SmallVector<CCValAssign, 16> RVLocs2;
2789    CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(),
2790                    getTargetMachine(), RVLocs2, *DAG.getContext());
2791    CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
2792
2793    if (RVLocs1.size() != RVLocs2.size())
2794      return false;
2795    for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
2796      if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
2797        return false;
2798      if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
2799        return false;
2800      if (RVLocs1[i].isRegLoc()) {
2801        if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
2802          return false;
2803      } else {
2804        if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
2805          return false;
2806      }
2807    }
2808  }
2809
2810  // If the callee takes no arguments then go on to check the results of the
2811  // call.
2812  if (!Outs.empty()) {
2813    // Check if stack adjustment is needed. For now, do not do this if any
2814    // argument is passed on the stack.
2815    SmallVector<CCValAssign, 16> ArgLocs;
2816    CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
2817                   getTargetMachine(), ArgLocs, *DAG.getContext());
2818
2819    // Allocate shadow area for Win64
2820    if (Subtarget->isTargetWin64()) {
2821      CCInfo.AllocateStack(32, 8);
2822    }
2823
2824    CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2825    if (CCInfo.getNextStackOffset()) {
2826      MachineFunction &MF = DAG.getMachineFunction();
2827      if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
2828        return false;
2829
2830      // Check if the arguments are already laid out in the right way as
2831      // the caller's fixed stack objects.
2832      MachineFrameInfo *MFI = MF.getFrameInfo();
2833      const MachineRegisterInfo *MRI = &MF.getRegInfo();
2834      const X86InstrInfo *TII =
2835        ((X86TargetMachine&)getTargetMachine()).getInstrInfo();
2836      for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2837        CCValAssign &VA = ArgLocs[i];
2838        SDValue Arg = OutVals[i];
2839        ISD::ArgFlagsTy Flags = Outs[i].Flags;
2840        if (VA.getLocInfo() == CCValAssign::Indirect)
2841          return false;
2842        if (!VA.isRegLoc()) {
2843          if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2844                                   MFI, MRI, TII))
2845            return false;
2846        }
2847      }
2848    }
2849
2850    // If the tailcall address may be in a register, then make sure it's
2851    // possible to register allocate for it. In 32-bit, the call address can
2852    // only target EAX, EDX, or ECX since the tail call must be scheduled after
2853    // callee-saved registers are restored. These happen to be the same
2854    // registers used to pass 'inreg' arguments so watch out for those.
2855    if (!Subtarget->is64Bit() &&
2856        !isa<GlobalAddressSDNode>(Callee) &&
2857        !isa<ExternalSymbolSDNode>(Callee)) {
2858      unsigned NumInRegs = 0;
2859      for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2860        CCValAssign &VA = ArgLocs[i];
2861        if (!VA.isRegLoc())
2862          continue;
2863        unsigned Reg = VA.getLocReg();
2864        switch (Reg) {
2865        default: break;
2866        case X86::EAX: case X86::EDX: case X86::ECX:
2867          if (++NumInRegs == 3)
2868            return false;
2869          break;
2870        }
2871      }
2872    }
2873  }
2874
2875  return true;
2876}
2877
2878FastISel *
2879X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
2880                                  const TargetLibraryInfo *libInfo) const {
2881  return X86::createFastISel(funcInfo, libInfo);
2882}
2883
2884
2885//===----------------------------------------------------------------------===//
2886//                           Other Lowering Hooks
2887//===----------------------------------------------------------------------===//
2888
2889static bool MayFoldLoad(SDValue Op) {
2890  return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
2891}
2892
2893static bool MayFoldIntoStore(SDValue Op) {
2894  return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
2895}
2896
2897static bool isTargetShuffle(unsigned Opcode) {
2898  switch(Opcode) {
2899  default: return false;
2900  case X86ISD::PSHUFD:
2901  case X86ISD::PSHUFHW:
2902  case X86ISD::PSHUFLW:
2903  case X86ISD::SHUFP:
2904  case X86ISD::PALIGN:
2905  case X86ISD::MOVLHPS:
2906  case X86ISD::MOVLHPD:
2907  case X86ISD::MOVHLPS:
2908  case X86ISD::MOVLPS:
2909  case X86ISD::MOVLPD:
2910  case X86ISD::MOVSHDUP:
2911  case X86ISD::MOVSLDUP:
2912  case X86ISD::MOVDDUP:
2913  case X86ISD::MOVSS:
2914  case X86ISD::MOVSD:
2915  case X86ISD::UNPCKL:
2916  case X86ISD::UNPCKH:
2917  case X86ISD::VPERMILP:
2918  case X86ISD::VPERM2X128:
2919  case X86ISD::VPERMI:
2920    return true;
2921  }
2922}
2923
2924static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2925                                    SDValue V1, SelectionDAG &DAG) {
2926  switch(Opc) {
2927  default: llvm_unreachable("Unknown x86 shuffle node");
2928  case X86ISD::MOVSHDUP:
2929  case X86ISD::MOVSLDUP:
2930  case X86ISD::MOVDDUP:
2931    return DAG.getNode(Opc, dl, VT, V1);
2932  }
2933}
2934
2935static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2936                                    SDValue V1, unsigned TargetMask,
2937                                    SelectionDAG &DAG) {
2938  switch(Opc) {
2939  default: llvm_unreachable("Unknown x86 shuffle node");
2940  case X86ISD::PSHUFD:
2941  case X86ISD::PSHUFHW:
2942  case X86ISD::PSHUFLW:
2943  case X86ISD::VPERMILP:
2944  case X86ISD::VPERMI:
2945    return DAG.getNode(Opc, dl, VT, V1, DAG.getConstant(TargetMask, MVT::i8));
2946  }
2947}
2948
2949static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2950                                    SDValue V1, SDValue V2, unsigned TargetMask,
2951                                    SelectionDAG &DAG) {
2952  switch(Opc) {
2953  default: llvm_unreachable("Unknown x86 shuffle node");
2954  case X86ISD::PALIGN:
2955  case X86ISD::SHUFP:
2956  case X86ISD::VPERM2X128:
2957    return DAG.getNode(Opc, dl, VT, V1, V2,
2958                       DAG.getConstant(TargetMask, MVT::i8));
2959  }
2960}
2961
2962static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2963                                    SDValue V1, SDValue V2, SelectionDAG &DAG) {
2964  switch(Opc) {
2965  default: llvm_unreachable("Unknown x86 shuffle node");
2966  case X86ISD::MOVLHPS:
2967  case X86ISD::MOVLHPD:
2968  case X86ISD::MOVHLPS:
2969  case X86ISD::MOVLPS:
2970  case X86ISD::MOVLPD:
2971  case X86ISD::MOVSS:
2972  case X86ISD::MOVSD:
2973  case X86ISD::UNPCKL:
2974  case X86ISD::UNPCKH:
2975    return DAG.getNode(Opc, dl, VT, V1, V2);
2976  }
2977}
2978
2979SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
2980  MachineFunction &MF = DAG.getMachineFunction();
2981  X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2982  int ReturnAddrIndex = FuncInfo->getRAIndex();
2983
2984  if (ReturnAddrIndex == 0) {
2985    // Set up a frame object for the return address.
2986    uint64_t SlotSize = TD->getPointerSize();
2987    ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize, -SlotSize,
2988                                                           false);
2989    FuncInfo->setRAIndex(ReturnAddrIndex);
2990  }
2991
2992  return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
2993}
2994
2995
2996bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
2997                                       bool hasSymbolicDisplacement) {
2998  // Offset should fit into 32 bit immediate field.
2999  if (!isInt<32>(Offset))
3000    return false;
3001
3002  // If we don't have a symbolic displacement - we don't have any extra
3003  // restrictions.
3004  if (!hasSymbolicDisplacement)
3005    return true;
3006
3007  // FIXME: Some tweaks might be needed for medium code model.
3008  if (M != CodeModel::Small && M != CodeModel::Kernel)
3009    return false;
3010
3011  // For small code model we assume that latest object is 16MB before end of 31
3012  // bits boundary. We may also accept pretty large negative constants knowing
3013  // that all objects are in the positive half of address space.
3014  if (M == CodeModel::Small && Offset < 16*1024*1024)
3015    return true;
3016
3017  // For kernel code model we know that all object resist in the negative half
3018  // of 32bits address space. We may not accept negative offsets, since they may
3019  // be just off and we may accept pretty large positive ones.
3020  if (M == CodeModel::Kernel && Offset > 0)
3021    return true;
3022
3023  return false;
3024}
3025
3026/// isCalleePop - Determines whether the callee is required to pop its
3027/// own arguments. Callee pop is necessary to support tail calls.
3028bool X86::isCalleePop(CallingConv::ID CallingConv,
3029                      bool is64Bit, bool IsVarArg, bool TailCallOpt) {
3030  if (IsVarArg)
3031    return false;
3032
3033  switch (CallingConv) {
3034  default:
3035    return false;
3036  case CallingConv::X86_StdCall:
3037    return !is64Bit;
3038  case CallingConv::X86_FastCall:
3039    return !is64Bit;
3040  case CallingConv::X86_ThisCall:
3041    return !is64Bit;
3042  case CallingConv::Fast:
3043    return TailCallOpt;
3044  case CallingConv::GHC:
3045    return TailCallOpt;
3046  }
3047}
3048
3049/// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
3050/// specific condition code, returning the condition code and the LHS/RHS of the
3051/// comparison to make.
3052static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
3053                               SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
3054  if (!isFP) {
3055    if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
3056      if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
3057        // X > -1   -> X == 0, jump !sign.
3058        RHS = DAG.getConstant(0, RHS.getValueType());
3059        return X86::COND_NS;
3060      }
3061      if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
3062        // X < 0   -> X == 0, jump on sign.
3063        return X86::COND_S;
3064      }
3065      if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
3066        // X < 1   -> X <= 0
3067        RHS = DAG.getConstant(0, RHS.getValueType());
3068        return X86::COND_LE;
3069      }
3070    }
3071
3072    switch (SetCCOpcode) {
3073    default: llvm_unreachable("Invalid integer condition!");
3074    case ISD::SETEQ:  return X86::COND_E;
3075    case ISD::SETGT:  return X86::COND_G;
3076    case ISD::SETGE:  return X86::COND_GE;
3077    case ISD::SETLT:  return X86::COND_L;
3078    case ISD::SETLE:  return X86::COND_LE;
3079    case ISD::SETNE:  return X86::COND_NE;
3080    case ISD::SETULT: return X86::COND_B;
3081    case ISD::SETUGT: return X86::COND_A;
3082    case ISD::SETULE: return X86::COND_BE;
3083    case ISD::SETUGE: return X86::COND_AE;
3084    }
3085  }
3086
3087  // First determine if it is required or is profitable to flip the operands.
3088
3089  // If LHS is a foldable load, but RHS is not, flip the condition.
3090  if (ISD::isNON_EXTLoad(LHS.getNode()) &&
3091      !ISD::isNON_EXTLoad(RHS.getNode())) {
3092    SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
3093    std::swap(LHS, RHS);
3094  }
3095
3096  switch (SetCCOpcode) {
3097  default: break;
3098  case ISD::SETOLT:
3099  case ISD::SETOLE:
3100  case ISD::SETUGT:
3101  case ISD::SETUGE:
3102    std::swap(LHS, RHS);
3103    break;
3104  }
3105
3106  // On a floating point condition, the flags are set as follows:
3107  // ZF  PF  CF   op
3108  //  0 | 0 | 0 | X > Y
3109  //  0 | 0 | 1 | X < Y
3110  //  1 | 0 | 0 | X == Y
3111  //  1 | 1 | 1 | unordered
3112  switch (SetCCOpcode) {
3113  default: llvm_unreachable("Condcode should be pre-legalized away");
3114  case ISD::SETUEQ:
3115  case ISD::SETEQ:   return X86::COND_E;
3116  case ISD::SETOLT:              // flipped
3117  case ISD::SETOGT:
3118  case ISD::SETGT:   return X86::COND_A;
3119  case ISD::SETOLE:              // flipped
3120  case ISD::SETOGE:
3121  case ISD::SETGE:   return X86::COND_AE;
3122  case ISD::SETUGT:              // flipped
3123  case ISD::SETULT:
3124  case ISD::SETLT:   return X86::COND_B;
3125  case ISD::SETUGE:              // flipped
3126  case ISD::SETULE:
3127  case ISD::SETLE:   return X86::COND_BE;
3128  case ISD::SETONE:
3129  case ISD::SETNE:   return X86::COND_NE;
3130  case ISD::SETUO:   return X86::COND_P;
3131  case ISD::SETO:    return X86::COND_NP;
3132  case ISD::SETOEQ:
3133  case ISD::SETUNE:  return X86::COND_INVALID;
3134  }
3135}
3136
3137/// hasFPCMov - is there a floating point cmov for the specific X86 condition
3138/// code. Current x86 isa includes the following FP cmov instructions:
3139/// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
3140static bool hasFPCMov(unsigned X86CC) {
3141  switch (X86CC) {
3142  default:
3143    return false;
3144  case X86::COND_B:
3145  case X86::COND_BE:
3146  case X86::COND_E:
3147  case X86::COND_P:
3148  case X86::COND_A:
3149  case X86::COND_AE:
3150  case X86::COND_NE:
3151  case X86::COND_NP:
3152    return true;
3153  }
3154}
3155
3156/// isFPImmLegal - Returns true if the target can instruction select the
3157/// specified FP immediate natively. If false, the legalizer will
3158/// materialize the FP immediate as a load from a constant pool.
3159bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3160  for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
3161    if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
3162      return true;
3163  }
3164  return false;
3165}
3166
3167/// isUndefOrInRange - Return true if Val is undef or if its value falls within
3168/// the specified range (L, H].
3169static bool isUndefOrInRange(int Val, int Low, int Hi) {
3170  return (Val < 0) || (Val >= Low && Val < Hi);
3171}
3172
3173/// isUndefOrEqual - Val is either less than zero (undef) or equal to the
3174/// specified value.
3175static bool isUndefOrEqual(int Val, int CmpVal) {
3176  if (Val < 0 || Val == CmpVal)
3177    return true;
3178  return false;
3179}
3180
3181/// isSequentialOrUndefInRange - Return true if every element in Mask, beginning
3182/// from position Pos and ending in Pos+Size, falls within the specified
3183/// sequential range (L, L+Pos]. or is undef.
3184static bool isSequentialOrUndefInRange(ArrayRef<int> Mask,
3185                                       unsigned Pos, unsigned Size, int Low) {
3186  for (unsigned i = Pos, e = Pos+Size; i != e; ++i, ++Low)
3187    if (!isUndefOrEqual(Mask[i], Low))
3188      return false;
3189  return true;
3190}
3191
3192/// isPSHUFDMask - Return true if the node specifies a shuffle of elements that
3193/// is suitable for input to PSHUFD or PSHUFW.  That is, it doesn't reference
3194/// the second operand.
3195static bool isPSHUFDMask(ArrayRef<int> Mask, EVT VT) {
3196  if (VT == MVT::v4f32 || VT == MVT::v4i32 )
3197    return (Mask[0] < 4 && Mask[1] < 4 && Mask[2] < 4 && Mask[3] < 4);
3198  if (VT == MVT::v2f64 || VT == MVT::v2i64)
3199    return (Mask[0] < 2 && Mask[1] < 2);
3200  return false;
3201}
3202
3203/// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that
3204/// is suitable for input to PSHUFHW.
3205static bool isPSHUFHWMask(ArrayRef<int> Mask, EVT VT, bool HasAVX2) {
3206  if (VT != MVT::v8i16 && (!HasAVX2 || VT != MVT::v16i16))
3207    return false;
3208
3209  // Lower quadword copied in order or undef.
3210  if (!isSequentialOrUndefInRange(Mask, 0, 4, 0))
3211    return false;
3212
3213  // Upper quadword shuffled.
3214  for (unsigned i = 4; i != 8; ++i)
3215    if (!isUndefOrInRange(Mask[i], 4, 8))
3216      return false;
3217
3218  if (VT == MVT::v16i16) {
3219    // Lower quadword copied in order or undef.
3220    if (!isSequentialOrUndefInRange(Mask, 8, 4, 8))
3221      return false;
3222
3223    // Upper quadword shuffled.
3224    for (unsigned i = 12; i != 16; ++i)
3225      if (!isUndefOrInRange(Mask[i], 12, 16))
3226        return false;
3227  }
3228
3229  return true;
3230}
3231
3232/// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that
3233/// is suitable for input to PSHUFLW.
3234static bool isPSHUFLWMask(ArrayRef<int> Mask, EVT VT, bool HasAVX2) {
3235  if (VT != MVT::v8i16 && (!HasAVX2 || VT != MVT::v16i16))
3236    return false;
3237
3238  // Upper quadword copied in order.
3239  if (!isSequentialOrUndefInRange(Mask, 4, 4, 4))
3240    return false;
3241
3242  // Lower quadword shuffled.
3243  for (unsigned i = 0; i != 4; ++i)
3244    if (!isUndefOrInRange(Mask[i], 0, 4))
3245      return false;
3246
3247  if (VT == MVT::v16i16) {
3248    // Upper quadword copied in order.
3249    if (!isSequentialOrUndefInRange(Mask, 12, 4, 12))
3250      return false;
3251
3252    // Lower quadword shuffled.
3253    for (unsigned i = 8; i != 12; ++i)
3254      if (!isUndefOrInRange(Mask[i], 8, 12))
3255        return false;
3256  }
3257
3258  return true;
3259}
3260
3261/// isPALIGNRMask - Return true if the node specifies a shuffle of elements that
3262/// is suitable for input to PALIGNR.
3263static bool isPALIGNRMask(ArrayRef<int> Mask, EVT VT,
3264                          const X86Subtarget *Subtarget) {
3265  if ((VT.getSizeInBits() == 128 && !Subtarget->hasSSSE3()) ||
3266      (VT.getSizeInBits() == 256 && !Subtarget->hasAVX2()))
3267    return false;
3268
3269  unsigned NumElts = VT.getVectorNumElements();
3270  unsigned NumLanes = VT.getSizeInBits()/128;
3271  unsigned NumLaneElts = NumElts/NumLanes;
3272
3273  // Do not handle 64-bit element shuffles with palignr.
3274  if (NumLaneElts == 2)
3275    return false;
3276
3277  for (unsigned l = 0; l != NumElts; l+=NumLaneElts) {
3278    unsigned i;
3279    for (i = 0; i != NumLaneElts; ++i) {
3280      if (Mask[i+l] >= 0)
3281        break;
3282    }
3283
3284    // Lane is all undef, go to next lane
3285    if (i == NumLaneElts)
3286      continue;
3287
3288    int Start = Mask[i+l];
3289
3290    // Make sure its in this lane in one of the sources
3291    if (!isUndefOrInRange(Start, l, l+NumLaneElts) &&
3292        !isUndefOrInRange(Start, l+NumElts, l+NumElts+NumLaneElts))
3293      return false;
3294
3295    // If not lane 0, then we must match lane 0
3296    if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Start, Mask[i]+l))
3297      return false;
3298
3299    // Correct second source to be contiguous with first source
3300    if (Start >= (int)NumElts)
3301      Start -= NumElts - NumLaneElts;
3302
3303    // Make sure we're shifting in the right direction.
3304    if (Start <= (int)(i+l))
3305      return false;
3306
3307    Start -= i;
3308
3309    // Check the rest of the elements to see if they are consecutive.
3310    for (++i; i != NumLaneElts; ++i) {
3311      int Idx = Mask[i+l];
3312
3313      // Make sure its in this lane
3314      if (!isUndefOrInRange(Idx, l, l+NumLaneElts) &&
3315          !isUndefOrInRange(Idx, l+NumElts, l+NumElts+NumLaneElts))
3316        return false;
3317
3318      // If not lane 0, then we must match lane 0
3319      if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Idx, Mask[i]+l))
3320        return false;
3321
3322      if (Idx >= (int)NumElts)
3323        Idx -= NumElts - NumLaneElts;
3324
3325      if (!isUndefOrEqual(Idx, Start+i))
3326        return false;
3327
3328    }
3329  }
3330
3331  return true;
3332}
3333
3334/// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
3335/// the two vector operands have swapped position.
3336static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask,
3337                                     unsigned NumElems) {
3338  for (unsigned i = 0; i != NumElems; ++i) {
3339    int idx = Mask[i];
3340    if (idx < 0)
3341      continue;
3342    else if (idx < (int)NumElems)
3343      Mask[i] = idx + NumElems;
3344    else
3345      Mask[i] = idx - NumElems;
3346  }
3347}
3348
3349/// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
3350/// specifies a shuffle of elements that is suitable for input to 128/256-bit
3351/// SHUFPS and SHUFPD. If Commuted is true, then it checks for sources to be
3352/// reverse of what x86 shuffles want.
3353static bool isSHUFPMask(ArrayRef<int> Mask, EVT VT, bool HasAVX,
3354                        bool Commuted = false) {
3355  if (!HasAVX && VT.getSizeInBits() == 256)
3356    return false;
3357
3358  unsigned NumElems = VT.getVectorNumElements();
3359  unsigned NumLanes = VT.getSizeInBits()/128;
3360  unsigned NumLaneElems = NumElems/NumLanes;
3361
3362  if (NumLaneElems != 2 && NumLaneElems != 4)
3363    return false;
3364
3365  // VSHUFPSY divides the resulting vector into 4 chunks.
3366  // The sources are also splitted into 4 chunks, and each destination
3367  // chunk must come from a different source chunk.
3368  //
3369  //  SRC1 =>   X7    X6    X5    X4    X3    X2    X1    X0
3370  //  SRC2 =>   Y7    Y6    Y5    Y4    Y3    Y2    Y1    Y9
3371  //
3372  //  DST  =>  Y7..Y4,   Y7..Y4,   X7..X4,   X7..X4,
3373  //           Y3..Y0,   Y3..Y0,   X3..X0,   X3..X0
3374  //
3375  // VSHUFPDY divides the resulting vector into 4 chunks.
3376  // The sources are also splitted into 4 chunks, and each destination
3377  // chunk must come from a different source chunk.
3378  //
3379  //  SRC1 =>      X3       X2       X1       X0
3380  //  SRC2 =>      Y3       Y2       Y1       Y0
3381  //
3382  //  DST  =>  Y3..Y2,  X3..X2,  Y1..Y0,  X1..X0
3383  //
3384  unsigned HalfLaneElems = NumLaneElems/2;
3385  for (unsigned l = 0; l != NumElems; l += NumLaneElems) {
3386    for (unsigned i = 0; i != NumLaneElems; ++i) {
3387      int Idx = Mask[i+l];
3388      unsigned RngStart = l + ((Commuted == (i<HalfLaneElems)) ? NumElems : 0);
3389      if (!isUndefOrInRange(Idx, RngStart, RngStart+NumLaneElems))
3390        return false;
3391      // For VSHUFPSY, the mask of the second half must be the same as the
3392      // first but with the appropriate offsets. This works in the same way as
3393      // VPERMILPS works with masks.
3394      if (NumElems != 8 || l == 0 || Mask[i] < 0)
3395        continue;
3396      if (!isUndefOrEqual(Idx, Mask[i]+l))
3397        return false;
3398    }
3399  }
3400
3401  return true;
3402}
3403
3404/// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
3405/// specifies a shuffle of elements that is suitable for input to MOVHLPS.
3406static bool isMOVHLPSMask(ArrayRef<int> Mask, EVT VT) {
3407  if (!VT.is128BitVector())
3408    return false;
3409
3410  unsigned NumElems = VT.getVectorNumElements();
3411
3412  if (NumElems != 4)
3413    return false;
3414
3415  // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
3416  return isUndefOrEqual(Mask[0], 6) &&
3417         isUndefOrEqual(Mask[1], 7) &&
3418         isUndefOrEqual(Mask[2], 2) &&
3419         isUndefOrEqual(Mask[3], 3);
3420}
3421
3422/// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
3423/// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
3424/// <2, 3, 2, 3>
3425static bool isMOVHLPS_v_undef_Mask(ArrayRef<int> Mask, EVT VT) {
3426  if (!VT.is128BitVector())
3427    return false;
3428
3429  unsigned NumElems = VT.getVectorNumElements();
3430
3431  if (NumElems != 4)
3432    return false;
3433
3434  return isUndefOrEqual(Mask[0], 2) &&
3435         isUndefOrEqual(Mask[1], 3) &&
3436         isUndefOrEqual(Mask[2], 2) &&
3437         isUndefOrEqual(Mask[3], 3);
3438}
3439
3440/// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
3441/// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
3442static bool isMOVLPMask(ArrayRef<int> Mask, EVT VT) {
3443  if (!VT.is128BitVector())
3444    return false;
3445
3446  unsigned NumElems = VT.getVectorNumElements();
3447
3448  if (NumElems != 2 && NumElems != 4)
3449    return false;
3450
3451  for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3452    if (!isUndefOrEqual(Mask[i], i + NumElems))
3453      return false;
3454
3455  for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
3456    if (!isUndefOrEqual(Mask[i], i))
3457      return false;
3458
3459  return true;
3460}
3461
3462/// isMOVLHPSMask - Return true if the specified VECTOR_SHUFFLE operand
3463/// specifies a shuffle of elements that is suitable for input to MOVLHPS.
3464static bool isMOVLHPSMask(ArrayRef<int> Mask, EVT VT) {
3465  if (!VT.is128BitVector())
3466    return false;
3467
3468  unsigned NumElems = VT.getVectorNumElements();
3469
3470  if (NumElems != 2 && NumElems != 4)
3471    return false;
3472
3473  for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3474    if (!isUndefOrEqual(Mask[i], i))
3475      return false;
3476
3477  for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3478    if (!isUndefOrEqual(Mask[i + e], i + NumElems))
3479      return false;
3480
3481  return true;
3482}
3483
3484//
3485// Some special combinations that can be optimized.
3486//
3487static
3488SDValue Compact8x32ShuffleNode(ShuffleVectorSDNode *SVOp,
3489                               SelectionDAG &DAG) {
3490  EVT VT = SVOp->getValueType(0);
3491  DebugLoc dl = SVOp->getDebugLoc();
3492
3493  if (VT != MVT::v8i32 && VT != MVT::v8f32)
3494    return SDValue();
3495
3496  ArrayRef<int> Mask = SVOp->getMask();
3497
3498  // These are the special masks that may be optimized.
3499  static const int MaskToOptimizeEven[] = {0, 8, 2, 10, 4, 12, 6, 14};
3500  static const int MaskToOptimizeOdd[]  = {1, 9, 3, 11, 5, 13, 7, 15};
3501  bool MatchEvenMask = true;
3502  bool MatchOddMask  = true;
3503  for (int i=0; i<8; ++i) {
3504    if (!isUndefOrEqual(Mask[i], MaskToOptimizeEven[i]))
3505      MatchEvenMask = false;
3506    if (!isUndefOrEqual(Mask[i], MaskToOptimizeOdd[i]))
3507      MatchOddMask = false;
3508  }
3509  static const int CompactionMaskEven[] = {0, 2, -1, -1, 4, 6, -1, -1};
3510  static const int CompactionMaskOdd [] = {1, 3, -1, -1, 5, 7, -1, -1};
3511
3512  const int *CompactionMask;
3513  if (MatchEvenMask)
3514    CompactionMask = CompactionMaskEven;
3515  else if (MatchOddMask)
3516    CompactionMask = CompactionMaskOdd;
3517  else
3518    return SDValue();
3519
3520  SDValue UndefNode = DAG.getNode(ISD::UNDEF, dl, VT);
3521
3522  SDValue Op0 = DAG.getVectorShuffle(VT, dl, SVOp->getOperand(0),
3523                                     UndefNode, CompactionMask);
3524  SDValue Op1 = DAG.getVectorShuffle(VT, dl, SVOp->getOperand(1),
3525                                     UndefNode, CompactionMask);
3526  static const int UnpackMask[] = {0, 8, 1, 9, 4, 12, 5, 13};
3527  return DAG.getVectorShuffle(VT, dl, Op0, Op1, UnpackMask);
3528}
3529
3530/// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
3531/// specifies a shuffle of elements that is suitable for input to UNPCKL.
3532static bool isUNPCKLMask(ArrayRef<int> Mask, EVT VT,
3533                         bool HasAVX2, bool V2IsSplat = false) {
3534  unsigned NumElts = VT.getVectorNumElements();
3535
3536  assert((VT.is128BitVector() || VT.is256BitVector()) &&
3537         "Unsupported vector type for unpckh");
3538
3539  if (VT.getSizeInBits() == 256 && NumElts != 4 && NumElts != 8 &&
3540      (!HasAVX2 || (NumElts != 16 && NumElts != 32)))
3541    return false;
3542
3543  // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3544  // independently on 128-bit lanes.
3545  unsigned NumLanes = VT.getSizeInBits()/128;
3546  unsigned NumLaneElts = NumElts/NumLanes;
3547
3548  for (unsigned l = 0; l != NumLanes; ++l) {
3549    for (unsigned i = l*NumLaneElts, j = l*NumLaneElts;
3550         i != (l+1)*NumLaneElts;
3551         i += 2, ++j) {
3552      int BitI  = Mask[i];
3553      int BitI1 = Mask[i+1];
3554      if (!isUndefOrEqual(BitI, j))
3555        return false;
3556      if (V2IsSplat) {
3557        if (!isUndefOrEqual(BitI1, NumElts))
3558          return false;
3559      } else {
3560        if (!isUndefOrEqual(BitI1, j + NumElts))
3561          return false;
3562      }
3563    }
3564  }
3565
3566  return true;
3567}
3568
3569/// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
3570/// specifies a shuffle of elements that is suitable for input to UNPCKH.
3571static bool isUNPCKHMask(ArrayRef<int> Mask, EVT VT,
3572                         bool HasAVX2, bool V2IsSplat = false) {
3573  unsigned NumElts = VT.getVectorNumElements();
3574
3575  assert((VT.is128BitVector() || VT.is256BitVector()) &&
3576         "Unsupported vector type for unpckh");
3577
3578  if (VT.getSizeInBits() == 256 && NumElts != 4 && NumElts != 8 &&
3579      (!HasAVX2 || (NumElts != 16 && NumElts != 32)))
3580    return false;
3581
3582  // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3583  // independently on 128-bit lanes.
3584  unsigned NumLanes = VT.getSizeInBits()/128;
3585  unsigned NumLaneElts = NumElts/NumLanes;
3586
3587  for (unsigned l = 0; l != NumLanes; ++l) {
3588    for (unsigned i = l*NumLaneElts, j = (l*NumLaneElts)+NumLaneElts/2;
3589         i != (l+1)*NumLaneElts; i += 2, ++j) {
3590      int BitI  = Mask[i];
3591      int BitI1 = Mask[i+1];
3592      if (!isUndefOrEqual(BitI, j))
3593        return false;
3594      if (V2IsSplat) {
3595        if (isUndefOrEqual(BitI1, NumElts))
3596          return false;
3597      } else {
3598        if (!isUndefOrEqual(BitI1, j+NumElts))
3599          return false;
3600      }
3601    }
3602  }
3603  return true;
3604}
3605
3606/// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
3607/// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
3608/// <0, 0, 1, 1>
3609static bool isUNPCKL_v_undef_Mask(ArrayRef<int> Mask, EVT VT,
3610                                  bool HasAVX2) {
3611  unsigned NumElts = VT.getVectorNumElements();
3612
3613  assert((VT.is128BitVector() || VT.is256BitVector()) &&
3614         "Unsupported vector type for unpckh");
3615
3616  if (VT.getSizeInBits() == 256 && NumElts != 4 && NumElts != 8 &&
3617      (!HasAVX2 || (NumElts != 16 && NumElts != 32)))
3618    return false;
3619
3620  // For 256-bit i64/f64, use MOVDDUPY instead, so reject the matching pattern
3621  // FIXME: Need a better way to get rid of this, there's no latency difference
3622  // between UNPCKLPD and MOVDDUP, the later should always be checked first and
3623  // the former later. We should also remove the "_undef" special mask.
3624  if (NumElts == 4 && VT.getSizeInBits() == 256)
3625    return false;
3626
3627  // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3628  // independently on 128-bit lanes.
3629  unsigned NumLanes = VT.getSizeInBits()/128;
3630  unsigned NumLaneElts = NumElts/NumLanes;
3631
3632  for (unsigned l = 0; l != NumLanes; ++l) {
3633    for (unsigned i = l*NumLaneElts, j = l*NumLaneElts;
3634         i != (l+1)*NumLaneElts;
3635         i += 2, ++j) {
3636      int BitI  = Mask[i];
3637      int BitI1 = Mask[i+1];
3638
3639      if (!isUndefOrEqual(BitI, j))
3640        return false;
3641      if (!isUndefOrEqual(BitI1, j))
3642        return false;
3643    }
3644  }
3645
3646  return true;
3647}
3648
3649/// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
3650/// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
3651/// <2, 2, 3, 3>
3652static bool isUNPCKH_v_undef_Mask(ArrayRef<int> Mask, EVT VT, bool HasAVX2) {
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 (!isUndefOrEqual(BitI1, j))
3675        return false;
3676    }
3677  }
3678  return true;
3679}
3680
3681/// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
3682/// specifies a shuffle of elements that is suitable for input to MOVSS,
3683/// MOVSD, and MOVD, i.e. setting the lowest element.
3684static bool isMOVLMask(ArrayRef<int> Mask, EVT VT) {
3685  if (VT.getVectorElementType().getSizeInBits() < 32)
3686    return false;
3687  if (!VT.is128BitVector())
3688    return false;
3689
3690  unsigned NumElts = VT.getVectorNumElements();
3691
3692  if (!isUndefOrEqual(Mask[0], NumElts))
3693    return false;
3694
3695  for (unsigned i = 1; i != NumElts; ++i)
3696    if (!isUndefOrEqual(Mask[i], i))
3697      return false;
3698
3699  return true;
3700}
3701
3702/// isVPERM2X128Mask - Match 256-bit shuffles where the elements are considered
3703/// as permutations between 128-bit chunks or halves. As an example: this
3704/// shuffle bellow:
3705///   vector_shuffle <4, 5, 6, 7, 12, 13, 14, 15>
3706/// The first half comes from the second half of V1 and the second half from the
3707/// the second half of V2.
3708static bool isVPERM2X128Mask(ArrayRef<int> Mask, EVT VT, bool HasAVX) {
3709  if (!HasAVX || !VT.is256BitVector())
3710    return false;
3711
3712  // The shuffle result is divided into half A and half B. In total the two
3713  // sources have 4 halves, namely: C, D, E, F. The final values of A and
3714  // B must come from C, D, E or F.
3715  unsigned HalfSize = VT.getVectorNumElements()/2;
3716  bool MatchA = false, MatchB = false;
3717
3718  // Check if A comes from one of C, D, E, F.
3719  for (unsigned Half = 0; Half != 4; ++Half) {
3720    if (isSequentialOrUndefInRange(Mask, 0, HalfSize, Half*HalfSize)) {
3721      MatchA = true;
3722      break;
3723    }
3724  }
3725
3726  // Check if B comes from one of C, D, E, F.
3727  for (unsigned Half = 0; Half != 4; ++Half) {
3728    if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, Half*HalfSize)) {
3729      MatchB = true;
3730      break;
3731    }
3732  }
3733
3734  return MatchA && MatchB;
3735}
3736
3737/// getShuffleVPERM2X128Immediate - Return the appropriate immediate to shuffle
3738/// the specified VECTOR_MASK mask with VPERM2F128/VPERM2I128 instructions.
3739static unsigned getShuffleVPERM2X128Immediate(ShuffleVectorSDNode *SVOp) {
3740  EVT VT = SVOp->getValueType(0);
3741
3742  unsigned HalfSize = VT.getVectorNumElements()/2;
3743
3744  unsigned FstHalf = 0, SndHalf = 0;
3745  for (unsigned i = 0; i < HalfSize; ++i) {
3746    if (SVOp->getMaskElt(i) > 0) {
3747      FstHalf = SVOp->getMaskElt(i)/HalfSize;
3748      break;
3749    }
3750  }
3751  for (unsigned i = HalfSize; i < HalfSize*2; ++i) {
3752    if (SVOp->getMaskElt(i) > 0) {
3753      SndHalf = SVOp->getMaskElt(i)/HalfSize;
3754      break;
3755    }
3756  }
3757
3758  return (FstHalf | (SndHalf << 4));
3759}
3760
3761/// isVPERMILPMask - Return true if the specified VECTOR_SHUFFLE operand
3762/// specifies a shuffle of elements that is suitable for input to VPERMILPD*.
3763/// Note that VPERMIL mask matching is different depending whether theunderlying
3764/// type is 32 or 64. In the VPERMILPS the high half of the mask should point
3765/// to the same elements of the low, but to the higher half of the source.
3766/// In VPERMILPD the two lanes could be shuffled independently of each other
3767/// with the same restriction that lanes can't be crossed. Also handles PSHUFDY.
3768static bool isVPERMILPMask(ArrayRef<int> Mask, EVT VT, bool HasAVX) {
3769  if (!HasAVX)
3770    return false;
3771
3772  unsigned NumElts = VT.getVectorNumElements();
3773  // Only match 256-bit with 32/64-bit types
3774  if (VT.getSizeInBits() != 256 || (NumElts != 4 && NumElts != 8))
3775    return false;
3776
3777  unsigned NumLanes = VT.getSizeInBits()/128;
3778  unsigned LaneSize = NumElts/NumLanes;
3779  for (unsigned l = 0; l != NumElts; l += LaneSize) {
3780    for (unsigned i = 0; i != LaneSize; ++i) {
3781      if (!isUndefOrInRange(Mask[i+l], l, l+LaneSize))
3782        return false;
3783      if (NumElts != 8 || l == 0)
3784        continue;
3785      // VPERMILPS handling
3786      if (Mask[i] < 0)
3787        continue;
3788      if (!isUndefOrEqual(Mask[i+l], Mask[i]+l))
3789        return false;
3790    }
3791  }
3792
3793  return true;
3794}
3795
3796/// isCommutedMOVLMask - Returns true if the shuffle mask is except the reverse
3797/// of what x86 movss want. X86 movs requires the lowest  element to be lowest
3798/// element of vector 2 and the other elements to come from vector 1 in order.
3799static bool isCommutedMOVLMask(ArrayRef<int> Mask, EVT VT,
3800                               bool V2IsSplat = false, bool V2IsUndef = false) {
3801  if (!VT.is128BitVector())
3802    return false;
3803
3804  unsigned NumOps = VT.getVectorNumElements();
3805  if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
3806    return false;
3807
3808  if (!isUndefOrEqual(Mask[0], 0))
3809    return false;
3810
3811  for (unsigned i = 1; i != NumOps; ++i)
3812    if (!(isUndefOrEqual(Mask[i], i+NumOps) ||
3813          (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) ||
3814          (V2IsSplat && isUndefOrEqual(Mask[i], NumOps))))
3815      return false;
3816
3817  return true;
3818}
3819
3820/// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3821/// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
3822/// Masks to match: <1, 1, 3, 3> or <1, 1, 3, 3, 5, 5, 7, 7>
3823static bool isMOVSHDUPMask(ArrayRef<int> Mask, EVT VT,
3824                           const X86Subtarget *Subtarget) {
3825  if (!Subtarget->hasSSE3())
3826    return false;
3827
3828  unsigned NumElems = VT.getVectorNumElements();
3829
3830  if ((VT.getSizeInBits() == 128 && NumElems != 4) ||
3831      (VT.getSizeInBits() == 256 && NumElems != 8))
3832    return false;
3833
3834  // "i+1" is the value the indexed mask element must have
3835  for (unsigned i = 0; i != NumElems; i += 2)
3836    if (!isUndefOrEqual(Mask[i], i+1) ||
3837        !isUndefOrEqual(Mask[i+1], i+1))
3838      return false;
3839
3840  return true;
3841}
3842
3843/// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3844/// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
3845/// Masks to match: <0, 0, 2, 2> or <0, 0, 2, 2, 4, 4, 6, 6>
3846static bool isMOVSLDUPMask(ArrayRef<int> Mask, EVT VT,
3847                           const X86Subtarget *Subtarget) {
3848  if (!Subtarget->hasSSE3())
3849    return false;
3850
3851  unsigned NumElems = VT.getVectorNumElements();
3852
3853  if ((VT.getSizeInBits() == 128 && NumElems != 4) ||
3854      (VT.getSizeInBits() == 256 && NumElems != 8))
3855    return false;
3856
3857  // "i" is the value the indexed mask element must have
3858  for (unsigned i = 0; i != NumElems; i += 2)
3859    if (!isUndefOrEqual(Mask[i], i) ||
3860        !isUndefOrEqual(Mask[i+1], i))
3861      return false;
3862
3863  return true;
3864}
3865
3866/// isMOVDDUPYMask - Return true if the specified VECTOR_SHUFFLE operand
3867/// specifies a shuffle of elements that is suitable for input to 256-bit
3868/// version of MOVDDUP.
3869static bool isMOVDDUPYMask(ArrayRef<int> Mask, EVT VT, bool HasAVX) {
3870  if (!HasAVX || !VT.is256BitVector())
3871    return false;
3872
3873  unsigned NumElts = VT.getVectorNumElements();
3874  if (NumElts != 4)
3875    return false;
3876
3877  for (unsigned i = 0; i != NumElts/2; ++i)
3878    if (!isUndefOrEqual(Mask[i], 0))
3879      return false;
3880  for (unsigned i = NumElts/2; i != NumElts; ++i)
3881    if (!isUndefOrEqual(Mask[i], NumElts/2))
3882      return false;
3883  return true;
3884}
3885
3886/// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3887/// specifies a shuffle of elements that is suitable for input to 128-bit
3888/// version of MOVDDUP.
3889static bool isMOVDDUPMask(ArrayRef<int> Mask, EVT VT) {
3890  if (!VT.is128BitVector())
3891    return false;
3892
3893  unsigned e = VT.getVectorNumElements() / 2;
3894  for (unsigned i = 0; i != e; ++i)
3895    if (!isUndefOrEqual(Mask[i], i))
3896      return false;
3897  for (unsigned i = 0; i != e; ++i)
3898    if (!isUndefOrEqual(Mask[e+i], i))
3899      return false;
3900  return true;
3901}
3902
3903/// isVEXTRACTF128Index - Return true if the specified
3904/// EXTRACT_SUBVECTOR operand specifies a vector extract that is
3905/// suitable for input to VEXTRACTF128.
3906bool X86::isVEXTRACTF128Index(SDNode *N) {
3907  if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
3908    return false;
3909
3910  // The index should be aligned on a 128-bit boundary.
3911  uint64_t Index =
3912    cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
3913
3914  unsigned VL = N->getValueType(0).getVectorNumElements();
3915  unsigned VBits = N->getValueType(0).getSizeInBits();
3916  unsigned ElSize = VBits / VL;
3917  bool Result = (Index * ElSize) % 128 == 0;
3918
3919  return Result;
3920}
3921
3922/// isVINSERTF128Index - Return true if the specified INSERT_SUBVECTOR
3923/// operand specifies a subvector insert that is suitable for input to
3924/// VINSERTF128.
3925bool X86::isVINSERTF128Index(SDNode *N) {
3926  if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
3927    return false;
3928
3929  // The index should be aligned on a 128-bit boundary.
3930  uint64_t Index =
3931    cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
3932
3933  unsigned VL = N->getValueType(0).getVectorNumElements();
3934  unsigned VBits = N->getValueType(0).getSizeInBits();
3935  unsigned ElSize = VBits / VL;
3936  bool Result = (Index * ElSize) % 128 == 0;
3937
3938  return Result;
3939}
3940
3941/// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
3942/// the specified VECTOR_SHUFFLE mask with PSHUF* and SHUFP* instructions.
3943/// Handles 128-bit and 256-bit.
3944static unsigned getShuffleSHUFImmediate(ShuffleVectorSDNode *N) {
3945  EVT VT = N->getValueType(0);
3946
3947  assert((VT.is128BitVector() || VT.is256BitVector()) &&
3948         "Unsupported vector type for PSHUF/SHUFP");
3949
3950  // Handle 128 and 256-bit vector lengths. AVX defines PSHUF/SHUFP to operate
3951  // independently on 128-bit lanes.
3952  unsigned NumElts = VT.getVectorNumElements();
3953  unsigned NumLanes = VT.getSizeInBits()/128;
3954  unsigned NumLaneElts = NumElts/NumLanes;
3955
3956  assert((NumLaneElts == 2 || NumLaneElts == 4) &&
3957         "Only supports 2 or 4 elements per lane");
3958
3959  unsigned Shift = (NumLaneElts == 4) ? 1 : 0;
3960  unsigned Mask = 0;
3961  for (unsigned i = 0; i != NumElts; ++i) {
3962    int Elt = N->getMaskElt(i);
3963    if (Elt < 0) continue;
3964    Elt &= NumLaneElts - 1;
3965    unsigned ShAmt = (i << Shift) % 8;
3966    Mask |= Elt << ShAmt;
3967  }
3968
3969  return Mask;
3970}
3971
3972/// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
3973/// the specified VECTOR_SHUFFLE mask with the PSHUFHW instruction.
3974static unsigned getShufflePSHUFHWImmediate(ShuffleVectorSDNode *N) {
3975  EVT VT = N->getValueType(0);
3976
3977  assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
3978         "Unsupported vector type for PSHUFHW");
3979
3980  unsigned NumElts = VT.getVectorNumElements();
3981
3982  unsigned Mask = 0;
3983  for (unsigned l = 0; l != NumElts; l += 8) {
3984    // 8 nodes per lane, but we only care about the last 4.
3985    for (unsigned i = 0; i < 4; ++i) {
3986      int Elt = N->getMaskElt(l+i+4);
3987      if (Elt < 0) continue;
3988      Elt &= 0x3; // only 2-bits.
3989      Mask |= Elt << (i * 2);
3990    }
3991  }
3992
3993  return Mask;
3994}
3995
3996/// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
3997/// the specified VECTOR_SHUFFLE mask with the PSHUFLW instruction.
3998static unsigned getShufflePSHUFLWImmediate(ShuffleVectorSDNode *N) {
3999  EVT VT = N->getValueType(0);
4000
4001  assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4002         "Unsupported vector type for PSHUFHW");
4003
4004  unsigned NumElts = VT.getVectorNumElements();
4005
4006  unsigned Mask = 0;
4007  for (unsigned l = 0; l != NumElts; l += 8) {
4008    // 8 nodes per lane, but we only care about the first 4.
4009    for (unsigned i = 0; i < 4; ++i) {
4010      int Elt = N->getMaskElt(l+i);
4011      if (Elt < 0) continue;
4012      Elt &= 0x3; // only 2-bits
4013      Mask |= Elt << (i * 2);
4014    }
4015  }
4016
4017  return Mask;
4018}
4019
4020/// getShufflePALIGNRImmediate - Return the appropriate immediate to shuffle
4021/// the specified VECTOR_SHUFFLE mask with the PALIGNR instruction.
4022static unsigned getShufflePALIGNRImmediate(ShuffleVectorSDNode *SVOp) {
4023  EVT VT = SVOp->getValueType(0);
4024  unsigned EltSize = VT.getVectorElementType().getSizeInBits() >> 3;
4025
4026  unsigned NumElts = VT.getVectorNumElements();
4027  unsigned NumLanes = VT.getSizeInBits()/128;
4028  unsigned NumLaneElts = NumElts/NumLanes;
4029
4030  int Val = 0;
4031  unsigned i;
4032  for (i = 0; i != NumElts; ++i) {
4033    Val = SVOp->getMaskElt(i);
4034    if (Val >= 0)
4035      break;
4036  }
4037  if (Val >= (int)NumElts)
4038    Val -= NumElts - NumLaneElts;
4039
4040  assert(Val - i > 0 && "PALIGNR imm should be positive");
4041  return (Val - i) * EltSize;
4042}
4043
4044/// getExtractVEXTRACTF128Immediate - Return the appropriate immediate
4045/// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF128
4046/// instructions.
4047unsigned X86::getExtractVEXTRACTF128Immediate(SDNode *N) {
4048  if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4049    llvm_unreachable("Illegal extract subvector for VEXTRACTF128");
4050
4051  uint64_t Index =
4052    cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4053
4054  EVT VecVT = N->getOperand(0).getValueType();
4055  EVT ElVT = VecVT.getVectorElementType();
4056
4057  unsigned NumElemsPerChunk = 128 / ElVT.getSizeInBits();
4058  return Index / NumElemsPerChunk;
4059}
4060
4061/// getInsertVINSERTF128Immediate - Return the appropriate immediate
4062/// to insert at the specified INSERT_SUBVECTOR index with VINSERTF128
4063/// instructions.
4064unsigned X86::getInsertVINSERTF128Immediate(SDNode *N) {
4065  if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4066    llvm_unreachable("Illegal insert subvector for VINSERTF128");
4067
4068  uint64_t Index =
4069    cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4070
4071  EVT VecVT = N->getValueType(0);
4072  EVT ElVT = VecVT.getVectorElementType();
4073
4074  unsigned NumElemsPerChunk = 128 / ElVT.getSizeInBits();
4075  return Index / NumElemsPerChunk;
4076}
4077
4078/// getShuffleCLImmediate - Return the appropriate immediate to shuffle
4079/// the specified VECTOR_SHUFFLE mask with VPERMQ and VPERMPD instructions.
4080/// Handles 256-bit.
4081static unsigned getShuffleCLImmediate(ShuffleVectorSDNode *N) {
4082  EVT VT = N->getValueType(0);
4083
4084  unsigned NumElts = VT.getVectorNumElements();
4085
4086  assert((VT.is256BitVector() && NumElts == 4) &&
4087         "Unsupported vector type for VPERMQ/VPERMPD");
4088
4089  unsigned Mask = 0;
4090  for (unsigned i = 0; i != NumElts; ++i) {
4091    int Elt = N->getMaskElt(i);
4092    if (Elt < 0)
4093      continue;
4094    Mask |= Elt << (i*2);
4095  }
4096
4097  return Mask;
4098}
4099/// isZeroNode - Returns true if Elt is a constant zero or a floating point
4100/// constant +0.0.
4101bool X86::isZeroNode(SDValue Elt) {
4102  return ((isa<ConstantSDNode>(Elt) &&
4103           cast<ConstantSDNode>(Elt)->isNullValue()) ||
4104          (isa<ConstantFPSDNode>(Elt) &&
4105           cast<ConstantFPSDNode>(Elt)->getValueAPF().isPosZero()));
4106}
4107
4108/// CommuteVectorShuffle - Swap vector_shuffle operands as well as values in
4109/// their permute mask.
4110static SDValue CommuteVectorShuffle(ShuffleVectorSDNode *SVOp,
4111                                    SelectionDAG &DAG) {
4112  EVT VT = SVOp->getValueType(0);
4113  unsigned NumElems = VT.getVectorNumElements();
4114  SmallVector<int, 8> MaskVec;
4115
4116  for (unsigned i = 0; i != NumElems; ++i) {
4117    int Idx = SVOp->getMaskElt(i);
4118    if (Idx >= 0) {
4119      if (Idx < (int)NumElems)
4120        Idx += NumElems;
4121      else
4122        Idx -= NumElems;
4123    }
4124    MaskVec.push_back(Idx);
4125  }
4126  return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(1),
4127                              SVOp->getOperand(0), &MaskVec[0]);
4128}
4129
4130/// ShouldXformToMOVHLPS - Return true if the node should be transformed to
4131/// match movhlps. The lower half elements should come from upper half of
4132/// V1 (and in order), and the upper half elements should come from the upper
4133/// half of V2 (and in order).
4134static bool ShouldXformToMOVHLPS(ArrayRef<int> Mask, EVT VT) {
4135  if (!VT.is128BitVector())
4136    return false;
4137  if (VT.getVectorNumElements() != 4)
4138    return false;
4139  for (unsigned i = 0, e = 2; i != e; ++i)
4140    if (!isUndefOrEqual(Mask[i], i+2))
4141      return false;
4142  for (unsigned i = 2; i != 4; ++i)
4143    if (!isUndefOrEqual(Mask[i], i+4))
4144      return false;
4145  return true;
4146}
4147
4148/// isScalarLoadToVector - Returns true if the node is a scalar load that
4149/// is promoted to a vector. It also returns the LoadSDNode by reference if
4150/// required.
4151static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = NULL) {
4152  if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
4153    return false;
4154  N = N->getOperand(0).getNode();
4155  if (!ISD::isNON_EXTLoad(N))
4156    return false;
4157  if (LD)
4158    *LD = cast<LoadSDNode>(N);
4159  return true;
4160}
4161
4162// Test whether the given value is a vector value which will be legalized
4163// into a load.
4164static bool WillBeConstantPoolLoad(SDNode *N) {
4165  if (N->getOpcode() != ISD::BUILD_VECTOR)
4166    return false;
4167
4168  // Check for any non-constant elements.
4169  for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
4170    switch (N->getOperand(i).getNode()->getOpcode()) {
4171    case ISD::UNDEF:
4172    case ISD::ConstantFP:
4173    case ISD::Constant:
4174      break;
4175    default:
4176      return false;
4177    }
4178
4179  // Vectors of all-zeros and all-ones are materialized with special
4180  // instructions rather than being loaded.
4181  return !ISD::isBuildVectorAllZeros(N) &&
4182         !ISD::isBuildVectorAllOnes(N);
4183}
4184
4185/// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
4186/// match movlp{s|d}. The lower half elements should come from lower half of
4187/// V1 (and in order), and the upper half elements should come from the upper
4188/// half of V2 (and in order). And since V1 will become the source of the
4189/// MOVLP, it must be either a vector load or a scalar load to vector.
4190static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2,
4191                               ArrayRef<int> Mask, EVT VT) {
4192  if (!VT.is128BitVector())
4193    return false;
4194
4195  if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
4196    return false;
4197  // Is V2 is a vector load, don't do this transformation. We will try to use
4198  // load folding shufps op.
4199  if (ISD::isNON_EXTLoad(V2) || WillBeConstantPoolLoad(V2))
4200    return false;
4201
4202  unsigned NumElems = VT.getVectorNumElements();
4203
4204  if (NumElems != 2 && NumElems != 4)
4205    return false;
4206  for (unsigned i = 0, e = NumElems/2; i != e; ++i)
4207    if (!isUndefOrEqual(Mask[i], i))
4208      return false;
4209  for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
4210    if (!isUndefOrEqual(Mask[i], i+NumElems))
4211      return false;
4212  return true;
4213}
4214
4215/// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
4216/// all the same.
4217static bool isSplatVector(SDNode *N) {
4218  if (N->getOpcode() != ISD::BUILD_VECTOR)
4219    return false;
4220
4221  SDValue SplatValue = N->getOperand(0);
4222  for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
4223    if (N->getOperand(i) != SplatValue)
4224      return false;
4225  return true;
4226}
4227
4228/// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
4229/// to an zero vector.
4230/// FIXME: move to dag combiner / method on ShuffleVectorSDNode
4231static bool isZeroShuffle(ShuffleVectorSDNode *N) {
4232  SDValue V1 = N->getOperand(0);
4233  SDValue V2 = N->getOperand(1);
4234  unsigned NumElems = N->getValueType(0).getVectorNumElements();
4235  for (unsigned i = 0; i != NumElems; ++i) {
4236    int Idx = N->getMaskElt(i);
4237    if (Idx >= (int)NumElems) {
4238      unsigned Opc = V2.getOpcode();
4239      if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
4240        continue;
4241      if (Opc != ISD::BUILD_VECTOR ||
4242          !X86::isZeroNode(V2.getOperand(Idx-NumElems)))
4243        return false;
4244    } else if (Idx >= 0) {
4245      unsigned Opc = V1.getOpcode();
4246      if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
4247        continue;
4248      if (Opc != ISD::BUILD_VECTOR ||
4249          !X86::isZeroNode(V1.getOperand(Idx)))
4250        return false;
4251    }
4252  }
4253  return true;
4254}
4255
4256/// getZeroVector - Returns a vector of specified type with all zero elements.
4257///
4258static SDValue getZeroVector(EVT VT, const X86Subtarget *Subtarget,
4259                             SelectionDAG &DAG, DebugLoc dl) {
4260  assert(VT.isVector() && "Expected a vector type");
4261  unsigned Size = VT.getSizeInBits();
4262
4263  // Always build SSE zero vectors as <4 x i32> bitcasted
4264  // to their dest type. This ensures they get CSE'd.
4265  SDValue Vec;
4266  if (Size == 128) {  // SSE
4267    if (Subtarget->hasSSE2()) {  // SSE2
4268      SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4269      Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4270    } else { // SSE1
4271      SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4272      Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
4273    }
4274  } else if (Size == 256) { // AVX
4275    if (Subtarget->hasAVX2()) { // AVX2
4276      SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4277      SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4278      Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops, 8);
4279    } else {
4280      // 256-bit logic and arithmetic instructions in AVX are all
4281      // floating-point, no support for integer ops. Emit fp zeroed vectors.
4282      SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4283      SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4284      Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops, 8);
4285    }
4286  } else
4287    llvm_unreachable("Unexpected vector type");
4288
4289  return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4290}
4291
4292/// getOnesVector - Returns a vector of specified type with all bits set.
4293/// Always build ones vectors as <4 x i32> or <8 x i32>. For 256-bit types with
4294/// no AVX2 supprt, use two <4 x i32> inserted in a <8 x i32> appropriately.
4295/// Then bitcast to their original type, ensuring they get CSE'd.
4296static SDValue getOnesVector(EVT VT, bool HasAVX2, SelectionDAG &DAG,
4297                             DebugLoc dl) {
4298  assert(VT.isVector() && "Expected a vector type");
4299  unsigned Size = VT.getSizeInBits();
4300
4301  SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
4302  SDValue Vec;
4303  if (Size == 256) {
4304    if (HasAVX2) { // AVX2
4305      SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4306      Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops, 8);
4307    } else { // AVX
4308      Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4309      Vec = Concat128BitVectors(Vec, Vec, MVT::v8i32, 8, DAG, dl);
4310    }
4311  } else if (Size == 128) {
4312    Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4313  } else
4314    llvm_unreachable("Unexpected vector type");
4315
4316  return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4317}
4318
4319/// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
4320/// that point to V2 points to its first element.
4321static void NormalizeMask(SmallVectorImpl<int> &Mask, unsigned NumElems) {
4322  for (unsigned i = 0; i != NumElems; ++i) {
4323    if (Mask[i] > (int)NumElems) {
4324      Mask[i] = NumElems;
4325    }
4326  }
4327}
4328
4329/// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
4330/// operation of specified width.
4331static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
4332                       SDValue V2) {
4333  unsigned NumElems = VT.getVectorNumElements();
4334  SmallVector<int, 8> Mask;
4335  Mask.push_back(NumElems);
4336  for (unsigned i = 1; i != NumElems; ++i)
4337    Mask.push_back(i);
4338  return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4339}
4340
4341/// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
4342static SDValue getUnpackl(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
4343                          SDValue V2) {
4344  unsigned NumElems = VT.getVectorNumElements();
4345  SmallVector<int, 8> Mask;
4346  for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
4347    Mask.push_back(i);
4348    Mask.push_back(i + NumElems);
4349  }
4350  return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4351}
4352
4353/// getUnpackh - Returns a vector_shuffle node for an unpackh operation.
4354static SDValue getUnpackh(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
4355                          SDValue V2) {
4356  unsigned NumElems = VT.getVectorNumElements();
4357  SmallVector<int, 8> Mask;
4358  for (unsigned i = 0, Half = NumElems/2; i != Half; ++i) {
4359    Mask.push_back(i + Half);
4360    Mask.push_back(i + NumElems + Half);
4361  }
4362  return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4363}
4364
4365// PromoteSplati8i16 - All i16 and i8 vector types can't be used directly by
4366// a generic shuffle instruction because the target has no such instructions.
4367// Generate shuffles which repeat i16 and i8 several times until they can be
4368// represented by v4f32 and then be manipulated by target suported shuffles.
4369static SDValue PromoteSplati8i16(SDValue V, SelectionDAG &DAG, int &EltNo) {
4370  EVT VT = V.getValueType();
4371  int NumElems = VT.getVectorNumElements();
4372  DebugLoc dl = V.getDebugLoc();
4373
4374  while (NumElems > 4) {
4375    if (EltNo < NumElems/2) {
4376      V = getUnpackl(DAG, dl, VT, V, V);
4377    } else {
4378      V = getUnpackh(DAG, dl, VT, V, V);
4379      EltNo -= NumElems/2;
4380    }
4381    NumElems >>= 1;
4382  }
4383  return V;
4384}
4385
4386/// getLegalSplat - Generate a legal splat with supported x86 shuffles
4387static SDValue getLegalSplat(SelectionDAG &DAG, SDValue V, int EltNo) {
4388  EVT VT = V.getValueType();
4389  DebugLoc dl = V.getDebugLoc();
4390  unsigned Size = VT.getSizeInBits();
4391
4392  if (Size == 128) {
4393    V = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V);
4394    int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo };
4395    V = DAG.getVectorShuffle(MVT::v4f32, dl, V, DAG.getUNDEF(MVT::v4f32),
4396                             &SplatMask[0]);
4397  } else if (Size == 256) {
4398    // To use VPERMILPS to splat scalars, the second half of indicies must
4399    // refer to the higher part, which is a duplication of the lower one,
4400    // because VPERMILPS can only handle in-lane permutations.
4401    int SplatMask[8] = { EltNo, EltNo, EltNo, EltNo,
4402                         EltNo+4, EltNo+4, EltNo+4, EltNo+4 };
4403
4404    V = DAG.getNode(ISD::BITCAST, dl, MVT::v8f32, V);
4405    V = DAG.getVectorShuffle(MVT::v8f32, dl, V, DAG.getUNDEF(MVT::v8f32),
4406                             &SplatMask[0]);
4407  } else
4408    llvm_unreachable("Vector size not supported");
4409
4410  return DAG.getNode(ISD::BITCAST, dl, VT, V);
4411}
4412
4413/// PromoteSplat - Splat is promoted to target supported vector shuffles.
4414static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG) {
4415  EVT SrcVT = SV->getValueType(0);
4416  SDValue V1 = SV->getOperand(0);
4417  DebugLoc dl = SV->getDebugLoc();
4418
4419  int EltNo = SV->getSplatIndex();
4420  int NumElems = SrcVT.getVectorNumElements();
4421  unsigned Size = SrcVT.getSizeInBits();
4422
4423  assert(((Size == 128 && NumElems > 4) || Size == 256) &&
4424          "Unknown how to promote splat for type");
4425
4426  // Extract the 128-bit part containing the splat element and update
4427  // the splat element index when it refers to the higher register.
4428  if (Size == 256) {
4429    V1 = Extract128BitVector(V1, EltNo, DAG, dl);
4430    if (EltNo >= NumElems/2)
4431      EltNo -= NumElems/2;
4432  }
4433
4434  // All i16 and i8 vector types can't be used directly by a generic shuffle
4435  // instruction because the target has no such instruction. Generate shuffles
4436  // which repeat i16 and i8 several times until they fit in i32, and then can
4437  // be manipulated by target suported shuffles.
4438  EVT EltVT = SrcVT.getVectorElementType();
4439  if (EltVT == MVT::i8 || EltVT == MVT::i16)
4440    V1 = PromoteSplati8i16(V1, DAG, EltNo);
4441
4442  // Recreate the 256-bit vector and place the same 128-bit vector
4443  // into the low and high part. This is necessary because we want
4444  // to use VPERM* to shuffle the vectors
4445  if (Size == 256) {
4446    V1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, SrcVT, V1, V1);
4447  }
4448
4449  return getLegalSplat(DAG, V1, EltNo);
4450}
4451
4452/// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
4453/// vector of zero or undef vector.  This produces a shuffle where the low
4454/// element of V2 is swizzled into the zero/undef vector, landing at element
4455/// Idx.  This produces a shuffle mask like 4,1,2,3 (idx=0) or  0,1,2,4 (idx=3).
4456static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
4457                                           bool IsZero,
4458                                           const X86Subtarget *Subtarget,
4459                                           SelectionDAG &DAG) {
4460  EVT VT = V2.getValueType();
4461  SDValue V1 = IsZero
4462    ? getZeroVector(VT, Subtarget, DAG, V2.getDebugLoc()) : DAG.getUNDEF(VT);
4463  unsigned NumElems = VT.getVectorNumElements();
4464  SmallVector<int, 16> MaskVec;
4465  for (unsigned i = 0; i != NumElems; ++i)
4466    // If this is the insertion idx, put the low elt of V2 here.
4467    MaskVec.push_back(i == Idx ? NumElems : i);
4468  return DAG.getVectorShuffle(VT, V2.getDebugLoc(), V1, V2, &MaskVec[0]);
4469}
4470
4471/// getTargetShuffleMask - Calculates the shuffle mask corresponding to the
4472/// target specific opcode. Returns true if the Mask could be calculated.
4473/// Sets IsUnary to true if only uses one source.
4474static bool getTargetShuffleMask(SDNode *N, MVT VT,
4475                                 SmallVectorImpl<int> &Mask, bool &IsUnary) {
4476  unsigned NumElems = VT.getVectorNumElements();
4477  SDValue ImmN;
4478
4479  IsUnary = false;
4480  switch(N->getOpcode()) {
4481  case X86ISD::SHUFP:
4482    ImmN = N->getOperand(N->getNumOperands()-1);
4483    DecodeSHUFPMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4484    break;
4485  case X86ISD::UNPCKH:
4486    DecodeUNPCKHMask(VT, Mask);
4487    break;
4488  case X86ISD::UNPCKL:
4489    DecodeUNPCKLMask(VT, Mask);
4490    break;
4491  case X86ISD::MOVHLPS:
4492    DecodeMOVHLPSMask(NumElems, Mask);
4493    break;
4494  case X86ISD::MOVLHPS:
4495    DecodeMOVLHPSMask(NumElems, Mask);
4496    break;
4497  case X86ISD::PSHUFD:
4498  case X86ISD::VPERMILP:
4499    ImmN = N->getOperand(N->getNumOperands()-1);
4500    DecodePSHUFMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4501    IsUnary = true;
4502    break;
4503  case X86ISD::PSHUFHW:
4504    ImmN = N->getOperand(N->getNumOperands()-1);
4505    DecodePSHUFHWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4506    IsUnary = true;
4507    break;
4508  case X86ISD::PSHUFLW:
4509    ImmN = N->getOperand(N->getNumOperands()-1);
4510    DecodePSHUFLWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4511    IsUnary = true;
4512    break;
4513  case X86ISD::VPERMI:
4514    ImmN = N->getOperand(N->getNumOperands()-1);
4515    DecodeVPERMMask(cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4516    IsUnary = true;
4517    break;
4518  case X86ISD::MOVSS:
4519  case X86ISD::MOVSD: {
4520    // The index 0 always comes from the first element of the second source,
4521    // this is why MOVSS and MOVSD are used in the first place. The other
4522    // elements come from the other positions of the first source vector
4523    Mask.push_back(NumElems);
4524    for (unsigned i = 1; i != NumElems; ++i) {
4525      Mask.push_back(i);
4526    }
4527    break;
4528  }
4529  case X86ISD::VPERM2X128:
4530    ImmN = N->getOperand(N->getNumOperands()-1);
4531    DecodeVPERM2X128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4532    if (Mask.empty()) return false;
4533    break;
4534  case X86ISD::MOVDDUP:
4535  case X86ISD::MOVLHPD:
4536  case X86ISD::MOVLPD:
4537  case X86ISD::MOVLPS:
4538  case X86ISD::MOVSHDUP:
4539  case X86ISD::MOVSLDUP:
4540  case X86ISD::PALIGN:
4541    // Not yet implemented
4542    return false;
4543  default: llvm_unreachable("unknown target shuffle node");
4544  }
4545
4546  return true;
4547}
4548
4549/// getShuffleScalarElt - Returns the scalar element that will make up the ith
4550/// element of the result of the vector shuffle.
4551static SDValue getShuffleScalarElt(SDNode *N, unsigned Index, SelectionDAG &DAG,
4552                                   unsigned Depth) {
4553  if (Depth == 6)
4554    return SDValue();  // Limit search depth.
4555
4556  SDValue V = SDValue(N, 0);
4557  EVT VT = V.getValueType();
4558  unsigned Opcode = V.getOpcode();
4559
4560  // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
4561  if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
4562    int Elt = SV->getMaskElt(Index);
4563
4564    if (Elt < 0)
4565      return DAG.getUNDEF(VT.getVectorElementType());
4566
4567    unsigned NumElems = VT.getVectorNumElements();
4568    SDValue NewV = (Elt < (int)NumElems) ? SV->getOperand(0)
4569                                         : SV->getOperand(1);
4570    return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG, Depth+1);
4571  }
4572
4573  // Recurse into target specific vector shuffles to find scalars.
4574  if (isTargetShuffle(Opcode)) {
4575    MVT ShufVT = V.getValueType().getSimpleVT();
4576    unsigned NumElems = ShufVT.getVectorNumElements();
4577    SmallVector<int, 16> ShuffleMask;
4578    SDValue ImmN;
4579    bool IsUnary;
4580
4581    if (!getTargetShuffleMask(N, ShufVT, ShuffleMask, IsUnary))
4582      return SDValue();
4583
4584    int Elt = ShuffleMask[Index];
4585    if (Elt < 0)
4586      return DAG.getUNDEF(ShufVT.getVectorElementType());
4587
4588    SDValue NewV = (Elt < (int)NumElems) ? N->getOperand(0)
4589                                         : N->getOperand(1);
4590    return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG,
4591                               Depth+1);
4592  }
4593
4594  // Actual nodes that may contain scalar elements
4595  if (Opcode == ISD::BITCAST) {
4596    V = V.getOperand(0);
4597    EVT SrcVT = V.getValueType();
4598    unsigned NumElems = VT.getVectorNumElements();
4599
4600    if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
4601      return SDValue();
4602  }
4603
4604  if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
4605    return (Index == 0) ? V.getOperand(0)
4606                        : DAG.getUNDEF(VT.getVectorElementType());
4607
4608  if (V.getOpcode() == ISD::BUILD_VECTOR)
4609    return V.getOperand(Index);
4610
4611  return SDValue();
4612}
4613
4614/// getNumOfConsecutiveZeros - Return the number of elements of a vector
4615/// shuffle operation which come from a consecutively from a zero. The
4616/// search can start in two different directions, from left or right.
4617static
4618unsigned getNumOfConsecutiveZeros(ShuffleVectorSDNode *SVOp, unsigned NumElems,
4619                                  bool ZerosFromLeft, SelectionDAG &DAG) {
4620  unsigned i;
4621  for (i = 0; i != NumElems; ++i) {
4622    unsigned Index = ZerosFromLeft ? i : NumElems-i-1;
4623    SDValue Elt = getShuffleScalarElt(SVOp, Index, DAG, 0);
4624    if (!(Elt.getNode() &&
4625         (Elt.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elt))))
4626      break;
4627  }
4628
4629  return i;
4630}
4631
4632/// isShuffleMaskConsecutive - Check if the shuffle mask indicies [MaskI, MaskE)
4633/// correspond consecutively to elements from one of the vector operands,
4634/// starting from its index OpIdx. Also tell OpNum which source vector operand.
4635static
4636bool isShuffleMaskConsecutive(ShuffleVectorSDNode *SVOp,
4637                              unsigned MaskI, unsigned MaskE, unsigned OpIdx,
4638                              unsigned NumElems, unsigned &OpNum) {
4639  bool SeenV1 = false;
4640  bool SeenV2 = false;
4641
4642  for (unsigned i = MaskI; i != MaskE; ++i, ++OpIdx) {
4643    int Idx = SVOp->getMaskElt(i);
4644    // Ignore undef indicies
4645    if (Idx < 0)
4646      continue;
4647
4648    if (Idx < (int)NumElems)
4649      SeenV1 = true;
4650    else
4651      SeenV2 = true;
4652
4653    // Only accept consecutive elements from the same vector
4654    if ((Idx % NumElems != OpIdx) || (SeenV1 && SeenV2))
4655      return false;
4656  }
4657
4658  OpNum = SeenV1 ? 0 : 1;
4659  return true;
4660}
4661
4662/// isVectorShiftRight - Returns true if the shuffle can be implemented as a
4663/// logical left shift of a vector.
4664static bool isVectorShiftRight(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4665                               bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4666  unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
4667  unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems,
4668              false /* check zeros from right */, DAG);
4669  unsigned OpSrc;
4670
4671  if (!NumZeros)
4672    return false;
4673
4674  // Considering the elements in the mask that are not consecutive zeros,
4675  // check if they consecutively come from only one of the source vectors.
4676  //
4677  //               V1 = {X, A, B, C}     0
4678  //                         \  \  \    /
4679  //   vector_shuffle V1, V2 <1, 2, 3, X>
4680  //
4681  if (!isShuffleMaskConsecutive(SVOp,
4682            0,                   // Mask Start Index
4683            NumElems-NumZeros,   // Mask End Index(exclusive)
4684            NumZeros,            // Where to start looking in the src vector
4685            NumElems,            // Number of elements in vector
4686            OpSrc))              // Which source operand ?
4687    return false;
4688
4689  isLeft = false;
4690  ShAmt = NumZeros;
4691  ShVal = SVOp->getOperand(OpSrc);
4692  return true;
4693}
4694
4695/// isVectorShiftLeft - Returns true if the shuffle can be implemented as a
4696/// logical left shift of a vector.
4697static bool isVectorShiftLeft(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4698                              bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4699  unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
4700  unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems,
4701              true /* check zeros from left */, DAG);
4702  unsigned OpSrc;
4703
4704  if (!NumZeros)
4705    return false;
4706
4707  // Considering the elements in the mask that are not consecutive zeros,
4708  // check if they consecutively come from only one of the source vectors.
4709  //
4710  //                           0    { A, B, X, X } = V2
4711  //                          / \    /  /
4712  //   vector_shuffle V1, V2 <X, X, 4, 5>
4713  //
4714  if (!isShuffleMaskConsecutive(SVOp,
4715            NumZeros,     // Mask Start Index
4716            NumElems,     // Mask End Index(exclusive)
4717            0,            // Where to start looking in the src vector
4718            NumElems,     // Number of elements in vector
4719            OpSrc))       // Which source operand ?
4720    return false;
4721
4722  isLeft = true;
4723  ShAmt = NumZeros;
4724  ShVal = SVOp->getOperand(OpSrc);
4725  return true;
4726}
4727
4728/// isVectorShift - Returns true if the shuffle can be implemented as a
4729/// logical left or right shift of a vector.
4730static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4731                          bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4732  // Although the logic below support any bitwidth size, there are no
4733  // shift instructions which handle more than 128-bit vectors.
4734  if (!SVOp->getValueType(0).is128BitVector())
4735    return false;
4736
4737  if (isVectorShiftLeft(SVOp, DAG, isLeft, ShVal, ShAmt) ||
4738      isVectorShiftRight(SVOp, DAG, isLeft, ShVal, ShAmt))
4739    return true;
4740
4741  return false;
4742}
4743
4744/// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
4745///
4746static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
4747                                       unsigned NumNonZero, unsigned NumZero,
4748                                       SelectionDAG &DAG,
4749                                       const X86Subtarget* Subtarget,
4750                                       const TargetLowering &TLI) {
4751  if (NumNonZero > 8)
4752    return SDValue();
4753
4754  DebugLoc dl = Op.getDebugLoc();
4755  SDValue V(0, 0);
4756  bool First = true;
4757  for (unsigned i = 0; i < 16; ++i) {
4758    bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
4759    if (ThisIsNonZero && First) {
4760      if (NumZero)
4761        V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
4762      else
4763        V = DAG.getUNDEF(MVT::v8i16);
4764      First = false;
4765    }
4766
4767    if ((i & 1) != 0) {
4768      SDValue ThisElt(0, 0), LastElt(0, 0);
4769      bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
4770      if (LastIsNonZero) {
4771        LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
4772                              MVT::i16, Op.getOperand(i-1));
4773      }
4774      if (ThisIsNonZero) {
4775        ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
4776        ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
4777                              ThisElt, DAG.getConstant(8, MVT::i8));
4778        if (LastIsNonZero)
4779          ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
4780      } else
4781        ThisElt = LastElt;
4782
4783      if (ThisElt.getNode())
4784        V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
4785                        DAG.getIntPtrConstant(i/2));
4786    }
4787  }
4788
4789  return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V);
4790}
4791
4792/// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
4793///
4794static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
4795                                     unsigned NumNonZero, unsigned NumZero,
4796                                     SelectionDAG &DAG,
4797                                     const X86Subtarget* Subtarget,
4798                                     const TargetLowering &TLI) {
4799  if (NumNonZero > 4)
4800    return SDValue();
4801
4802  DebugLoc dl = Op.getDebugLoc();
4803  SDValue V(0, 0);
4804  bool First = true;
4805  for (unsigned i = 0; i < 8; ++i) {
4806    bool isNonZero = (NonZeros & (1 << i)) != 0;
4807    if (isNonZero) {
4808      if (First) {
4809        if (NumZero)
4810          V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
4811        else
4812          V = DAG.getUNDEF(MVT::v8i16);
4813        First = false;
4814      }
4815      V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
4816                      MVT::v8i16, V, Op.getOperand(i),
4817                      DAG.getIntPtrConstant(i));
4818    }
4819  }
4820
4821  return V;
4822}
4823
4824/// getVShift - Return a vector logical shift node.
4825///
4826static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
4827                         unsigned NumBits, SelectionDAG &DAG,
4828                         const TargetLowering &TLI, DebugLoc dl) {
4829  assert(VT.is128BitVector() && "Unknown type for VShift");
4830  EVT ShVT = MVT::v2i64;
4831  unsigned Opc = isLeft ? X86ISD::VSHLDQ : X86ISD::VSRLDQ;
4832  SrcOp = DAG.getNode(ISD::BITCAST, dl, ShVT, SrcOp);
4833  return DAG.getNode(ISD::BITCAST, dl, VT,
4834                     DAG.getNode(Opc, dl, ShVT, SrcOp,
4835                             DAG.getConstant(NumBits,
4836                                  TLI.getShiftAmountTy(SrcOp.getValueType()))));
4837}
4838
4839SDValue
4840X86TargetLowering::LowerAsSplatVectorLoad(SDValue SrcOp, EVT VT, DebugLoc dl,
4841                                          SelectionDAG &DAG) const {
4842
4843  // Check if the scalar load can be widened into a vector load. And if
4844  // the address is "base + cst" see if the cst can be "absorbed" into
4845  // the shuffle mask.
4846  if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
4847    SDValue Ptr = LD->getBasePtr();
4848    if (!ISD::isNormalLoad(LD) || LD->isVolatile())
4849      return SDValue();
4850    EVT PVT = LD->getValueType(0);
4851    if (PVT != MVT::i32 && PVT != MVT::f32)
4852      return SDValue();
4853
4854    int FI = -1;
4855    int64_t Offset = 0;
4856    if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
4857      FI = FINode->getIndex();
4858      Offset = 0;
4859    } else if (DAG.isBaseWithConstantOffset(Ptr) &&
4860               isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
4861      FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
4862      Offset = Ptr.getConstantOperandVal(1);
4863      Ptr = Ptr.getOperand(0);
4864    } else {
4865      return SDValue();
4866    }
4867
4868    // FIXME: 256-bit vector instructions don't require a strict alignment,
4869    // improve this code to support it better.
4870    unsigned RequiredAlign = VT.getSizeInBits()/8;
4871    SDValue Chain = LD->getChain();
4872    // Make sure the stack object alignment is at least 16 or 32.
4873    MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
4874    if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
4875      if (MFI->isFixedObjectIndex(FI)) {
4876        // Can't change the alignment. FIXME: It's possible to compute
4877        // the exact stack offset and reference FI + adjust offset instead.
4878        // If someone *really* cares about this. That's the way to implement it.
4879        return SDValue();
4880      } else {
4881        MFI->setObjectAlignment(FI, RequiredAlign);
4882      }
4883    }
4884
4885    // (Offset % 16 or 32) must be multiple of 4. Then address is then
4886    // Ptr + (Offset & ~15).
4887    if (Offset < 0)
4888      return SDValue();
4889    if ((Offset % RequiredAlign) & 3)
4890      return SDValue();
4891    int64_t StartOffset = Offset & ~(RequiredAlign-1);
4892    if (StartOffset)
4893      Ptr = DAG.getNode(ISD::ADD, Ptr.getDebugLoc(), Ptr.getValueType(),
4894                        Ptr,DAG.getConstant(StartOffset, Ptr.getValueType()));
4895
4896    int EltNo = (Offset - StartOffset) >> 2;
4897    unsigned NumElems = VT.getVectorNumElements();
4898
4899    EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
4900    SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
4901                             LD->getPointerInfo().getWithOffset(StartOffset),
4902                             false, false, false, 0);
4903
4904    SmallVector<int, 8> Mask;
4905    for (unsigned i = 0; i != NumElems; ++i)
4906      Mask.push_back(EltNo);
4907
4908    return DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &Mask[0]);
4909  }
4910
4911  return SDValue();
4912}
4913
4914/// EltsFromConsecutiveLoads - Given the initializing elements 'Elts' of a
4915/// vector of type 'VT', see if the elements can be replaced by a single large
4916/// load which has the same value as a build_vector whose operands are 'elts'.
4917///
4918/// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
4919///
4920/// FIXME: we'd also like to handle the case where the last elements are zero
4921/// rather than undef via VZEXT_LOAD, but we do not detect that case today.
4922/// There's even a handy isZeroNode for that purpose.
4923static SDValue EltsFromConsecutiveLoads(EVT VT, SmallVectorImpl<SDValue> &Elts,
4924                                        DebugLoc &DL, SelectionDAG &DAG) {
4925  EVT EltVT = VT.getVectorElementType();
4926  unsigned NumElems = Elts.size();
4927
4928  LoadSDNode *LDBase = NULL;
4929  unsigned LastLoadedElt = -1U;
4930
4931  // For each element in the initializer, see if we've found a load or an undef.
4932  // If we don't find an initial load element, or later load elements are
4933  // non-consecutive, bail out.
4934  for (unsigned i = 0; i < NumElems; ++i) {
4935    SDValue Elt = Elts[i];
4936
4937    if (!Elt.getNode() ||
4938        (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
4939      return SDValue();
4940    if (!LDBase) {
4941      if (Elt.getNode()->getOpcode() == ISD::UNDEF)
4942        return SDValue();
4943      LDBase = cast<LoadSDNode>(Elt.getNode());
4944      LastLoadedElt = i;
4945      continue;
4946    }
4947    if (Elt.getOpcode() == ISD::UNDEF)
4948      continue;
4949
4950    LoadSDNode *LD = cast<LoadSDNode>(Elt);
4951    if (!DAG.isConsecutiveLoad(LD, LDBase, EltVT.getSizeInBits()/8, i))
4952      return SDValue();
4953    LastLoadedElt = i;
4954  }
4955
4956  // If we have found an entire vector of loads and undefs, then return a large
4957  // load of the entire vector width starting at the base pointer.  If we found
4958  // consecutive loads for the low half, generate a vzext_load node.
4959  if (LastLoadedElt == NumElems - 1) {
4960    if (DAG.InferPtrAlignment(LDBase->getBasePtr()) >= 16)
4961      return DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
4962                         LDBase->getPointerInfo(),
4963                         LDBase->isVolatile(), LDBase->isNonTemporal(),
4964                         LDBase->isInvariant(), 0);
4965    return DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
4966                       LDBase->getPointerInfo(),
4967                       LDBase->isVolatile(), LDBase->isNonTemporal(),
4968                       LDBase->isInvariant(), LDBase->getAlignment());
4969  }
4970  if (NumElems == 4 && LastLoadedElt == 1 &&
4971      DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) {
4972    SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
4973    SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
4974    SDValue ResNode =
4975        DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops, 2, MVT::i64,
4976                                LDBase->getPointerInfo(),
4977                                LDBase->getAlignment(),
4978                                false/*isVolatile*/, true/*ReadMem*/,
4979                                false/*WriteMem*/);
4980
4981    // Make sure the newly-created LOAD is in the same position as LDBase in
4982    // terms of dependency. We create a TokenFactor for LDBase and ResNode, and
4983    // update uses of LDBase's output chain to use the TokenFactor.
4984    if (LDBase->hasAnyUseOfValue(1)) {
4985      SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
4986                             SDValue(LDBase, 1), SDValue(ResNode.getNode(), 1));
4987      DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
4988      DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
4989                             SDValue(ResNode.getNode(), 1));
4990    }
4991
4992    return DAG.getNode(ISD::BITCAST, DL, VT, ResNode);
4993  }
4994  return SDValue();
4995}
4996
4997/// LowerVectorBroadcast - Attempt to use the vbroadcast instruction
4998/// to generate a splat value for the following cases:
4999/// 1. A splat BUILD_VECTOR which uses a single scalar load, or a constant.
5000/// 2. A splat shuffle which uses a scalar_to_vector node which comes from
5001/// a scalar load, or a constant.
5002/// The VBROADCAST node is returned when a pattern is found,
5003/// or SDValue() otherwise.
5004SDValue
5005X86TargetLowering::LowerVectorBroadcast(SDValue &Op, SelectionDAG &DAG) const {
5006  if (!Subtarget->hasAVX())
5007    return SDValue();
5008
5009  EVT VT = Op.getValueType();
5010  DebugLoc dl = Op.getDebugLoc();
5011
5012  assert((VT.is128BitVector() || VT.is256BitVector()) &&
5013         "Unsupported vector type for broadcast.");
5014
5015  SDValue Ld;
5016  bool ConstSplatVal;
5017
5018  switch (Op.getOpcode()) {
5019    default:
5020      // Unknown pattern found.
5021      return SDValue();
5022
5023    case ISD::BUILD_VECTOR: {
5024      // The BUILD_VECTOR node must be a splat.
5025      if (!isSplatVector(Op.getNode()))
5026        return SDValue();
5027
5028      Ld = Op.getOperand(0);
5029      ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5030                     Ld.getOpcode() == ISD::ConstantFP);
5031
5032      // The suspected load node has several users. Make sure that all
5033      // of its users are from the BUILD_VECTOR node.
5034      // Constants may have multiple users.
5035      if (!ConstSplatVal && !Ld->hasNUsesOfValue(VT.getVectorNumElements(), 0))
5036        return SDValue();
5037      break;
5038    }
5039
5040    case ISD::VECTOR_SHUFFLE: {
5041      ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5042
5043      // Shuffles must have a splat mask where the first element is
5044      // broadcasted.
5045      if ((!SVOp->isSplat()) || SVOp->getMaskElt(0) != 0)
5046        return SDValue();
5047
5048      SDValue Sc = Op.getOperand(0);
5049      if (Sc.getOpcode() != ISD::SCALAR_TO_VECTOR &&
5050          Sc.getOpcode() != ISD::BUILD_VECTOR) {
5051
5052        if (!Subtarget->hasAVX2())
5053          return SDValue();
5054
5055        // Use the register form of the broadcast instruction available on AVX2.
5056        if (VT.is256BitVector())
5057          Sc = Extract128BitVector(Sc, 0, DAG, dl);
5058        return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Sc);
5059      }
5060
5061      Ld = Sc.getOperand(0);
5062      ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5063                       Ld.getOpcode() == ISD::ConstantFP);
5064
5065      // The scalar_to_vector node and the suspected
5066      // load node must have exactly one user.
5067      // Constants may have multiple users.
5068      if (!ConstSplatVal && (!Sc.hasOneUse() || !Ld.hasOneUse()))
5069        return SDValue();
5070      break;
5071    }
5072  }
5073
5074  bool Is256 = VT.is256BitVector();
5075
5076  // Handle the broadcasting a single constant scalar from the constant pool
5077  // into a vector. On Sandybridge it is still better to load a constant vector
5078  // from the constant pool and not to broadcast it from a scalar.
5079  if (ConstSplatVal && Subtarget->hasAVX2()) {
5080    EVT CVT = Ld.getValueType();
5081    assert(!CVT.isVector() && "Must not broadcast a vector type");
5082    unsigned ScalarSize = CVT.getSizeInBits();
5083
5084    if (ScalarSize == 32 || (Is256 && ScalarSize == 64)) {
5085      const Constant *C = 0;
5086      if (ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Ld))
5087        C = CI->getConstantIntValue();
5088      else if (ConstantFPSDNode *CF = dyn_cast<ConstantFPSDNode>(Ld))
5089        C = CF->getConstantFPValue();
5090
5091      assert(C && "Invalid constant type");
5092
5093      SDValue CP = DAG.getConstantPool(C, getPointerTy());
5094      unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
5095      Ld = DAG.getLoad(CVT, dl, DAG.getEntryNode(), CP,
5096                       MachinePointerInfo::getConstantPool(),
5097                       false, false, false, Alignment);
5098
5099      return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5100    }
5101  }
5102
5103  bool IsLoad = ISD::isNormalLoad(Ld.getNode());
5104  unsigned ScalarSize = Ld.getValueType().getSizeInBits();
5105
5106  // Handle AVX2 in-register broadcasts.
5107  if (!IsLoad && Subtarget->hasAVX2() &&
5108      (ScalarSize == 32 || (Is256 && ScalarSize == 64)))
5109    return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5110
5111  // The scalar source must be a normal load.
5112  if (!IsLoad)
5113    return SDValue();
5114
5115  if (ScalarSize == 32 || (Is256 && ScalarSize == 64))
5116    return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5117
5118  // The integer check is needed for the 64-bit into 128-bit so it doesn't match
5119  // double since there is no vbroadcastsd xmm
5120  if (Subtarget->hasAVX2() && Ld.getValueType().isInteger()) {
5121    if (ScalarSize == 8 || ScalarSize == 16 || ScalarSize == 64)
5122      return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5123  }
5124
5125  // Unsupported broadcast.
5126  return SDValue();
5127}
5128
5129// LowerVectorFpExtend - Recognize the scalarized FP_EXTEND from v2f32 to v2f64
5130// and convert it into X86ISD::VFPEXT due to the current ISD::FP_EXTEND has the
5131// constraint of matching input/output vector elements.
5132SDValue
5133X86TargetLowering::LowerVectorFpExtend(SDValue &Op, SelectionDAG &DAG) const {
5134  DebugLoc DL = Op.getDebugLoc();
5135  SDNode *N = Op.getNode();
5136  EVT VT = Op.getValueType();
5137  unsigned NumElts = Op.getNumOperands();
5138
5139  // Check supported types and sub-targets.
5140  //
5141  // Only v2f32 -> v2f64 needs special handling.
5142  if (VT != MVT::v2f64 || !Subtarget->hasSSE2())
5143    return SDValue();
5144
5145  SDValue VecIn;
5146  EVT VecInVT;
5147  SmallVector<int, 8> Mask;
5148  EVT SrcVT = MVT::Other;
5149
5150  // Check the patterns could be translated into X86vfpext.
5151  for (unsigned i = 0; i < NumElts; ++i) {
5152    SDValue In = N->getOperand(i);
5153    unsigned Opcode = In.getOpcode();
5154
5155    // Skip if the element is undefined.
5156    if (Opcode == ISD::UNDEF) {
5157      Mask.push_back(-1);
5158      continue;
5159    }
5160
5161    // Quit if one of the elements is not defined from 'fpext'.
5162    if (Opcode != ISD::FP_EXTEND)
5163      return SDValue();
5164
5165    // Check how the source of 'fpext' is defined.
5166    SDValue L2In = In.getOperand(0);
5167    EVT L2InVT = L2In.getValueType();
5168
5169    // Check the original type
5170    if (SrcVT == MVT::Other)
5171      SrcVT = L2InVT;
5172    else if (SrcVT != L2InVT) // Quit if non-homogenous typed.
5173      return SDValue();
5174
5175    // Check whether the value being 'fpext'ed is extracted from the same
5176    // source.
5177    Opcode = L2In.getOpcode();
5178
5179    // Quit if it's not extracted with a constant index.
5180    if (Opcode != ISD::EXTRACT_VECTOR_ELT ||
5181        !isa<ConstantSDNode>(L2In.getOperand(1)))
5182      return SDValue();
5183
5184    SDValue ExtractedFromVec = L2In.getOperand(0);
5185
5186    if (VecIn.getNode() == 0) {
5187      VecIn = ExtractedFromVec;
5188      VecInVT = ExtractedFromVec.getValueType();
5189    } else if (VecIn != ExtractedFromVec) // Quit if built from more than 1 vec.
5190      return SDValue();
5191
5192    Mask.push_back(cast<ConstantSDNode>(L2In.getOperand(1))->getZExtValue());
5193  }
5194
5195  // Quit if all operands of BUILD_VECTOR are undefined.
5196  if (!VecIn.getNode())
5197    return SDValue();
5198
5199  // Fill the remaining mask as undef.
5200  for (unsigned i = NumElts; i < VecInVT.getVectorNumElements(); ++i)
5201    Mask.push_back(-1);
5202
5203  return DAG.getNode(X86ISD::VFPEXT, DL, VT,
5204                     DAG.getVectorShuffle(VecInVT, DL,
5205                                          VecIn, DAG.getUNDEF(VecInVT),
5206                                          &Mask[0]));
5207}
5208
5209SDValue
5210X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
5211  DebugLoc dl = Op.getDebugLoc();
5212
5213  EVT VT = Op.getValueType();
5214  EVT ExtVT = VT.getVectorElementType();
5215  unsigned NumElems = Op.getNumOperands();
5216
5217  // Vectors containing all zeros can be matched by pxor and xorps later
5218  if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5219    // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
5220    // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
5221    if (VT == MVT::v4i32 || VT == MVT::v8i32)
5222      return Op;
5223
5224    return getZeroVector(VT, Subtarget, DAG, dl);
5225  }
5226
5227  // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
5228  // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use
5229  // vpcmpeqd on 256-bit vectors.
5230  if (ISD::isBuildVectorAllOnes(Op.getNode())) {
5231    if (VT == MVT::v4i32 || (VT == MVT::v8i32 && Subtarget->hasAVX2()))
5232      return Op;
5233
5234    return getOnesVector(VT, Subtarget->hasAVX2(), DAG, dl);
5235  }
5236
5237  SDValue Broadcast = LowerVectorBroadcast(Op, DAG);
5238  if (Broadcast.getNode())
5239    return Broadcast;
5240
5241  SDValue FpExt = LowerVectorFpExtend(Op, DAG);
5242  if (FpExt.getNode())
5243    return FpExt;
5244
5245  unsigned EVTBits = ExtVT.getSizeInBits();
5246
5247  unsigned NumZero  = 0;
5248  unsigned NumNonZero = 0;
5249  unsigned NonZeros = 0;
5250  bool IsAllConstants = true;
5251  SmallSet<SDValue, 8> Values;
5252  for (unsigned i = 0; i < NumElems; ++i) {
5253    SDValue Elt = Op.getOperand(i);
5254    if (Elt.getOpcode() == ISD::UNDEF)
5255      continue;
5256    Values.insert(Elt);
5257    if (Elt.getOpcode() != ISD::Constant &&
5258        Elt.getOpcode() != ISD::ConstantFP)
5259      IsAllConstants = false;
5260    if (X86::isZeroNode(Elt))
5261      NumZero++;
5262    else {
5263      NonZeros |= (1 << i);
5264      NumNonZero++;
5265    }
5266  }
5267
5268  // All undef vector. Return an UNDEF.  All zero vectors were handled above.
5269  if (NumNonZero == 0)
5270    return DAG.getUNDEF(VT);
5271
5272  // Special case for single non-zero, non-undef, element.
5273  if (NumNonZero == 1) {
5274    unsigned Idx = CountTrailingZeros_32(NonZeros);
5275    SDValue Item = Op.getOperand(Idx);
5276
5277    // If this is an insertion of an i64 value on x86-32, and if the top bits of
5278    // the value are obviously zero, truncate the value to i32 and do the
5279    // insertion that way.  Only do this if the value is non-constant or if the
5280    // value is a constant being inserted into element 0.  It is cheaper to do
5281    // a constant pool load than it is to do a movd + shuffle.
5282    if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
5283        (!IsAllConstants || Idx == 0)) {
5284      if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
5285        // Handle SSE only.
5286        assert(VT == MVT::v2i64 && "Expected an SSE value type!");
5287        EVT VecVT = MVT::v4i32;
5288        unsigned VecElts = 4;
5289
5290        // Truncate the value (which may itself be a constant) to i32, and
5291        // convert it to a vector with movd (S2V+shuffle to zero extend).
5292        Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
5293        Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
5294        Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5295
5296        // Now we have our 32-bit value zero extended in the low element of
5297        // a vector.  If Idx != 0, swizzle it into place.
5298        if (Idx != 0) {
5299          SmallVector<int, 4> Mask;
5300          Mask.push_back(Idx);
5301          for (unsigned i = 1; i != VecElts; ++i)
5302            Mask.push_back(i);
5303          Item = DAG.getVectorShuffle(VecVT, dl, Item, DAG.getUNDEF(VecVT),
5304                                      &Mask[0]);
5305        }
5306        return DAG.getNode(ISD::BITCAST, dl, VT, Item);
5307      }
5308    }
5309
5310    // If we have a constant or non-constant insertion into the low element of
5311    // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
5312    // the rest of the elements.  This will be matched as movd/movq/movss/movsd
5313    // depending on what the source datatype is.
5314    if (Idx == 0) {
5315      if (NumZero == 0)
5316        return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5317
5318      if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
5319          (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
5320        if (VT.is256BitVector()) {
5321          SDValue ZeroVec = getZeroVector(VT, Subtarget, DAG, dl);
5322          return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, ZeroVec,
5323                             Item, DAG.getIntPtrConstant(0));
5324        }
5325        assert(VT.is128BitVector() && "Expected an SSE value type!");
5326        Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5327        // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
5328        return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5329      }
5330
5331      if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
5332        Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
5333        Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
5334        if (VT.is256BitVector()) {
5335          SDValue ZeroVec = getZeroVector(MVT::v8i32, Subtarget, DAG, dl);
5336          Item = Insert128BitVector(ZeroVec, Item, 0, DAG, dl);
5337        } else {
5338          assert(VT.is128BitVector() && "Expected an SSE value type!");
5339          Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5340        }
5341        return DAG.getNode(ISD::BITCAST, dl, VT, Item);
5342      }
5343    }
5344
5345    // Is it a vector logical left shift?
5346    if (NumElems == 2 && Idx == 1 &&
5347        X86::isZeroNode(Op.getOperand(0)) &&
5348        !X86::isZeroNode(Op.getOperand(1))) {
5349      unsigned NumBits = VT.getSizeInBits();
5350      return getVShift(true, VT,
5351                       DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
5352                                   VT, Op.getOperand(1)),
5353                       NumBits/2, DAG, *this, dl);
5354    }
5355
5356    if (IsAllConstants) // Otherwise, it's better to do a constpool load.
5357      return SDValue();
5358
5359    // Otherwise, if this is a vector with i32 or f32 elements, and the element
5360    // is a non-constant being inserted into an element other than the low one,
5361    // we can't use a constant pool load.  Instead, use SCALAR_TO_VECTOR (aka
5362    // movd/movss) to move this into the low element, then shuffle it into
5363    // place.
5364    if (EVTBits == 32) {
5365      Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5366
5367      // Turn it into a shuffle of zero and zero-extended scalar to vector.
5368      Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0, Subtarget, DAG);
5369      SmallVector<int, 8> MaskVec;
5370      for (unsigned i = 0; i != NumElems; ++i)
5371        MaskVec.push_back(i == Idx ? 0 : 1);
5372      return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
5373    }
5374  }
5375
5376  // Splat is obviously ok. Let legalizer expand it to a shuffle.
5377  if (Values.size() == 1) {
5378    if (EVTBits == 32) {
5379      // Instead of a shuffle like this:
5380      // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
5381      // Check if it's possible to issue this instead.
5382      // shuffle (vload ptr)), undef, <1, 1, 1, 1>
5383      unsigned Idx = CountTrailingZeros_32(NonZeros);
5384      SDValue Item = Op.getOperand(Idx);
5385      if (Op.getNode()->isOnlyUserOf(Item.getNode()))
5386        return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
5387    }
5388    return SDValue();
5389  }
5390
5391  // A vector full of immediates; various special cases are already
5392  // handled, so this is best done with a single constant-pool load.
5393  if (IsAllConstants)
5394    return SDValue();
5395
5396  // For AVX-length vectors, build the individual 128-bit pieces and use
5397  // shuffles to put them in place.
5398  if (VT.is256BitVector()) {
5399    SmallVector<SDValue, 32> V;
5400    for (unsigned i = 0; i != NumElems; ++i)
5401      V.push_back(Op.getOperand(i));
5402
5403    EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
5404
5405    // Build both the lower and upper subvector.
5406    SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[0], NumElems/2);
5407    SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[NumElems / 2],
5408                                NumElems/2);
5409
5410    // Recreate the wider vector with the lower and upper part.
5411    return Concat128BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
5412  }
5413
5414  // Let legalizer expand 2-wide build_vectors.
5415  if (EVTBits == 64) {
5416    if (NumNonZero == 1) {
5417      // One half is zero or undef.
5418      unsigned Idx = CountTrailingZeros_32(NonZeros);
5419      SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
5420                                 Op.getOperand(Idx));
5421      return getShuffleVectorZeroOrUndef(V2, Idx, true, Subtarget, DAG);
5422    }
5423    return SDValue();
5424  }
5425
5426  // If element VT is < 32 bits, convert it to inserts into a zero vector.
5427  if (EVTBits == 8 && NumElems == 16) {
5428    SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
5429                                        Subtarget, *this);
5430    if (V.getNode()) return V;
5431  }
5432
5433  if (EVTBits == 16 && NumElems == 8) {
5434    SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
5435                                      Subtarget, *this);
5436    if (V.getNode()) return V;
5437  }
5438
5439  // If element VT is == 32 bits, turn it into a number of shuffles.
5440  SmallVector<SDValue, 8> V(NumElems);
5441  if (NumElems == 4 && NumZero > 0) {
5442    for (unsigned i = 0; i < 4; ++i) {
5443      bool isZero = !(NonZeros & (1 << i));
5444      if (isZero)
5445        V[i] = getZeroVector(VT, Subtarget, DAG, dl);
5446      else
5447        V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
5448    }
5449
5450    for (unsigned i = 0; i < 2; ++i) {
5451      switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
5452        default: break;
5453        case 0:
5454          V[i] = V[i*2];  // Must be a zero vector.
5455          break;
5456        case 1:
5457          V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
5458          break;
5459        case 2:
5460          V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
5461          break;
5462        case 3:
5463          V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
5464          break;
5465      }
5466    }
5467
5468    bool Reverse1 = (NonZeros & 0x3) == 2;
5469    bool Reverse2 = ((NonZeros & (0x3 << 2)) >> 2) == 2;
5470    int MaskVec[] = {
5471      Reverse1 ? 1 : 0,
5472      Reverse1 ? 0 : 1,
5473      static_cast<int>(Reverse2 ? NumElems+1 : NumElems),
5474      static_cast<int>(Reverse2 ? NumElems   : NumElems+1)
5475    };
5476    return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
5477  }
5478
5479  if (Values.size() > 1 && VT.is128BitVector()) {
5480    // Check for a build vector of consecutive loads.
5481    for (unsigned i = 0; i < NumElems; ++i)
5482      V[i] = Op.getOperand(i);
5483
5484    // Check for elements which are consecutive loads.
5485    SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG);
5486    if (LD.getNode())
5487      return LD;
5488
5489    // For SSE 4.1, use insertps to put the high elements into the low element.
5490    if (getSubtarget()->hasSSE41()) {
5491      SDValue Result;
5492      if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
5493        Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
5494      else
5495        Result = DAG.getUNDEF(VT);
5496
5497      for (unsigned i = 1; i < NumElems; ++i) {
5498        if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
5499        Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
5500                             Op.getOperand(i), DAG.getIntPtrConstant(i));
5501      }
5502      return Result;
5503    }
5504
5505    // Otherwise, expand into a number of unpckl*, start by extending each of
5506    // our (non-undef) elements to the full vector width with the element in the
5507    // bottom slot of the vector (which generates no code for SSE).
5508    for (unsigned i = 0; i < NumElems; ++i) {
5509      if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
5510        V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
5511      else
5512        V[i] = DAG.getUNDEF(VT);
5513    }
5514
5515    // Next, we iteratively mix elements, e.g. for v4f32:
5516    //   Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
5517    //         : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
5518    //   Step 2: unpcklps X, Y ==>    <3, 2, 1, 0>
5519    unsigned EltStride = NumElems >> 1;
5520    while (EltStride != 0) {
5521      for (unsigned i = 0; i < EltStride; ++i) {
5522        // If V[i+EltStride] is undef and this is the first round of mixing,
5523        // then it is safe to just drop this shuffle: V[i] is already in the
5524        // right place, the one element (since it's the first round) being
5525        // inserted as undef can be dropped.  This isn't safe for successive
5526        // rounds because they will permute elements within both vectors.
5527        if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
5528            EltStride == NumElems/2)
5529          continue;
5530
5531        V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
5532      }
5533      EltStride >>= 1;
5534    }
5535    return V[0];
5536  }
5537  return SDValue();
5538}
5539
5540// LowerAVXCONCAT_VECTORS - 256-bit AVX can use the vinsertf128 instruction
5541// to create 256-bit vectors from two other 128-bit ones.
5542static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5543  DebugLoc dl = Op.getDebugLoc();
5544  EVT ResVT = Op.getValueType();
5545
5546  assert(ResVT.is256BitVector() && "Value type must be 256-bit wide");
5547
5548  SDValue V1 = Op.getOperand(0);
5549  SDValue V2 = Op.getOperand(1);
5550  unsigned NumElems = ResVT.getVectorNumElements();
5551
5552  return Concat128BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
5553}
5554
5555SDValue
5556X86TargetLowering::LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) const {
5557  assert(Op.getNumOperands() == 2);
5558
5559  // 256-bit AVX can use the vinsertf128 instruction to create 256-bit vectors
5560  // from two other 128-bit ones.
5561  return LowerAVXCONCAT_VECTORS(Op, DAG);
5562}
5563
5564// Try to lower a shuffle node into a simple blend instruction.
5565static SDValue LowerVECTOR_SHUFFLEtoBlend(ShuffleVectorSDNode *SVOp,
5566                                          const X86Subtarget *Subtarget,
5567                                          SelectionDAG &DAG) {
5568  SDValue V1 = SVOp->getOperand(0);
5569  SDValue V2 = SVOp->getOperand(1);
5570  DebugLoc dl = SVOp->getDebugLoc();
5571  MVT VT = SVOp->getValueType(0).getSimpleVT();
5572  unsigned NumElems = VT.getVectorNumElements();
5573
5574  if (!Subtarget->hasSSE41())
5575    return SDValue();
5576
5577  unsigned ISDNo = 0;
5578  MVT OpTy;
5579
5580  switch (VT.SimpleTy) {
5581  default: return SDValue();
5582  case MVT::v8i16:
5583    ISDNo = X86ISD::BLENDPW;
5584    OpTy = MVT::v8i16;
5585    break;
5586  case MVT::v4i32:
5587  case MVT::v4f32:
5588    ISDNo = X86ISD::BLENDPS;
5589    OpTy = MVT::v4f32;
5590    break;
5591  case MVT::v2i64:
5592  case MVT::v2f64:
5593    ISDNo = X86ISD::BLENDPD;
5594    OpTy = MVT::v2f64;
5595    break;
5596  case MVT::v8i32:
5597  case MVT::v8f32:
5598    if (!Subtarget->hasAVX())
5599      return SDValue();
5600    ISDNo = X86ISD::BLENDPS;
5601    OpTy = MVT::v8f32;
5602    break;
5603  case MVT::v4i64:
5604  case MVT::v4f64:
5605    if (!Subtarget->hasAVX())
5606      return SDValue();
5607    ISDNo = X86ISD::BLENDPD;
5608    OpTy = MVT::v4f64;
5609    break;
5610  }
5611  assert(ISDNo && "Invalid Op Number");
5612
5613  unsigned MaskVals = 0;
5614
5615  for (unsigned i = 0; i != NumElems; ++i) {
5616    int EltIdx = SVOp->getMaskElt(i);
5617    if (EltIdx == (int)i || EltIdx < 0)
5618      MaskVals |= (1<<i);
5619    else if (EltIdx == (int)(i + NumElems))
5620      continue; // Bit is set to zero;
5621    else
5622      return SDValue();
5623  }
5624
5625  V1 = DAG.getNode(ISD::BITCAST, dl, OpTy, V1);
5626  V2 = DAG.getNode(ISD::BITCAST, dl, OpTy, V2);
5627  SDValue Ret =  DAG.getNode(ISDNo, dl, OpTy, V1, V2,
5628                             DAG.getConstant(MaskVals, MVT::i32));
5629  return DAG.getNode(ISD::BITCAST, dl, VT, Ret);
5630}
5631
5632// v8i16 shuffles - Prefer shuffles in the following order:
5633// 1. [all]   pshuflw, pshufhw, optional move
5634// 2. [ssse3] 1 x pshufb
5635// 3. [ssse3] 2 x pshufb + 1 x por
5636// 4. [all]   mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
5637SDValue
5638X86TargetLowering::LowerVECTOR_SHUFFLEv8i16(SDValue Op,
5639                                            SelectionDAG &DAG) const {
5640  ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5641  SDValue V1 = SVOp->getOperand(0);
5642  SDValue V2 = SVOp->getOperand(1);
5643  DebugLoc dl = SVOp->getDebugLoc();
5644  SmallVector<int, 8> MaskVals;
5645
5646  // Determine if more than 1 of the words in each of the low and high quadwords
5647  // of the result come from the same quadword of one of the two inputs.  Undef
5648  // mask values count as coming from any quadword, for better codegen.
5649  unsigned LoQuad[] = { 0, 0, 0, 0 };
5650  unsigned HiQuad[] = { 0, 0, 0, 0 };
5651  std::bitset<4> InputQuads;
5652  for (unsigned i = 0; i < 8; ++i) {
5653    unsigned *Quad = i < 4 ? LoQuad : HiQuad;
5654    int EltIdx = SVOp->getMaskElt(i);
5655    MaskVals.push_back(EltIdx);
5656    if (EltIdx < 0) {
5657      ++Quad[0];
5658      ++Quad[1];
5659      ++Quad[2];
5660      ++Quad[3];
5661      continue;
5662    }
5663    ++Quad[EltIdx / 4];
5664    InputQuads.set(EltIdx / 4);
5665  }
5666
5667  int BestLoQuad = -1;
5668  unsigned MaxQuad = 1;
5669  for (unsigned i = 0; i < 4; ++i) {
5670    if (LoQuad[i] > MaxQuad) {
5671      BestLoQuad = i;
5672      MaxQuad = LoQuad[i];
5673    }
5674  }
5675
5676  int BestHiQuad = -1;
5677  MaxQuad = 1;
5678  for (unsigned i = 0; i < 4; ++i) {
5679    if (HiQuad[i] > MaxQuad) {
5680      BestHiQuad = i;
5681      MaxQuad = HiQuad[i];
5682    }
5683  }
5684
5685  // For SSSE3, If all 8 words of the result come from only 1 quadword of each
5686  // of the two input vectors, shuffle them into one input vector so only a
5687  // single pshufb instruction is necessary. If There are more than 2 input
5688  // quads, disable the next transformation since it does not help SSSE3.
5689  bool V1Used = InputQuads[0] || InputQuads[1];
5690  bool V2Used = InputQuads[2] || InputQuads[3];
5691  if (Subtarget->hasSSSE3()) {
5692    if (InputQuads.count() == 2 && V1Used && V2Used) {
5693      BestLoQuad = InputQuads[0] ? 0 : 1;
5694      BestHiQuad = InputQuads[2] ? 2 : 3;
5695    }
5696    if (InputQuads.count() > 2) {
5697      BestLoQuad = -1;
5698      BestHiQuad = -1;
5699    }
5700  }
5701
5702  // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
5703  // the shuffle mask.  If a quad is scored as -1, that means that it contains
5704  // words from all 4 input quadwords.
5705  SDValue NewV;
5706  if (BestLoQuad >= 0 || BestHiQuad >= 0) {
5707    int MaskV[] = {
5708      BestLoQuad < 0 ? 0 : BestLoQuad,
5709      BestHiQuad < 0 ? 1 : BestHiQuad
5710    };
5711    NewV = DAG.getVectorShuffle(MVT::v2i64, dl,
5712                  DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1),
5713                  DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2), &MaskV[0]);
5714    NewV = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, NewV);
5715
5716    // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
5717    // source words for the shuffle, to aid later transformations.
5718    bool AllWordsInNewV = true;
5719    bool InOrder[2] = { true, true };
5720    for (unsigned i = 0; i != 8; ++i) {
5721      int idx = MaskVals[i];
5722      if (idx != (int)i)
5723        InOrder[i/4] = false;
5724      if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
5725        continue;
5726      AllWordsInNewV = false;
5727      break;
5728    }
5729
5730    bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
5731    if (AllWordsInNewV) {
5732      for (int i = 0; i != 8; ++i) {
5733        int idx = MaskVals[i];
5734        if (idx < 0)
5735          continue;
5736        idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
5737        if ((idx != i) && idx < 4)
5738          pshufhw = false;
5739        if ((idx != i) && idx > 3)
5740          pshuflw = false;
5741      }
5742      V1 = NewV;
5743      V2Used = false;
5744      BestLoQuad = 0;
5745      BestHiQuad = 1;
5746    }
5747
5748    // If we've eliminated the use of V2, and the new mask is a pshuflw or
5749    // pshufhw, that's as cheap as it gets.  Return the new shuffle.
5750    if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
5751      unsigned Opc = pshufhw ? X86ISD::PSHUFHW : X86ISD::PSHUFLW;
5752      unsigned TargetMask = 0;
5753      NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV,
5754                                  DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
5755      ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
5756      TargetMask = pshufhw ? getShufflePSHUFHWImmediate(SVOp):
5757                             getShufflePSHUFLWImmediate(SVOp);
5758      V1 = NewV.getOperand(0);
5759      return getTargetShuffleNode(Opc, dl, MVT::v8i16, V1, TargetMask, DAG);
5760    }
5761  }
5762
5763  // If we have SSSE3, and all words of the result are from 1 input vector,
5764  // case 2 is generated, otherwise case 3 is generated.  If no SSSE3
5765  // is present, fall back to case 4.
5766  if (Subtarget->hasSSSE3()) {
5767    SmallVector<SDValue,16> pshufbMask;
5768
5769    // If we have elements from both input vectors, set the high bit of the
5770    // shuffle mask element to zero out elements that come from V2 in the V1
5771    // mask, and elements that come from V1 in the V2 mask, so that the two
5772    // results can be OR'd together.
5773    bool TwoInputs = V1Used && V2Used;
5774    for (unsigned i = 0; i != 8; ++i) {
5775      int EltIdx = MaskVals[i] * 2;
5776      int Idx0 = (TwoInputs && (EltIdx >= 16)) ? 0x80 : EltIdx;
5777      int Idx1 = (TwoInputs && (EltIdx >= 16)) ? 0x80 : EltIdx+1;
5778      pshufbMask.push_back(DAG.getConstant(Idx0,   MVT::i8));
5779      pshufbMask.push_back(DAG.getConstant(Idx1, MVT::i8));
5780    }
5781    V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V1);
5782    V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
5783                     DAG.getNode(ISD::BUILD_VECTOR, dl,
5784                                 MVT::v16i8, &pshufbMask[0], 16));
5785    if (!TwoInputs)
5786      return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5787
5788    // Calculate the shuffle mask for the second input, shuffle it, and
5789    // OR it with the first shuffled input.
5790    pshufbMask.clear();
5791    for (unsigned i = 0; i != 8; ++i) {
5792      int EltIdx = MaskVals[i] * 2;
5793      int Idx0 = (EltIdx < 16) ? 0x80 : EltIdx - 16;
5794      int Idx1 = (EltIdx < 16) ? 0x80 : EltIdx - 15;
5795      pshufbMask.push_back(DAG.getConstant(Idx0, MVT::i8));
5796      pshufbMask.push_back(DAG.getConstant(Idx1, MVT::i8));
5797    }
5798    V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V2);
5799    V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
5800                     DAG.getNode(ISD::BUILD_VECTOR, dl,
5801                                 MVT::v16i8, &pshufbMask[0], 16));
5802    V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
5803    return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5804  }
5805
5806  // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
5807  // and update MaskVals with new element order.
5808  std::bitset<8> InOrder;
5809  if (BestLoQuad >= 0) {
5810    int MaskV[] = { -1, -1, -1, -1, 4, 5, 6, 7 };
5811    for (int i = 0; i != 4; ++i) {
5812      int idx = MaskVals[i];
5813      if (idx < 0) {
5814        InOrder.set(i);
5815      } else if ((idx / 4) == BestLoQuad) {
5816        MaskV[i] = idx & 3;
5817        InOrder.set(i);
5818      }
5819    }
5820    NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
5821                                &MaskV[0]);
5822
5823    if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3()) {
5824      ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
5825      NewV = getTargetShuffleNode(X86ISD::PSHUFLW, dl, MVT::v8i16,
5826                                  NewV.getOperand(0),
5827                                  getShufflePSHUFLWImmediate(SVOp), DAG);
5828    }
5829  }
5830
5831  // If BestHi >= 0, generate a pshufhw to put the high elements in order,
5832  // and update MaskVals with the new element order.
5833  if (BestHiQuad >= 0) {
5834    int MaskV[] = { 0, 1, 2, 3, -1, -1, -1, -1 };
5835    for (unsigned i = 4; i != 8; ++i) {
5836      int idx = MaskVals[i];
5837      if (idx < 0) {
5838        InOrder.set(i);
5839      } else if ((idx / 4) == BestHiQuad) {
5840        MaskV[i] = (idx & 3) + 4;
5841        InOrder.set(i);
5842      }
5843    }
5844    NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
5845                                &MaskV[0]);
5846
5847    if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3()) {
5848      ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
5849      NewV = getTargetShuffleNode(X86ISD::PSHUFHW, dl, MVT::v8i16,
5850                                  NewV.getOperand(0),
5851                                  getShufflePSHUFHWImmediate(SVOp), DAG);
5852    }
5853  }
5854
5855  // In case BestHi & BestLo were both -1, which means each quadword has a word
5856  // from each of the four input quadwords, calculate the InOrder bitvector now
5857  // before falling through to the insert/extract cleanup.
5858  if (BestLoQuad == -1 && BestHiQuad == -1) {
5859    NewV = V1;
5860    for (int i = 0; i != 8; ++i)
5861      if (MaskVals[i] < 0 || MaskVals[i] == i)
5862        InOrder.set(i);
5863  }
5864
5865  // The other elements are put in the right place using pextrw and pinsrw.
5866  for (unsigned i = 0; i != 8; ++i) {
5867    if (InOrder[i])
5868      continue;
5869    int EltIdx = MaskVals[i];
5870    if (EltIdx < 0)
5871      continue;
5872    SDValue ExtOp = (EltIdx < 8) ?
5873      DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
5874                  DAG.getIntPtrConstant(EltIdx)) :
5875      DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
5876                  DAG.getIntPtrConstant(EltIdx - 8));
5877    NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
5878                       DAG.getIntPtrConstant(i));
5879  }
5880  return NewV;
5881}
5882
5883// v16i8 shuffles - Prefer shuffles in the following order:
5884// 1. [ssse3] 1 x pshufb
5885// 2. [ssse3] 2 x pshufb + 1 x por
5886// 3. [all]   v8i16 shuffle + N x pextrw + rotate + pinsrw
5887static
5888SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
5889                                 SelectionDAG &DAG,
5890                                 const X86TargetLowering &TLI) {
5891  SDValue V1 = SVOp->getOperand(0);
5892  SDValue V2 = SVOp->getOperand(1);
5893  DebugLoc dl = SVOp->getDebugLoc();
5894  ArrayRef<int> MaskVals = SVOp->getMask();
5895
5896  // If we have SSSE3, case 1 is generated when all result bytes come from
5897  // one of  the inputs.  Otherwise, case 2 is generated.  If no SSSE3 is
5898  // present, fall back to case 3.
5899
5900  // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
5901  if (TLI.getSubtarget()->hasSSSE3()) {
5902    SmallVector<SDValue,16> pshufbMask;
5903
5904    // If all result elements are from one input vector, then only translate
5905    // undef mask values to 0x80 (zero out result) in the pshufb mask.
5906    //
5907    // Otherwise, we have elements from both input vectors, and must zero out
5908    // elements that come from V2 in the first mask, and V1 in the second mask
5909    // so that we can OR them together.
5910    for (unsigned i = 0; i != 16; ++i) {
5911      int EltIdx = MaskVals[i];
5912      if (EltIdx < 0 || EltIdx >= 16)
5913        EltIdx = 0x80;
5914      pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
5915    }
5916    V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
5917                     DAG.getNode(ISD::BUILD_VECTOR, dl,
5918                                 MVT::v16i8, &pshufbMask[0], 16));
5919
5920    // As PSHUFB will zero elements with negative indices, it's safe to ignore
5921    // the 2nd operand if it's undefined or zero.
5922    if (V2.getOpcode() == ISD::UNDEF ||
5923        ISD::isBuildVectorAllZeros(V2.getNode()))
5924      return V1;
5925
5926    // Calculate the shuffle mask for the second input, shuffle it, and
5927    // OR it with the first shuffled input.
5928    pshufbMask.clear();
5929    for (unsigned i = 0; i != 16; ++i) {
5930      int EltIdx = MaskVals[i];
5931      EltIdx = (EltIdx < 16) ? 0x80 : EltIdx - 16;
5932      pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
5933    }
5934    V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
5935                     DAG.getNode(ISD::BUILD_VECTOR, dl,
5936                                 MVT::v16i8, &pshufbMask[0], 16));
5937    return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
5938  }
5939
5940  // No SSSE3 - Calculate in place words and then fix all out of place words
5941  // With 0-16 extracts & inserts.  Worst case is 16 bytes out of order from
5942  // the 16 different words that comprise the two doublequadword input vectors.
5943  V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5944  V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
5945  SDValue NewV = V1;
5946  for (int i = 0; i != 8; ++i) {
5947    int Elt0 = MaskVals[i*2];
5948    int Elt1 = MaskVals[i*2+1];
5949
5950    // This word of the result is all undef, skip it.
5951    if (Elt0 < 0 && Elt1 < 0)
5952      continue;
5953
5954    // This word of the result is already in the correct place, skip it.
5955    if ((Elt0 == i*2) && (Elt1 == i*2+1))
5956      continue;
5957
5958    SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
5959    SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
5960    SDValue InsElt;
5961
5962    // If Elt0 and Elt1 are defined, are consecutive, and can be load
5963    // using a single extract together, load it and store it.
5964    if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
5965      InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
5966                           DAG.getIntPtrConstant(Elt1 / 2));
5967      NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
5968                        DAG.getIntPtrConstant(i));
5969      continue;
5970    }
5971
5972    // If Elt1 is defined, extract it from the appropriate source.  If the
5973    // source byte is not also odd, shift the extracted word left 8 bits
5974    // otherwise clear the bottom 8 bits if we need to do an or.
5975    if (Elt1 >= 0) {
5976      InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
5977                           DAG.getIntPtrConstant(Elt1 / 2));
5978      if ((Elt1 & 1) == 0)
5979        InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
5980                             DAG.getConstant(8,
5981                                  TLI.getShiftAmountTy(InsElt.getValueType())));
5982      else if (Elt0 >= 0)
5983        InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
5984                             DAG.getConstant(0xFF00, MVT::i16));
5985    }
5986    // If Elt0 is defined, extract it from the appropriate source.  If the
5987    // source byte is not also even, shift the extracted word right 8 bits. If
5988    // Elt1 was also defined, OR the extracted values together before
5989    // inserting them in the result.
5990    if (Elt0 >= 0) {
5991      SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
5992                                    Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
5993      if ((Elt0 & 1) != 0)
5994        InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
5995                              DAG.getConstant(8,
5996                                 TLI.getShiftAmountTy(InsElt0.getValueType())));
5997      else if (Elt1 >= 0)
5998        InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
5999                             DAG.getConstant(0x00FF, MVT::i16));
6000      InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
6001                         : InsElt0;
6002    }
6003    NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
6004                       DAG.getIntPtrConstant(i));
6005  }
6006  return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, NewV);
6007}
6008
6009/// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
6010/// ones, or rewriting v4i32 / v4f32 as 2 wide ones if possible. This can be
6011/// done when every pair / quad of shuffle mask elements point to elements in
6012/// the right sequence. e.g.
6013/// vector_shuffle X, Y, <2, 3, | 10, 11, | 0, 1, | 14, 15>
6014static
6015SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
6016                                 SelectionDAG &DAG, DebugLoc dl) {
6017  MVT VT = SVOp->getValueType(0).getSimpleVT();
6018  unsigned NumElems = VT.getVectorNumElements();
6019  MVT NewVT;
6020  unsigned Scale;
6021  switch (VT.SimpleTy) {
6022  default: llvm_unreachable("Unexpected!");
6023  case MVT::v4f32:  NewVT = MVT::v2f64; Scale = 2; break;
6024  case MVT::v4i32:  NewVT = MVT::v2i64; Scale = 2; break;
6025  case MVT::v8i16:  NewVT = MVT::v4i32; Scale = 2; break;
6026  case MVT::v16i8:  NewVT = MVT::v4i32; Scale = 4; break;
6027  case MVT::v16i16: NewVT = MVT::v8i32; Scale = 2; break;
6028  case MVT::v32i8:  NewVT = MVT::v8i32; Scale = 4; break;
6029  }
6030
6031  SmallVector<int, 8> MaskVec;
6032  for (unsigned i = 0; i != NumElems; i += Scale) {
6033    int StartIdx = -1;
6034    for (unsigned j = 0; j != Scale; ++j) {
6035      int EltIdx = SVOp->getMaskElt(i+j);
6036      if (EltIdx < 0)
6037        continue;
6038      if (StartIdx < 0)
6039        StartIdx = (EltIdx / Scale);
6040      if (EltIdx != (int)(StartIdx*Scale + j))
6041        return SDValue();
6042    }
6043    MaskVec.push_back(StartIdx);
6044  }
6045
6046  SDValue V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(0));
6047  SDValue V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(1));
6048  return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
6049}
6050
6051/// getVZextMovL - Return a zero-extending vector move low node.
6052///
6053static SDValue getVZextMovL(EVT VT, EVT OpVT,
6054                            SDValue SrcOp, SelectionDAG &DAG,
6055                            const X86Subtarget *Subtarget, DebugLoc dl) {
6056  if (VT == MVT::v2f64 || VT == MVT::v4f32) {
6057    LoadSDNode *LD = NULL;
6058    if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
6059      LD = dyn_cast<LoadSDNode>(SrcOp);
6060    if (!LD) {
6061      // movssrr and movsdrr do not clear top bits. Try to use movd, movq
6062      // instead.
6063      MVT ExtVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
6064      if ((ExtVT != MVT::i64 || Subtarget->is64Bit()) &&
6065          SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
6066          SrcOp.getOperand(0).getOpcode() == ISD::BITCAST &&
6067          SrcOp.getOperand(0).getOperand(0).getValueType() == ExtVT) {
6068        // PR2108
6069        OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
6070        return DAG.getNode(ISD::BITCAST, dl, VT,
6071                           DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
6072                                       DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6073                                                   OpVT,
6074                                                   SrcOp.getOperand(0)
6075                                                          .getOperand(0))));
6076      }
6077    }
6078  }
6079
6080  return DAG.getNode(ISD::BITCAST, dl, VT,
6081                     DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
6082                                 DAG.getNode(ISD::BITCAST, dl,
6083                                             OpVT, SrcOp)));
6084}
6085
6086/// LowerVECTOR_SHUFFLE_256 - Handle all 256-bit wide vectors shuffles
6087/// which could not be matched by any known target speficic shuffle
6088static SDValue
6089LowerVECTOR_SHUFFLE_256(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
6090
6091  SDValue NewOp = Compact8x32ShuffleNode(SVOp, DAG);
6092  if (NewOp.getNode())
6093    return NewOp;
6094
6095  EVT VT = SVOp->getValueType(0);
6096
6097  unsigned NumElems = VT.getVectorNumElements();
6098  unsigned NumLaneElems = NumElems / 2;
6099
6100  DebugLoc dl = SVOp->getDebugLoc();
6101  MVT EltVT = VT.getVectorElementType().getSimpleVT();
6102  EVT NVT = MVT::getVectorVT(EltVT, NumLaneElems);
6103  SDValue Output[2];
6104
6105  SmallVector<int, 16> Mask;
6106  for (unsigned l = 0; l < 2; ++l) {
6107    // Build a shuffle mask for the output, discovering on the fly which
6108    // input vectors to use as shuffle operands (recorded in InputUsed).
6109    // If building a suitable shuffle vector proves too hard, then bail
6110    // out with UseBuildVector set.
6111    bool UseBuildVector = false;
6112    int InputUsed[2] = { -1, -1 }; // Not yet discovered.
6113    unsigned LaneStart = l * NumLaneElems;
6114    for (unsigned i = 0; i != NumLaneElems; ++i) {
6115      // The mask element.  This indexes into the input.
6116      int Idx = SVOp->getMaskElt(i+LaneStart);
6117      if (Idx < 0) {
6118        // the mask element does not index into any input vector.
6119        Mask.push_back(-1);
6120        continue;
6121      }
6122
6123      // The input vector this mask element indexes into.
6124      int Input = Idx / NumLaneElems;
6125
6126      // Turn the index into an offset from the start of the input vector.
6127      Idx -= Input * NumLaneElems;
6128
6129      // Find or create a shuffle vector operand to hold this input.
6130      unsigned OpNo;
6131      for (OpNo = 0; OpNo < array_lengthof(InputUsed); ++OpNo) {
6132        if (InputUsed[OpNo] == Input)
6133          // This input vector is already an operand.
6134          break;
6135        if (InputUsed[OpNo] < 0) {
6136          // Create a new operand for this input vector.
6137          InputUsed[OpNo] = Input;
6138          break;
6139        }
6140      }
6141
6142      if (OpNo >= array_lengthof(InputUsed)) {
6143        // More than two input vectors used!  Give up on trying to create a
6144        // shuffle vector.  Insert all elements into a BUILD_VECTOR instead.
6145        UseBuildVector = true;
6146        break;
6147      }
6148
6149      // Add the mask index for the new shuffle vector.
6150      Mask.push_back(Idx + OpNo * NumLaneElems);
6151    }
6152
6153    if (UseBuildVector) {
6154      SmallVector<SDValue, 16> SVOps;
6155      for (unsigned i = 0; i != NumLaneElems; ++i) {
6156        // The mask element.  This indexes into the input.
6157        int Idx = SVOp->getMaskElt(i+LaneStart);
6158        if (Idx < 0) {
6159          SVOps.push_back(DAG.getUNDEF(EltVT));
6160          continue;
6161        }
6162
6163        // The input vector this mask element indexes into.
6164        int Input = Idx / NumElems;
6165
6166        // Turn the index into an offset from the start of the input vector.
6167        Idx -= Input * NumElems;
6168
6169        // Extract the vector element by hand.
6170        SVOps.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
6171                                    SVOp->getOperand(Input),
6172                                    DAG.getIntPtrConstant(Idx)));
6173      }
6174
6175      // Construct the output using a BUILD_VECTOR.
6176      Output[l] = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, &SVOps[0],
6177                              SVOps.size());
6178    } else if (InputUsed[0] < 0) {
6179      // No input vectors were used! The result is undefined.
6180      Output[l] = DAG.getUNDEF(NVT);
6181    } else {
6182      SDValue Op0 = Extract128BitVector(SVOp->getOperand(InputUsed[0] / 2),
6183                                        (InputUsed[0] % 2) * NumLaneElems,
6184                                        DAG, dl);
6185      // If only one input was used, use an undefined vector for the other.
6186      SDValue Op1 = (InputUsed[1] < 0) ? DAG.getUNDEF(NVT) :
6187        Extract128BitVector(SVOp->getOperand(InputUsed[1] / 2),
6188                            (InputUsed[1] % 2) * NumLaneElems, DAG, dl);
6189      // At least one input vector was used. Create a new shuffle vector.
6190      Output[l] = DAG.getVectorShuffle(NVT, dl, Op0, Op1, &Mask[0]);
6191    }
6192
6193    Mask.clear();
6194  }
6195
6196  // Concatenate the result back
6197  return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Output[0], Output[1]);
6198}
6199
6200/// LowerVECTOR_SHUFFLE_128v4 - Handle all 128-bit wide vectors with
6201/// 4 elements, and match them with several different shuffle types.
6202static SDValue
6203LowerVECTOR_SHUFFLE_128v4(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
6204  SDValue V1 = SVOp->getOperand(0);
6205  SDValue V2 = SVOp->getOperand(1);
6206  DebugLoc dl = SVOp->getDebugLoc();
6207  EVT VT = SVOp->getValueType(0);
6208
6209  assert(VT.is128BitVector() && "Unsupported vector size");
6210
6211  std::pair<int, int> Locs[4];
6212  int Mask1[] = { -1, -1, -1, -1 };
6213  SmallVector<int, 8> PermMask(SVOp->getMask().begin(), SVOp->getMask().end());
6214
6215  unsigned NumHi = 0;
6216  unsigned NumLo = 0;
6217  for (unsigned i = 0; i != 4; ++i) {
6218    int Idx = PermMask[i];
6219    if (Idx < 0) {
6220      Locs[i] = std::make_pair(-1, -1);
6221    } else {
6222      assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
6223      if (Idx < 4) {
6224        Locs[i] = std::make_pair(0, NumLo);
6225        Mask1[NumLo] = Idx;
6226        NumLo++;
6227      } else {
6228        Locs[i] = std::make_pair(1, NumHi);
6229        if (2+NumHi < 4)
6230          Mask1[2+NumHi] = Idx;
6231        NumHi++;
6232      }
6233    }
6234  }
6235
6236  if (NumLo <= 2 && NumHi <= 2) {
6237    // If no more than two elements come from either vector. This can be
6238    // implemented with two shuffles. First shuffle gather the elements.
6239    // The second shuffle, which takes the first shuffle as both of its
6240    // vector operands, put the elements into the right order.
6241    V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6242
6243    int Mask2[] = { -1, -1, -1, -1 };
6244
6245    for (unsigned i = 0; i != 4; ++i)
6246      if (Locs[i].first != -1) {
6247        unsigned Idx = (i < 2) ? 0 : 4;
6248        Idx += Locs[i].first * 2 + Locs[i].second;
6249        Mask2[i] = Idx;
6250      }
6251
6252    return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
6253  }
6254
6255  if (NumLo == 3 || NumHi == 3) {
6256    // Otherwise, we must have three elements from one vector, call it X, and
6257    // one element from the other, call it Y.  First, use a shufps to build an
6258    // intermediate vector with the one element from Y and the element from X
6259    // that will be in the same half in the final destination (the indexes don't
6260    // matter). Then, use a shufps to build the final vector, taking the half
6261    // containing the element from Y from the intermediate, and the other half
6262    // from X.
6263    if (NumHi == 3) {
6264      // Normalize it so the 3 elements come from V1.
6265      CommuteVectorShuffleMask(PermMask, 4);
6266      std::swap(V1, V2);
6267    }
6268
6269    // Find the element from V2.
6270    unsigned HiIndex;
6271    for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
6272      int Val = PermMask[HiIndex];
6273      if (Val < 0)
6274        continue;
6275      if (Val >= 4)
6276        break;
6277    }
6278
6279    Mask1[0] = PermMask[HiIndex];
6280    Mask1[1] = -1;
6281    Mask1[2] = PermMask[HiIndex^1];
6282    Mask1[3] = -1;
6283    V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6284
6285    if (HiIndex >= 2) {
6286      Mask1[0] = PermMask[0];
6287      Mask1[1] = PermMask[1];
6288      Mask1[2] = HiIndex & 1 ? 6 : 4;
6289      Mask1[3] = HiIndex & 1 ? 4 : 6;
6290      return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6291    }
6292
6293    Mask1[0] = HiIndex & 1 ? 2 : 0;
6294    Mask1[1] = HiIndex & 1 ? 0 : 2;
6295    Mask1[2] = PermMask[2];
6296    Mask1[3] = PermMask[3];
6297    if (Mask1[2] >= 0)
6298      Mask1[2] += 4;
6299    if (Mask1[3] >= 0)
6300      Mask1[3] += 4;
6301    return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
6302  }
6303
6304  // Break it into (shuffle shuffle_hi, shuffle_lo).
6305  int LoMask[] = { -1, -1, -1, -1 };
6306  int HiMask[] = { -1, -1, -1, -1 };
6307
6308  int *MaskPtr = LoMask;
6309  unsigned MaskIdx = 0;
6310  unsigned LoIdx = 0;
6311  unsigned HiIdx = 2;
6312  for (unsigned i = 0; i != 4; ++i) {
6313    if (i == 2) {
6314      MaskPtr = HiMask;
6315      MaskIdx = 1;
6316      LoIdx = 0;
6317      HiIdx = 2;
6318    }
6319    int Idx = PermMask[i];
6320    if (Idx < 0) {
6321      Locs[i] = std::make_pair(-1, -1);
6322    } else if (Idx < 4) {
6323      Locs[i] = std::make_pair(MaskIdx, LoIdx);
6324      MaskPtr[LoIdx] = Idx;
6325      LoIdx++;
6326    } else {
6327      Locs[i] = std::make_pair(MaskIdx, HiIdx);
6328      MaskPtr[HiIdx] = Idx;
6329      HiIdx++;
6330    }
6331  }
6332
6333  SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
6334  SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
6335  int MaskOps[] = { -1, -1, -1, -1 };
6336  for (unsigned i = 0; i != 4; ++i)
6337    if (Locs[i].first != -1)
6338      MaskOps[i] = Locs[i].first * 4 + Locs[i].second;
6339  return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
6340}
6341
6342static bool MayFoldVectorLoad(SDValue V) {
6343  if (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
6344    V = V.getOperand(0);
6345  if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
6346    V = V.getOperand(0);
6347  if (V.hasOneUse() && V.getOpcode() == ISD::BUILD_VECTOR &&
6348      V.getNumOperands() == 2 && V.getOperand(1).getOpcode() == ISD::UNDEF)
6349    // BUILD_VECTOR (load), undef
6350    V = V.getOperand(0);
6351  if (MayFoldLoad(V))
6352    return true;
6353  return false;
6354}
6355
6356// FIXME: the version above should always be used. Since there's
6357// a bug where several vector shuffles can't be folded because the
6358// DAG is not updated during lowering and a node claims to have two
6359// uses while it only has one, use this version, and let isel match
6360// another instruction if the load really happens to have more than
6361// one use. Remove this version after this bug get fixed.
6362// rdar://8434668, PR8156
6363static bool RelaxedMayFoldVectorLoad(SDValue V) {
6364  if (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
6365    V = V.getOperand(0);
6366  if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
6367    V = V.getOperand(0);
6368  if (ISD::isNormalLoad(V.getNode()))
6369    return true;
6370  return false;
6371}
6372
6373static
6374SDValue getMOVDDup(SDValue &Op, DebugLoc &dl, SDValue V1, SelectionDAG &DAG) {
6375  EVT VT = Op.getValueType();
6376
6377  // Canonizalize to v2f64.
6378  V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
6379  return DAG.getNode(ISD::BITCAST, dl, VT,
6380                     getTargetShuffleNode(X86ISD::MOVDDUP, dl, MVT::v2f64,
6381                                          V1, DAG));
6382}
6383
6384static
6385SDValue getMOVLowToHigh(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG,
6386                        bool HasSSE2) {
6387  SDValue V1 = Op.getOperand(0);
6388  SDValue V2 = Op.getOperand(1);
6389  EVT VT = Op.getValueType();
6390
6391  assert(VT != MVT::v2i64 && "unsupported shuffle type");
6392
6393  if (HasSSE2 && VT == MVT::v2f64)
6394    return getTargetShuffleNode(X86ISD::MOVLHPD, dl, VT, V1, V2, DAG);
6395
6396  // v4f32 or v4i32: canonizalized to v4f32 (which is legal for SSE1)
6397  return DAG.getNode(ISD::BITCAST, dl, VT,
6398                     getTargetShuffleNode(X86ISD::MOVLHPS, dl, MVT::v4f32,
6399                           DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V1),
6400                           DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V2), DAG));
6401}
6402
6403static
6404SDValue getMOVHighToLow(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG) {
6405  SDValue V1 = Op.getOperand(0);
6406  SDValue V2 = Op.getOperand(1);
6407  EVT VT = Op.getValueType();
6408
6409  assert((VT == MVT::v4i32 || VT == MVT::v4f32) &&
6410         "unsupported shuffle type");
6411
6412  if (V2.getOpcode() == ISD::UNDEF)
6413    V2 = V1;
6414
6415  // v4i32 or v4f32
6416  return getTargetShuffleNode(X86ISD::MOVHLPS, dl, VT, V1, V2, DAG);
6417}
6418
6419static
6420SDValue getMOVLP(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG, bool HasSSE2) {
6421  SDValue V1 = Op.getOperand(0);
6422  SDValue V2 = Op.getOperand(1);
6423  EVT VT = Op.getValueType();
6424  unsigned NumElems = VT.getVectorNumElements();
6425
6426  // Use MOVLPS and MOVLPD in case V1 or V2 are loads. During isel, the second
6427  // operand of these instructions is only memory, so check if there's a
6428  // potencial load folding here, otherwise use SHUFPS or MOVSD to match the
6429  // same masks.
6430  bool CanFoldLoad = false;
6431
6432  // Trivial case, when V2 comes from a load.
6433  if (MayFoldVectorLoad(V2))
6434    CanFoldLoad = true;
6435
6436  // When V1 is a load, it can be folded later into a store in isel, example:
6437  //  (store (v4f32 (X86Movlps (load addr:$src1), VR128:$src2)), addr:$src1)
6438  //    turns into:
6439  //  (MOVLPSmr addr:$src1, VR128:$src2)
6440  // So, recognize this potential and also use MOVLPS or MOVLPD
6441  else if (MayFoldVectorLoad(V1) && MayFoldIntoStore(Op))
6442    CanFoldLoad = true;
6443
6444  ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6445  if (CanFoldLoad) {
6446    if (HasSSE2 && NumElems == 2)
6447      return getTargetShuffleNode(X86ISD::MOVLPD, dl, VT, V1, V2, DAG);
6448
6449    if (NumElems == 4)
6450      // If we don't care about the second element, proceed to use movss.
6451      if (SVOp->getMaskElt(1) != -1)
6452        return getTargetShuffleNode(X86ISD::MOVLPS, dl, VT, V1, V2, DAG);
6453  }
6454
6455  // movl and movlp will both match v2i64, but v2i64 is never matched by
6456  // movl earlier because we make it strict to avoid messing with the movlp load
6457  // folding logic (see the code above getMOVLP call). Match it here then,
6458  // this is horrible, but will stay like this until we move all shuffle
6459  // matching to x86 specific nodes. Note that for the 1st condition all
6460  // types are matched with movsd.
6461  if (HasSSE2) {
6462    // FIXME: isMOVLMask should be checked and matched before getMOVLP,
6463    // as to remove this logic from here, as much as possible
6464    if (NumElems == 2 || !isMOVLMask(SVOp->getMask(), VT))
6465      return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
6466    return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
6467  }
6468
6469  assert(VT != MVT::v4i32 && "unsupported shuffle type");
6470
6471  // Invert the operand order and use SHUFPS to match it.
6472  return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V2, V1,
6473                              getShuffleSHUFImmediate(SVOp), DAG);
6474}
6475
6476SDValue
6477X86TargetLowering::NormalizeVectorShuffle(SDValue Op, SelectionDAG &DAG) const {
6478  ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6479  EVT VT = Op.getValueType();
6480  DebugLoc dl = Op.getDebugLoc();
6481  SDValue V1 = Op.getOperand(0);
6482  SDValue V2 = Op.getOperand(1);
6483
6484  if (isZeroShuffle(SVOp))
6485    return getZeroVector(VT, Subtarget, DAG, dl);
6486
6487  // Handle splat operations
6488  if (SVOp->isSplat()) {
6489    unsigned NumElem = VT.getVectorNumElements();
6490    int Size = VT.getSizeInBits();
6491
6492    // Use vbroadcast whenever the splat comes from a foldable load
6493    SDValue Broadcast = LowerVectorBroadcast(Op, DAG);
6494    if (Broadcast.getNode())
6495      return Broadcast;
6496
6497    // Handle splats by matching through known shuffle masks
6498    if ((Size == 128 && NumElem <= 4) ||
6499        (Size == 256 && NumElem < 8))
6500      return SDValue();
6501
6502    // All remaning splats are promoted to target supported vector shuffles.
6503    return PromoteSplat(SVOp, DAG);
6504  }
6505
6506  // If the shuffle can be profitably rewritten as a narrower shuffle, then
6507  // do it!
6508  if (VT == MVT::v8i16  || VT == MVT::v16i8 ||
6509      VT == MVT::v16i16 || VT == MVT::v32i8) {
6510    SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
6511    if (NewOp.getNode())
6512      return DAG.getNode(ISD::BITCAST, dl, VT, NewOp);
6513  } else if ((VT == MVT::v4i32 ||
6514             (VT == MVT::v4f32 && Subtarget->hasSSE2()))) {
6515    // FIXME: Figure out a cleaner way to do this.
6516    // Try to make use of movq to zero out the top part.
6517    if (ISD::isBuildVectorAllZeros(V2.getNode())) {
6518      SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
6519      if (NewOp.getNode()) {
6520        EVT NewVT = NewOp.getValueType();
6521        if (isCommutedMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(),
6522                               NewVT, true, false))
6523          return getVZextMovL(VT, NewVT, NewOp.getOperand(0),
6524                              DAG, Subtarget, dl);
6525      }
6526    } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
6527      SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
6528      if (NewOp.getNode()) {
6529        EVT NewVT = NewOp.getValueType();
6530        if (isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(), NewVT))
6531          return getVZextMovL(VT, NewVT, NewOp.getOperand(1),
6532                              DAG, Subtarget, dl);
6533      }
6534    }
6535  }
6536  return SDValue();
6537}
6538
6539SDValue
6540X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) const {
6541  ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6542  SDValue V1 = Op.getOperand(0);
6543  SDValue V2 = Op.getOperand(1);
6544  EVT VT = Op.getValueType();
6545  DebugLoc dl = Op.getDebugLoc();
6546  unsigned NumElems = VT.getVectorNumElements();
6547  bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
6548  bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
6549  bool V1IsSplat = false;
6550  bool V2IsSplat = false;
6551  bool HasSSE2 = Subtarget->hasSSE2();
6552  bool HasAVX    = Subtarget->hasAVX();
6553  bool HasAVX2   = Subtarget->hasAVX2();
6554  MachineFunction &MF = DAG.getMachineFunction();
6555  bool OptForSize = MF.getFunction()->hasFnAttr(Attribute::OptimizeForSize);
6556
6557  assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
6558
6559  if (V1IsUndef && V2IsUndef)
6560    return DAG.getUNDEF(VT);
6561
6562  assert(!V1IsUndef && "Op 1 of shuffle should not be undef");
6563
6564  // Vector shuffle lowering takes 3 steps:
6565  //
6566  // 1) Normalize the input vectors. Here splats, zeroed vectors, profitable
6567  //    narrowing and commutation of operands should be handled.
6568  // 2) Matching of shuffles with known shuffle masks to x86 target specific
6569  //    shuffle nodes.
6570  // 3) Rewriting of unmatched masks into new generic shuffle operations,
6571  //    so the shuffle can be broken into other shuffles and the legalizer can
6572  //    try the lowering again.
6573  //
6574  // The general idea is that no vector_shuffle operation should be left to
6575  // be matched during isel, all of them must be converted to a target specific
6576  // node here.
6577
6578  // Normalize the input vectors. Here splats, zeroed vectors, profitable
6579  // narrowing and commutation of operands should be handled. The actual code
6580  // doesn't include all of those, work in progress...
6581  SDValue NewOp = NormalizeVectorShuffle(Op, DAG);
6582  if (NewOp.getNode())
6583    return NewOp;
6584
6585  SmallVector<int, 8> M(SVOp->getMask().begin(), SVOp->getMask().end());
6586
6587  // NOTE: isPSHUFDMask can also match both masks below (unpckl_undef and
6588  // unpckh_undef). Only use pshufd if speed is more important than size.
6589  if (OptForSize && isUNPCKL_v_undef_Mask(M, VT, HasAVX2))
6590    return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
6591  if (OptForSize && isUNPCKH_v_undef_Mask(M, VT, HasAVX2))
6592    return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
6593
6594  if (isMOVDDUPMask(M, VT) && Subtarget->hasSSE3() &&
6595      V2IsUndef && RelaxedMayFoldVectorLoad(V1))
6596    return getMOVDDup(Op, dl, V1, DAG);
6597
6598  if (isMOVHLPS_v_undef_Mask(M, VT))
6599    return getMOVHighToLow(Op, dl, DAG);
6600
6601  // Use to match splats
6602  if (HasSSE2 && isUNPCKHMask(M, VT, HasAVX2) && V2IsUndef &&
6603      (VT == MVT::v2f64 || VT == MVT::v2i64))
6604    return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
6605
6606  if (isPSHUFDMask(M, VT)) {
6607    // The actual implementation will match the mask in the if above and then
6608    // during isel it can match several different instructions, not only pshufd
6609    // as its name says, sad but true, emulate the behavior for now...
6610    if (isMOVDDUPMask(M, VT) && ((VT == MVT::v4f32 || VT == MVT::v2i64)))
6611      return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V1, DAG);
6612
6613    unsigned TargetMask = getShuffleSHUFImmediate(SVOp);
6614
6615    if (HasAVX && (VT == MVT::v4f32 || VT == MVT::v2f64))
6616      return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1, TargetMask, DAG);
6617
6618    if (HasSSE2 && (VT == MVT::v4f32 || VT == MVT::v4i32))
6619      return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1, TargetMask, DAG);
6620
6621    return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V1,
6622                                TargetMask, DAG);
6623  }
6624
6625  // Check if this can be converted into a logical shift.
6626  bool isLeft = false;
6627  unsigned ShAmt = 0;
6628  SDValue ShVal;
6629  bool isShift = HasSSE2 && isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
6630  if (isShift && ShVal.hasOneUse()) {
6631    // If the shifted value has multiple uses, it may be cheaper to use
6632    // v_set0 + movlhps or movhlps, etc.
6633    EVT EltVT = VT.getVectorElementType();
6634    ShAmt *= EltVT.getSizeInBits();
6635    return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
6636  }
6637
6638  if (isMOVLMask(M, VT)) {
6639    if (ISD::isBuildVectorAllZeros(V1.getNode()))
6640      return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
6641    if (!isMOVLPMask(M, VT)) {
6642      if (HasSSE2 && (VT == MVT::v2i64 || VT == MVT::v2f64))
6643        return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
6644
6645      if (VT == MVT::v4i32 || VT == MVT::v4f32)
6646        return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
6647    }
6648  }
6649
6650  // FIXME: fold these into legal mask.
6651  if (isMOVLHPSMask(M, VT) && !isUNPCKLMask(M, VT, HasAVX2))
6652    return getMOVLowToHigh(Op, dl, DAG, HasSSE2);
6653
6654  if (isMOVHLPSMask(M, VT))
6655    return getMOVHighToLow(Op, dl, DAG);
6656
6657  if (V2IsUndef && isMOVSHDUPMask(M, VT, Subtarget))
6658    return getTargetShuffleNode(X86ISD::MOVSHDUP, dl, VT, V1, DAG);
6659
6660  if (V2IsUndef && isMOVSLDUPMask(M, VT, Subtarget))
6661    return getTargetShuffleNode(X86ISD::MOVSLDUP, dl, VT, V1, DAG);
6662
6663  if (isMOVLPMask(M, VT))
6664    return getMOVLP(Op, dl, DAG, HasSSE2);
6665
6666  if (ShouldXformToMOVHLPS(M, VT) ||
6667      ShouldXformToMOVLP(V1.getNode(), V2.getNode(), M, VT))
6668    return CommuteVectorShuffle(SVOp, DAG);
6669
6670  if (isShift) {
6671    // No better options. Use a vshldq / vsrldq.
6672    EVT EltVT = VT.getVectorElementType();
6673    ShAmt *= EltVT.getSizeInBits();
6674    return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
6675  }
6676
6677  bool Commuted = false;
6678  // FIXME: This should also accept a bitcast of a splat?  Be careful, not
6679  // 1,1,1,1 -> v8i16 though.
6680  V1IsSplat = isSplatVector(V1.getNode());
6681  V2IsSplat = isSplatVector(V2.getNode());
6682
6683  // Canonicalize the splat or undef, if present, to be on the RHS.
6684  if (!V2IsUndef && V1IsSplat && !V2IsSplat) {
6685    CommuteVectorShuffleMask(M, NumElems);
6686    std::swap(V1, V2);
6687    std::swap(V1IsSplat, V2IsSplat);
6688    Commuted = true;
6689  }
6690
6691  if (isCommutedMOVLMask(M, VT, V2IsSplat, V2IsUndef)) {
6692    // Shuffling low element of v1 into undef, just return v1.
6693    if (V2IsUndef)
6694      return V1;
6695    // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
6696    // the instruction selector will not match, so get a canonical MOVL with
6697    // swapped operands to undo the commute.
6698    return getMOVL(DAG, dl, VT, V2, V1);
6699  }
6700
6701  if (isUNPCKLMask(M, VT, HasAVX2))
6702    return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
6703
6704  if (isUNPCKHMask(M, VT, HasAVX2))
6705    return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
6706
6707  if (V2IsSplat) {
6708    // Normalize mask so all entries that point to V2 points to its first
6709    // element then try to match unpck{h|l} again. If match, return a
6710    // new vector_shuffle with the corrected mask.p
6711    SmallVector<int, 8> NewMask(M.begin(), M.end());
6712    NormalizeMask(NewMask, NumElems);
6713    if (isUNPCKLMask(NewMask, VT, HasAVX2, true))
6714      return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
6715    if (isUNPCKHMask(NewMask, VT, HasAVX2, true))
6716      return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
6717  }
6718
6719  if (Commuted) {
6720    // Commute is back and try unpck* again.
6721    // FIXME: this seems wrong.
6722    CommuteVectorShuffleMask(M, NumElems);
6723    std::swap(V1, V2);
6724    std::swap(V1IsSplat, V2IsSplat);
6725    Commuted = false;
6726
6727    if (isUNPCKLMask(M, VT, HasAVX2))
6728      return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
6729
6730    if (isUNPCKHMask(M, VT, HasAVX2))
6731      return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
6732  }
6733
6734  // Normalize the node to match x86 shuffle ops if needed
6735  if (!V2IsUndef && (isSHUFPMask(M, VT, HasAVX, /* Commuted */ true)))
6736    return CommuteVectorShuffle(SVOp, DAG);
6737
6738  // The checks below are all present in isShuffleMaskLegal, but they are
6739  // inlined here right now to enable us to directly emit target specific
6740  // nodes, and remove one by one until they don't return Op anymore.
6741
6742  if (isPALIGNRMask(M, VT, Subtarget))
6743    return getTargetShuffleNode(X86ISD::PALIGN, dl, VT, V1, V2,
6744                                getShufflePALIGNRImmediate(SVOp),
6745                                DAG);
6746
6747  if (ShuffleVectorSDNode::isSplatMask(&M[0], VT) &&
6748      SVOp->getSplatIndex() == 0 && V2IsUndef) {
6749    if (VT == MVT::v2f64 || VT == MVT::v2i64)
6750      return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
6751  }
6752
6753  if (isPSHUFHWMask(M, VT, HasAVX2))
6754    return getTargetShuffleNode(X86ISD::PSHUFHW, dl, VT, V1,
6755                                getShufflePSHUFHWImmediate(SVOp),
6756                                DAG);
6757
6758  if (isPSHUFLWMask(M, VT, HasAVX2))
6759    return getTargetShuffleNode(X86ISD::PSHUFLW, dl, VT, V1,
6760                                getShufflePSHUFLWImmediate(SVOp),
6761                                DAG);
6762
6763  if (isSHUFPMask(M, VT, HasAVX))
6764    return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V2,
6765                                getShuffleSHUFImmediate(SVOp), DAG);
6766
6767  if (isUNPCKL_v_undef_Mask(M, VT, HasAVX2))
6768    return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
6769  if (isUNPCKH_v_undef_Mask(M, VT, HasAVX2))
6770    return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
6771
6772  //===--------------------------------------------------------------------===//
6773  // Generate target specific nodes for 128 or 256-bit shuffles only
6774  // supported in the AVX instruction set.
6775  //
6776
6777  // Handle VMOVDDUPY permutations
6778  if (V2IsUndef && isMOVDDUPYMask(M, VT, HasAVX))
6779    return getTargetShuffleNode(X86ISD::MOVDDUP, dl, VT, V1, DAG);
6780
6781  // Handle VPERMILPS/D* permutations
6782  if (isVPERMILPMask(M, VT, HasAVX)) {
6783    if (HasAVX2 && VT == MVT::v8i32)
6784      return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1,
6785                                  getShuffleSHUFImmediate(SVOp), DAG);
6786    return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1,
6787                                getShuffleSHUFImmediate(SVOp), DAG);
6788  }
6789
6790  // Handle VPERM2F128/VPERM2I128 permutations
6791  if (isVPERM2X128Mask(M, VT, HasAVX))
6792    return getTargetShuffleNode(X86ISD::VPERM2X128, dl, VT, V1,
6793                                V2, getShuffleVPERM2X128Immediate(SVOp), DAG);
6794
6795  SDValue BlendOp = LowerVECTOR_SHUFFLEtoBlend(SVOp, Subtarget, DAG);
6796  if (BlendOp.getNode())
6797    return BlendOp;
6798
6799  if (V2IsUndef && HasAVX2 && (VT == MVT::v8i32 || VT == MVT::v8f32)) {
6800    SmallVector<SDValue, 8> permclMask;
6801    for (unsigned i = 0; i != 8; ++i) {
6802      permclMask.push_back(DAG.getConstant((M[i]>=0) ? M[i] : 0, MVT::i32));
6803    }
6804    SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32,
6805                               &permclMask[0], 8);
6806    // Bitcast is for VPERMPS since mask is v8i32 but node takes v8f32
6807    return DAG.getNode(X86ISD::VPERMV, dl, VT,
6808                       DAG.getNode(ISD::BITCAST, dl, VT, Mask), V1);
6809  }
6810
6811  if (V2IsUndef && HasAVX2 && (VT == MVT::v4i64 || VT == MVT::v4f64))
6812    return getTargetShuffleNode(X86ISD::VPERMI, dl, VT, V1,
6813                                getShuffleCLImmediate(SVOp), DAG);
6814
6815
6816  //===--------------------------------------------------------------------===//
6817  // Since no target specific shuffle was selected for this generic one,
6818  // lower it into other known shuffles. FIXME: this isn't true yet, but
6819  // this is the plan.
6820  //
6821
6822  // Handle v8i16 specifically since SSE can do byte extraction and insertion.
6823  if (VT == MVT::v8i16) {
6824    SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(Op, DAG);
6825    if (NewOp.getNode())
6826      return NewOp;
6827  }
6828
6829  if (VT == MVT::v16i8) {
6830    SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, DAG, *this);
6831    if (NewOp.getNode())
6832      return NewOp;
6833  }
6834
6835  // Handle all 128-bit wide vectors with 4 elements, and match them with
6836  // several different shuffle types.
6837  if (NumElems == 4 && VT.is128BitVector())
6838    return LowerVECTOR_SHUFFLE_128v4(SVOp, DAG);
6839
6840  // Handle general 256-bit shuffles
6841  if (VT.is256BitVector())
6842    return LowerVECTOR_SHUFFLE_256(SVOp, DAG);
6843
6844  return SDValue();
6845}
6846
6847SDValue
6848X86TargetLowering::LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op,
6849                                                SelectionDAG &DAG) const {
6850  EVT VT = Op.getValueType();
6851  DebugLoc dl = Op.getDebugLoc();
6852
6853  if (!Op.getOperand(0).getValueType().is128BitVector())
6854    return SDValue();
6855
6856  if (VT.getSizeInBits() == 8) {
6857    SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
6858                                    Op.getOperand(0), Op.getOperand(1));
6859    SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
6860                                    DAG.getValueType(VT));
6861    return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
6862  }
6863
6864  if (VT.getSizeInBits() == 16) {
6865    unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6866    // If Idx is 0, it's cheaper to do a move instead of a pextrw.
6867    if (Idx == 0)
6868      return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
6869                         DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
6870                                     DAG.getNode(ISD::BITCAST, dl,
6871                                                 MVT::v4i32,
6872                                                 Op.getOperand(0)),
6873                                     Op.getOperand(1)));
6874    SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
6875                                    Op.getOperand(0), Op.getOperand(1));
6876    SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
6877                                    DAG.getValueType(VT));
6878    return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
6879  }
6880
6881  if (VT == MVT::f32) {
6882    // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
6883    // the result back to FR32 register. It's only worth matching if the
6884    // result has a single use which is a store or a bitcast to i32.  And in
6885    // the case of a store, it's not worth it if the index is a constant 0,
6886    // because a MOVSSmr can be used instead, which is smaller and faster.
6887    if (!Op.hasOneUse())
6888      return SDValue();
6889    SDNode *User = *Op.getNode()->use_begin();
6890    if ((User->getOpcode() != ISD::STORE ||
6891         (isa<ConstantSDNode>(Op.getOperand(1)) &&
6892          cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
6893        (User->getOpcode() != ISD::BITCAST ||
6894         User->getValueType(0) != MVT::i32))
6895      return SDValue();
6896    SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
6897                                  DAG.getNode(ISD::BITCAST, dl, MVT::v4i32,
6898                                              Op.getOperand(0)),
6899                                              Op.getOperand(1));
6900    return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Extract);
6901  }
6902
6903  if (VT == MVT::i32 || VT == MVT::i64) {
6904    // ExtractPS/pextrq works with constant index.
6905    if (isa<ConstantSDNode>(Op.getOperand(1)))
6906      return Op;
6907  }
6908  return SDValue();
6909}
6910
6911
6912SDValue
6913X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
6914                                           SelectionDAG &DAG) const {
6915  if (!isa<ConstantSDNode>(Op.getOperand(1)))
6916    return SDValue();
6917
6918  SDValue Vec = Op.getOperand(0);
6919  EVT VecVT = Vec.getValueType();
6920
6921  // If this is a 256-bit vector result, first extract the 128-bit vector and
6922  // then extract the element from the 128-bit vector.
6923  if (VecVT.is256BitVector()) {
6924    DebugLoc dl = Op.getNode()->getDebugLoc();
6925    unsigned NumElems = VecVT.getVectorNumElements();
6926    SDValue Idx = Op.getOperand(1);
6927    unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
6928
6929    // Get the 128-bit vector.
6930    Vec = Extract128BitVector(Vec, IdxVal, DAG, dl);
6931
6932    if (IdxVal >= NumElems/2)
6933      IdxVal -= NumElems/2;
6934    return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
6935                       DAG.getConstant(IdxVal, MVT::i32));
6936  }
6937
6938  assert(VecVT.is128BitVector() && "Unexpected vector length");
6939
6940  if (Subtarget->hasSSE41()) {
6941    SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
6942    if (Res.getNode())
6943      return Res;
6944  }
6945
6946  EVT VT = Op.getValueType();
6947  DebugLoc dl = Op.getDebugLoc();
6948  // TODO: handle v16i8.
6949  if (VT.getSizeInBits() == 16) {
6950    SDValue Vec = Op.getOperand(0);
6951    unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6952    if (Idx == 0)
6953      return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
6954                         DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
6955                                     DAG.getNode(ISD::BITCAST, dl,
6956                                                 MVT::v4i32, Vec),
6957                                     Op.getOperand(1)));
6958    // Transform it so it match pextrw which produces a 32-bit result.
6959    EVT EltVT = MVT::i32;
6960    SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
6961                                    Op.getOperand(0), Op.getOperand(1));
6962    SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
6963                                    DAG.getValueType(VT));
6964    return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
6965  }
6966
6967  if (VT.getSizeInBits() == 32) {
6968    unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6969    if (Idx == 0)
6970      return Op;
6971
6972    // SHUFPS the element to the lowest double word, then movss.
6973    int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
6974    EVT VVT = Op.getOperand(0).getValueType();
6975    SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
6976                                       DAG.getUNDEF(VVT), Mask);
6977    return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
6978                       DAG.getIntPtrConstant(0));
6979  }
6980
6981  if (VT.getSizeInBits() == 64) {
6982    // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
6983    // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
6984    //        to match extract_elt for f64.
6985    unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6986    if (Idx == 0)
6987      return Op;
6988
6989    // UNPCKHPD the element to the lowest double word, then movsd.
6990    // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
6991    // to a f64mem, the whole operation is folded into a single MOVHPDmr.
6992    int Mask[2] = { 1, -1 };
6993    EVT VVT = Op.getOperand(0).getValueType();
6994    SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
6995                                       DAG.getUNDEF(VVT), Mask);
6996    return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
6997                       DAG.getIntPtrConstant(0));
6998  }
6999
7000  return SDValue();
7001}
7002
7003SDValue
7004X86TargetLowering::LowerINSERT_VECTOR_ELT_SSE4(SDValue Op,
7005                                               SelectionDAG &DAG) const {
7006  EVT VT = Op.getValueType();
7007  EVT EltVT = VT.getVectorElementType();
7008  DebugLoc dl = Op.getDebugLoc();
7009
7010  SDValue N0 = Op.getOperand(0);
7011  SDValue N1 = Op.getOperand(1);
7012  SDValue N2 = Op.getOperand(2);
7013
7014  if (!VT.is128BitVector())
7015    return SDValue();
7016
7017  if ((EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) &&
7018      isa<ConstantSDNode>(N2)) {
7019    unsigned Opc;
7020    if (VT == MVT::v8i16)
7021      Opc = X86ISD::PINSRW;
7022    else if (VT == MVT::v16i8)
7023      Opc = X86ISD::PINSRB;
7024    else
7025      Opc = X86ISD::PINSRB;
7026
7027    // Transform it so it match pinsr{b,w} which expects a GR32 as its second
7028    // argument.
7029    if (N1.getValueType() != MVT::i32)
7030      N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
7031    if (N2.getValueType() != MVT::i32)
7032      N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
7033    return DAG.getNode(Opc, dl, VT, N0, N1, N2);
7034  }
7035
7036  if (EltVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
7037    // Bits [7:6] of the constant are the source select.  This will always be
7038    //  zero here.  The DAG Combiner may combine an extract_elt index into these
7039    //  bits.  For example (insert (extract, 3), 2) could be matched by putting
7040    //  the '3' into bits [7:6] of X86ISD::INSERTPS.
7041    // Bits [5:4] of the constant are the destination select.  This is the
7042    //  value of the incoming immediate.
7043    // Bits [3:0] of the constant are the zero mask.  The DAG Combiner may
7044    //   combine either bitwise AND or insert of float 0.0 to set these bits.
7045    N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
7046    // Create this as a scalar to vector..
7047    N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
7048    return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
7049  }
7050
7051  if ((EltVT == MVT::i32 || EltVT == MVT::i64) && isa<ConstantSDNode>(N2)) {
7052    // PINSR* works with constant index.
7053    return Op;
7054  }
7055  return SDValue();
7056}
7057
7058SDValue
7059X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) const {
7060  EVT VT = Op.getValueType();
7061  EVT EltVT = VT.getVectorElementType();
7062
7063  DebugLoc dl = Op.getDebugLoc();
7064  SDValue N0 = Op.getOperand(0);
7065  SDValue N1 = Op.getOperand(1);
7066  SDValue N2 = Op.getOperand(2);
7067
7068  // If this is a 256-bit vector result, first extract the 128-bit vector,
7069  // insert the element into the extracted half and then place it back.
7070  if (VT.is256BitVector()) {
7071    if (!isa<ConstantSDNode>(N2))
7072      return SDValue();
7073
7074    // Get the desired 128-bit vector half.
7075    unsigned NumElems = VT.getVectorNumElements();
7076    unsigned IdxVal = cast<ConstantSDNode>(N2)->getZExtValue();
7077    SDValue V = Extract128BitVector(N0, IdxVal, DAG, dl);
7078
7079    // Insert the element into the desired half.
7080    bool Upper = IdxVal >= NumElems/2;
7081    V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V, N1,
7082                 DAG.getConstant(Upper ? IdxVal-NumElems/2 : IdxVal, MVT::i32));
7083
7084    // Insert the changed part back to the 256-bit vector
7085    return Insert128BitVector(N0, V, IdxVal, DAG, dl);
7086  }
7087
7088  if (Subtarget->hasSSE41())
7089    return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
7090
7091  if (EltVT == MVT::i8)
7092    return SDValue();
7093
7094  if (EltVT.getSizeInBits() == 16 && isa<ConstantSDNode>(N2)) {
7095    // Transform it so it match pinsrw which expects a 16-bit value in a GR32
7096    // as its second argument.
7097    if (N1.getValueType() != MVT::i32)
7098      N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
7099    if (N2.getValueType() != MVT::i32)
7100      N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
7101    return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
7102  }
7103  return SDValue();
7104}
7105
7106SDValue
7107X86TargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) const {
7108  LLVMContext *Context = DAG.getContext();
7109  DebugLoc dl = Op.getDebugLoc();
7110  EVT OpVT = Op.getValueType();
7111
7112  // If this is a 256-bit vector result, first insert into a 128-bit
7113  // vector and then insert into the 256-bit vector.
7114  if (!OpVT.is128BitVector()) {
7115    // Insert into a 128-bit vector.
7116    EVT VT128 = EVT::getVectorVT(*Context,
7117                                 OpVT.getVectorElementType(),
7118                                 OpVT.getVectorNumElements() / 2);
7119
7120    Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
7121
7122    // Insert the 128-bit vector.
7123    return Insert128BitVector(DAG.getUNDEF(OpVT), Op, 0, DAG, dl);
7124  }
7125
7126  if (OpVT == MVT::v1i64 &&
7127      Op.getOperand(0).getValueType() == MVT::i64)
7128    return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
7129
7130  SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
7131  assert(OpVT.is128BitVector() && "Expected an SSE type!");
7132  return DAG.getNode(ISD::BITCAST, dl, OpVT,
7133                     DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,AnyExt));
7134}
7135
7136// Lower a node with an EXTRACT_SUBVECTOR opcode.  This may result in
7137// a simple subregister reference or explicit instructions to grab
7138// upper bits of a vector.
7139SDValue
7140X86TargetLowering::LowerEXTRACT_SUBVECTOR(SDValue Op, SelectionDAG &DAG) const {
7141  if (Subtarget->hasAVX()) {
7142    DebugLoc dl = Op.getNode()->getDebugLoc();
7143    SDValue Vec = Op.getNode()->getOperand(0);
7144    SDValue Idx = Op.getNode()->getOperand(1);
7145
7146    if (Op.getNode()->getValueType(0).is128BitVector() &&
7147        Vec.getNode()->getValueType(0).is256BitVector() &&
7148        isa<ConstantSDNode>(Idx)) {
7149      unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
7150      return Extract128BitVector(Vec, IdxVal, DAG, dl);
7151    }
7152  }
7153  return SDValue();
7154}
7155
7156// Lower a node with an INSERT_SUBVECTOR opcode.  This may result in a
7157// simple superregister reference or explicit instructions to insert
7158// the upper bits of a vector.
7159SDValue
7160X86TargetLowering::LowerINSERT_SUBVECTOR(SDValue Op, SelectionDAG &DAG) const {
7161  if (Subtarget->hasAVX()) {
7162    DebugLoc dl = Op.getNode()->getDebugLoc();
7163    SDValue Vec = Op.getNode()->getOperand(0);
7164    SDValue SubVec = Op.getNode()->getOperand(1);
7165    SDValue Idx = Op.getNode()->getOperand(2);
7166
7167    if (Op.getNode()->getValueType(0).is256BitVector() &&
7168        SubVec.getNode()->getValueType(0).is128BitVector() &&
7169        isa<ConstantSDNode>(Idx)) {
7170      unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
7171      return Insert128BitVector(Vec, SubVec, IdxVal, DAG, dl);
7172    }
7173  }
7174  return SDValue();
7175}
7176
7177// ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
7178// their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
7179// one of the above mentioned nodes. It has to be wrapped because otherwise
7180// Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
7181// be used to form addressing mode. These wrapped nodes will be selected
7182// into MOV32ri.
7183SDValue
7184X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
7185  ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
7186
7187  // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7188  // global base reg.
7189  unsigned char OpFlag = 0;
7190  unsigned WrapperKind = X86ISD::Wrapper;
7191  CodeModel::Model M = getTargetMachine().getCodeModel();
7192
7193  if (Subtarget->isPICStyleRIPRel() &&
7194      (M == CodeModel::Small || M == CodeModel::Kernel))
7195    WrapperKind = X86ISD::WrapperRIP;
7196  else if (Subtarget->isPICStyleGOT())
7197    OpFlag = X86II::MO_GOTOFF;
7198  else if (Subtarget->isPICStyleStubPIC())
7199    OpFlag = X86II::MO_PIC_BASE_OFFSET;
7200
7201  SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
7202                                             CP->getAlignment(),
7203                                             CP->getOffset(), OpFlag);
7204  DebugLoc DL = CP->getDebugLoc();
7205  Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7206  // With PIC, the address is actually $g + Offset.
7207  if (OpFlag) {
7208    Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7209                         DAG.getNode(X86ISD::GlobalBaseReg,
7210                                     DebugLoc(), getPointerTy()),
7211                         Result);
7212  }
7213
7214  return Result;
7215}
7216
7217SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
7218  JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
7219
7220  // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7221  // global base reg.
7222  unsigned char OpFlag = 0;
7223  unsigned WrapperKind = X86ISD::Wrapper;
7224  CodeModel::Model M = getTargetMachine().getCodeModel();
7225
7226  if (Subtarget->isPICStyleRIPRel() &&
7227      (M == CodeModel::Small || M == CodeModel::Kernel))
7228    WrapperKind = X86ISD::WrapperRIP;
7229  else if (Subtarget->isPICStyleGOT())
7230    OpFlag = X86II::MO_GOTOFF;
7231  else if (Subtarget->isPICStyleStubPIC())
7232    OpFlag = X86II::MO_PIC_BASE_OFFSET;
7233
7234  SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
7235                                          OpFlag);
7236  DebugLoc DL = JT->getDebugLoc();
7237  Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7238
7239  // With PIC, the address is actually $g + Offset.
7240  if (OpFlag)
7241    Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7242                         DAG.getNode(X86ISD::GlobalBaseReg,
7243                                     DebugLoc(), getPointerTy()),
7244                         Result);
7245
7246  return Result;
7247}
7248
7249SDValue
7250X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
7251  const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
7252
7253  // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7254  // global base reg.
7255  unsigned char OpFlag = 0;
7256  unsigned WrapperKind = X86ISD::Wrapper;
7257  CodeModel::Model M = getTargetMachine().getCodeModel();
7258
7259  if (Subtarget->isPICStyleRIPRel() &&
7260      (M == CodeModel::Small || M == CodeModel::Kernel)) {
7261    if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
7262      OpFlag = X86II::MO_GOTPCREL;
7263    WrapperKind = X86ISD::WrapperRIP;
7264  } else if (Subtarget->isPICStyleGOT()) {
7265    OpFlag = X86II::MO_GOT;
7266  } else if (Subtarget->isPICStyleStubPIC()) {
7267    OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
7268  } else if (Subtarget->isPICStyleStubNoDynamic()) {
7269    OpFlag = X86II::MO_DARWIN_NONLAZY;
7270  }
7271
7272  SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
7273
7274  DebugLoc DL = Op.getDebugLoc();
7275  Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7276
7277
7278  // With PIC, the address is actually $g + Offset.
7279  if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
7280      !Subtarget->is64Bit()) {
7281    Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7282                         DAG.getNode(X86ISD::GlobalBaseReg,
7283                                     DebugLoc(), getPointerTy()),
7284                         Result);
7285  }
7286
7287  // For symbols that require a load from a stub to get the address, emit the
7288  // load.
7289  if (isGlobalStubReference(OpFlag))
7290    Result = DAG.getLoad(getPointerTy(), DL, DAG.getEntryNode(), Result,
7291                         MachinePointerInfo::getGOT(), false, false, false, 0);
7292
7293  return Result;
7294}
7295
7296SDValue
7297X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
7298  // Create the TargetBlockAddressAddress node.
7299  unsigned char OpFlags =
7300    Subtarget->ClassifyBlockAddressReference();
7301  CodeModel::Model M = getTargetMachine().getCodeModel();
7302  const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
7303  DebugLoc dl = Op.getDebugLoc();
7304  SDValue Result = DAG.getBlockAddress(BA, getPointerTy(),
7305                                       /*isTarget=*/true, OpFlags);
7306
7307  if (Subtarget->isPICStyleRIPRel() &&
7308      (M == CodeModel::Small || M == CodeModel::Kernel))
7309    Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
7310  else
7311    Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
7312
7313  // With PIC, the address is actually $g + Offset.
7314  if (isGlobalRelativeToPICBase(OpFlags)) {
7315    Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
7316                         DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
7317                         Result);
7318  }
7319
7320  return Result;
7321}
7322
7323SDValue
7324X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, DebugLoc dl,
7325                                      int64_t Offset,
7326                                      SelectionDAG &DAG) const {
7327  // Create the TargetGlobalAddress node, folding in the constant
7328  // offset if it is legal.
7329  unsigned char OpFlags =
7330    Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
7331  CodeModel::Model M = getTargetMachine().getCodeModel();
7332  SDValue Result;
7333  if (OpFlags == X86II::MO_NO_FLAG &&
7334      X86::isOffsetSuitableForCodeModel(Offset, M)) {
7335    // A direct static reference to a global.
7336    Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
7337    Offset = 0;
7338  } else {
7339    Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
7340  }
7341
7342  if (Subtarget->isPICStyleRIPRel() &&
7343      (M == CodeModel::Small || M == CodeModel::Kernel))
7344    Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
7345  else
7346    Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
7347
7348  // With PIC, the address is actually $g + Offset.
7349  if (isGlobalRelativeToPICBase(OpFlags)) {
7350    Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
7351                         DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
7352                         Result);
7353  }
7354
7355  // For globals that require a load from a stub to get the address, emit the
7356  // load.
7357  if (isGlobalStubReference(OpFlags))
7358    Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
7359                         MachinePointerInfo::getGOT(), false, false, false, 0);
7360
7361  // If there was a non-zero offset that we didn't fold, create an explicit
7362  // addition for it.
7363  if (Offset != 0)
7364    Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
7365                         DAG.getConstant(Offset, getPointerTy()));
7366
7367  return Result;
7368}
7369
7370SDValue
7371X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
7372  const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
7373  int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
7374  return LowerGlobalAddress(GV, Op.getDebugLoc(), Offset, DAG);
7375}
7376
7377static SDValue
7378GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
7379           SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
7380           unsigned char OperandFlags, bool LocalDynamic = false) {
7381  MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7382  SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7383  DebugLoc dl = GA->getDebugLoc();
7384  SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7385                                           GA->getValueType(0),
7386                                           GA->getOffset(),
7387                                           OperandFlags);
7388
7389  X86ISD::NodeType CallType = LocalDynamic ? X86ISD::TLSBASEADDR
7390                                           : X86ISD::TLSADDR;
7391
7392  if (InFlag) {
7393    SDValue Ops[] = { Chain,  TGA, *InFlag };
7394    Chain = DAG.getNode(CallType, dl, NodeTys, Ops, 3);
7395  } else {
7396    SDValue Ops[]  = { Chain, TGA };
7397    Chain = DAG.getNode(CallType, dl, NodeTys, Ops, 2);
7398  }
7399
7400  // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
7401  MFI->setAdjustsStack(true);
7402
7403  SDValue Flag = Chain.getValue(1);
7404  return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
7405}
7406
7407// Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
7408static SDValue
7409LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7410                                const EVT PtrVT) {
7411  SDValue InFlag;
7412  DebugLoc dl = GA->getDebugLoc();  // ? function entry point might be better
7413  SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
7414                                     DAG.getNode(X86ISD::GlobalBaseReg,
7415                                                 DebugLoc(), PtrVT), InFlag);
7416  InFlag = Chain.getValue(1);
7417
7418  return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
7419}
7420
7421// Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
7422static SDValue
7423LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7424                                const EVT PtrVT) {
7425  return GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT,
7426                    X86::RAX, X86II::MO_TLSGD);
7427}
7428
7429static SDValue LowerToTLSLocalDynamicModel(GlobalAddressSDNode *GA,
7430                                           SelectionDAG &DAG,
7431                                           const EVT PtrVT,
7432                                           bool is64Bit) {
7433  DebugLoc dl = GA->getDebugLoc();
7434
7435  // Get the start address of the TLS block for this module.
7436  X86MachineFunctionInfo* MFI = DAG.getMachineFunction()
7437      .getInfo<X86MachineFunctionInfo>();
7438  MFI->incNumLocalDynamicTLSAccesses();
7439
7440  SDValue Base;
7441  if (is64Bit) {
7442    Base = GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT, X86::RAX,
7443                      X86II::MO_TLSLD, /*LocalDynamic=*/true);
7444  } else {
7445    SDValue InFlag;
7446    SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
7447        DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), PtrVT), InFlag);
7448    InFlag = Chain.getValue(1);
7449    Base = GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX,
7450                      X86II::MO_TLSLDM, /*LocalDynamic=*/true);
7451  }
7452
7453  // Note: the CleanupLocalDynamicTLSPass will remove redundant computations
7454  // of Base.
7455
7456  // Build x@dtpoff.
7457  unsigned char OperandFlags = X86II::MO_DTPOFF;
7458  unsigned WrapperKind = X86ISD::Wrapper;
7459  SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7460                                           GA->getValueType(0),
7461                                           GA->getOffset(), OperandFlags);
7462  SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
7463
7464  // Add x@dtpoff with the base.
7465  return DAG.getNode(ISD::ADD, dl, PtrVT, Offset, Base);
7466}
7467
7468// Lower ISD::GlobalTLSAddress using the "initial exec" or "local exec" model.
7469static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7470                                   const EVT PtrVT, TLSModel::Model model,
7471                                   bool is64Bit, bool isPIC) {
7472  DebugLoc dl = GA->getDebugLoc();
7473
7474  // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
7475  Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
7476                                                         is64Bit ? 257 : 256));
7477
7478  SDValue ThreadPointer = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
7479                                      DAG.getIntPtrConstant(0),
7480                                      MachinePointerInfo(Ptr),
7481                                      false, false, false, 0);
7482
7483  unsigned char OperandFlags = 0;
7484  // Most TLS accesses are not RIP relative, even on x86-64.  One exception is
7485  // initialexec.
7486  unsigned WrapperKind = X86ISD::Wrapper;
7487  if (model == TLSModel::LocalExec) {
7488    OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
7489  } else if (model == TLSModel::InitialExec) {
7490    if (is64Bit) {
7491      OperandFlags = X86II::MO_GOTTPOFF;
7492      WrapperKind = X86ISD::WrapperRIP;
7493    } else {
7494      OperandFlags = isPIC ? X86II::MO_GOTNTPOFF : X86II::MO_INDNTPOFF;
7495    }
7496  } else {
7497    llvm_unreachable("Unexpected model");
7498  }
7499
7500  // emit "addl x@ntpoff,%eax" (local exec)
7501  // or "addl x@indntpoff,%eax" (initial exec)
7502  // or "addl x@gotntpoff(%ebx) ,%eax" (initial exec, 32-bit pic)
7503  SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7504                                           GA->getValueType(0),
7505                                           GA->getOffset(), OperandFlags);
7506  SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
7507
7508  if (model == TLSModel::InitialExec) {
7509    if (isPIC && !is64Bit) {
7510      Offset = DAG.getNode(ISD::ADD, dl, PtrVT,
7511                          DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), PtrVT),
7512                           Offset);
7513    }
7514
7515    Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
7516                         MachinePointerInfo::getGOT(), false, false, false,
7517                         0);
7518  }
7519
7520  // The address of the thread local variable is the add of the thread
7521  // pointer with the offset of the variable.
7522  return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
7523}
7524
7525SDValue
7526X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
7527
7528  GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
7529  const GlobalValue *GV = GA->getGlobal();
7530
7531  if (Subtarget->isTargetELF()) {
7532    TLSModel::Model model = getTargetMachine().getTLSModel(GV);
7533
7534    switch (model) {
7535      case TLSModel::GeneralDynamic:
7536        if (Subtarget->is64Bit())
7537          return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
7538        return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
7539      case TLSModel::LocalDynamic:
7540        return LowerToTLSLocalDynamicModel(GA, DAG, getPointerTy(),
7541                                           Subtarget->is64Bit());
7542      case TLSModel::InitialExec:
7543      case TLSModel::LocalExec:
7544        return LowerToTLSExecModel(GA, DAG, getPointerTy(), model,
7545                                   Subtarget->is64Bit(),
7546                         getTargetMachine().getRelocationModel() == Reloc::PIC_);
7547    }
7548    llvm_unreachable("Unknown TLS model.");
7549  }
7550
7551  if (Subtarget->isTargetDarwin()) {
7552    // Darwin only has one model of TLS.  Lower to that.
7553    unsigned char OpFlag = 0;
7554    unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
7555                           X86ISD::WrapperRIP : X86ISD::Wrapper;
7556
7557    // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7558    // global base reg.
7559    bool PIC32 = (getTargetMachine().getRelocationModel() == Reloc::PIC_) &&
7560                  !Subtarget->is64Bit();
7561    if (PIC32)
7562      OpFlag = X86II::MO_TLVP_PIC_BASE;
7563    else
7564      OpFlag = X86II::MO_TLVP;
7565    DebugLoc DL = Op.getDebugLoc();
7566    SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
7567                                                GA->getValueType(0),
7568                                                GA->getOffset(), OpFlag);
7569    SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7570
7571    // With PIC32, the address is actually $g + Offset.
7572    if (PIC32)
7573      Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7574                           DAG.getNode(X86ISD::GlobalBaseReg,
7575                                       DebugLoc(), getPointerTy()),
7576                           Offset);
7577
7578    // Lowering the machine isd will make sure everything is in the right
7579    // location.
7580    SDValue Chain = DAG.getEntryNode();
7581    SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7582    SDValue Args[] = { Chain, Offset };
7583    Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args, 2);
7584
7585    // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
7586    MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7587    MFI->setAdjustsStack(true);
7588
7589    // And our return value (tls address) is in the standard call return value
7590    // location.
7591    unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
7592    return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy(),
7593                              Chain.getValue(1));
7594  }
7595
7596  if (Subtarget->isTargetWindows()) {
7597    // Just use the implicit TLS architecture
7598    // Need to generate someting similar to:
7599    //   mov     rdx, qword [gs:abs 58H]; Load pointer to ThreadLocalStorage
7600    //                                  ; from TEB
7601    //   mov     ecx, dword [rel _tls_index]: Load index (from C runtime)
7602    //   mov     rcx, qword [rdx+rcx*8]
7603    //   mov     eax, .tls$:tlsvar
7604    //   [rax+rcx] contains the address
7605    // Windows 64bit: gs:0x58
7606    // Windows 32bit: fs:__tls_array
7607
7608    // If GV is an alias then use the aliasee for determining
7609    // thread-localness.
7610    if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
7611      GV = GA->resolveAliasedGlobal(false);
7612    DebugLoc dl = GA->getDebugLoc();
7613    SDValue Chain = DAG.getEntryNode();
7614
7615    // Get the Thread Pointer, which is %fs:__tls_array (32-bit) or
7616    // %gs:0x58 (64-bit).
7617    Value *Ptr = Constant::getNullValue(Subtarget->is64Bit()
7618                                        ? Type::getInt8PtrTy(*DAG.getContext(),
7619                                                             256)
7620                                        : Type::getInt32PtrTy(*DAG.getContext(),
7621                                                              257));
7622
7623    SDValue ThreadPointer = DAG.getLoad(getPointerTy(), dl, Chain,
7624                                        Subtarget->is64Bit()
7625                                        ? DAG.getIntPtrConstant(0x58)
7626                                        : DAG.getExternalSymbol("_tls_array",
7627                                                                getPointerTy()),
7628                                        MachinePointerInfo(Ptr),
7629                                        false, false, false, 0);
7630
7631    // Load the _tls_index variable
7632    SDValue IDX = DAG.getExternalSymbol("_tls_index", getPointerTy());
7633    if (Subtarget->is64Bit())
7634      IDX = DAG.getExtLoad(ISD::ZEXTLOAD, dl, getPointerTy(), Chain,
7635                           IDX, MachinePointerInfo(), MVT::i32,
7636                           false, false, 0);
7637    else
7638      IDX = DAG.getLoad(getPointerTy(), dl, Chain, IDX, MachinePointerInfo(),
7639                        false, false, false, 0);
7640
7641    SDValue Scale = DAG.getConstant(Log2_64_Ceil(TD->getPointerSize()),
7642                                    getPointerTy());
7643    IDX = DAG.getNode(ISD::SHL, dl, getPointerTy(), IDX, Scale);
7644
7645    SDValue res = DAG.getNode(ISD::ADD, dl, getPointerTy(), ThreadPointer, IDX);
7646    res = DAG.getLoad(getPointerTy(), dl, Chain, res, MachinePointerInfo(),
7647                      false, false, false, 0);
7648
7649    // Get the offset of start of .tls section
7650    SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7651                                             GA->getValueType(0),
7652                                             GA->getOffset(), X86II::MO_SECREL);
7653    SDValue Offset = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), TGA);
7654
7655    // The address of the thread local variable is the add of the thread
7656    // pointer with the offset of the variable.
7657    return DAG.getNode(ISD::ADD, dl, getPointerTy(), res, Offset);
7658  }
7659
7660  llvm_unreachable("TLS not implemented for this target.");
7661}
7662
7663
7664/// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values
7665/// and take a 2 x i32 value to shift plus a shift amount.
7666SDValue X86TargetLowering::LowerShiftParts(SDValue Op, SelectionDAG &DAG) const{
7667  assert(Op.getNumOperands() == 3 && "Not a double-shift!");
7668  EVT VT = Op.getValueType();
7669  unsigned VTBits = VT.getSizeInBits();
7670  DebugLoc dl = Op.getDebugLoc();
7671  bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
7672  SDValue ShOpLo = Op.getOperand(0);
7673  SDValue ShOpHi = Op.getOperand(1);
7674  SDValue ShAmt  = Op.getOperand(2);
7675  SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
7676                                     DAG.getConstant(VTBits - 1, MVT::i8))
7677                       : DAG.getConstant(0, VT);
7678
7679  SDValue Tmp2, Tmp3;
7680  if (Op.getOpcode() == ISD::SHL_PARTS) {
7681    Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
7682    Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
7683  } else {
7684    Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
7685    Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, ShAmt);
7686  }
7687
7688  SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
7689                                DAG.getConstant(VTBits, MVT::i8));
7690  SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
7691                             AndNode, DAG.getConstant(0, MVT::i8));
7692
7693  SDValue Hi, Lo;
7694  SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
7695  SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
7696  SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
7697
7698  if (Op.getOpcode() == ISD::SHL_PARTS) {
7699    Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
7700    Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
7701  } else {
7702    Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
7703    Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
7704  }
7705
7706  SDValue Ops[2] = { Lo, Hi };
7707  return DAG.getMergeValues(Ops, 2, dl);
7708}
7709
7710SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
7711                                           SelectionDAG &DAG) const {
7712  EVT SrcVT = Op.getOperand(0).getValueType();
7713
7714  if (SrcVT.isVector())
7715    return SDValue();
7716
7717  assert(SrcVT.getSimpleVT() <= MVT::i64 && SrcVT.getSimpleVT() >= MVT::i16 &&
7718         "Unknown SINT_TO_FP to lower!");
7719
7720  // These are really Legal; return the operand so the caller accepts it as
7721  // Legal.
7722  if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
7723    return Op;
7724  if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
7725      Subtarget->is64Bit()) {
7726    return Op;
7727  }
7728
7729  DebugLoc dl = Op.getDebugLoc();
7730  unsigned Size = SrcVT.getSizeInBits()/8;
7731  MachineFunction &MF = DAG.getMachineFunction();
7732  int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
7733  SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7734  SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
7735                               StackSlot,
7736                               MachinePointerInfo::getFixedStack(SSFI),
7737                               false, false, 0);
7738  return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
7739}
7740
7741SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
7742                                     SDValue StackSlot,
7743                                     SelectionDAG &DAG) const {
7744  // Build the FILD
7745  DebugLoc DL = Op.getDebugLoc();
7746  SDVTList Tys;
7747  bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
7748  if (useSSE)
7749    Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
7750  else
7751    Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
7752
7753  unsigned ByteSize = SrcVT.getSizeInBits()/8;
7754
7755  FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
7756  MachineMemOperand *MMO;
7757  if (FI) {
7758    int SSFI = FI->getIndex();
7759    MMO =
7760      DAG.getMachineFunction()
7761      .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7762                            MachineMemOperand::MOLoad, ByteSize, ByteSize);
7763  } else {
7764    MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
7765    StackSlot = StackSlot.getOperand(1);
7766  }
7767  SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
7768  SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
7769                                           X86ISD::FILD, DL,
7770                                           Tys, Ops, array_lengthof(Ops),
7771                                           SrcVT, MMO);
7772
7773  if (useSSE) {
7774    Chain = Result.getValue(1);
7775    SDValue InFlag = Result.getValue(2);
7776
7777    // FIXME: Currently the FST is flagged to the FILD_FLAG. This
7778    // shouldn't be necessary except that RFP cannot be live across
7779    // multiple blocks. When stackifier is fixed, they can be uncoupled.
7780    MachineFunction &MF = DAG.getMachineFunction();
7781    unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
7782    int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
7783    SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7784    Tys = DAG.getVTList(MVT::Other);
7785    SDValue Ops[] = {
7786      Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
7787    };
7788    MachineMemOperand *MMO =
7789      DAG.getMachineFunction()
7790      .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7791                            MachineMemOperand::MOStore, SSFISize, SSFISize);
7792
7793    Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
7794                                    Ops, array_lengthof(Ops),
7795                                    Op.getValueType(), MMO);
7796    Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
7797                         MachinePointerInfo::getFixedStack(SSFI),
7798                         false, false, false, 0);
7799  }
7800
7801  return Result;
7802}
7803
7804// LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
7805SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
7806                                               SelectionDAG &DAG) const {
7807  // This algorithm is not obvious. Here it is what we're trying to output:
7808  /*
7809     movq       %rax,  %xmm0
7810     punpckldq  (c0),  %xmm0  // c0: (uint4){ 0x43300000U, 0x45300000U, 0U, 0U }
7811     subpd      (c1),  %xmm0  // c1: (double2){ 0x1.0p52, 0x1.0p52 * 0x1.0p32 }
7812     #ifdef __SSE3__
7813       haddpd   %xmm0, %xmm0
7814     #else
7815       pshufd   $0x4e, %xmm0, %xmm1
7816       addpd    %xmm1, %xmm0
7817     #endif
7818  */
7819
7820  DebugLoc dl = Op.getDebugLoc();
7821  LLVMContext *Context = DAG.getContext();
7822
7823  // Build some magic constants.
7824  const uint32_t CV0[] = { 0x43300000, 0x45300000, 0, 0 };
7825  Constant *C0 = ConstantDataVector::get(*Context, CV0);
7826  SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
7827
7828  SmallVector<Constant*,2> CV1;
7829  CV1.push_back(
7830        ConstantFP::get(*Context, APFloat(APInt(64, 0x4330000000000000ULL))));
7831  CV1.push_back(
7832        ConstantFP::get(*Context, APFloat(APInt(64, 0x4530000000000000ULL))));
7833  Constant *C1 = ConstantVector::get(CV1);
7834  SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
7835
7836  // Load the 64-bit value into an XMM register.
7837  SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
7838                            Op.getOperand(0));
7839  SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
7840                              MachinePointerInfo::getConstantPool(),
7841                              false, false, false, 16);
7842  SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32,
7843                              DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, XR1),
7844                              CLod0);
7845
7846  SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
7847                              MachinePointerInfo::getConstantPool(),
7848                              false, false, false, 16);
7849  SDValue XR2F = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Unpck1);
7850  SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
7851  SDValue Result;
7852
7853  if (Subtarget->hasSSE3()) {
7854    // FIXME: The 'haddpd' instruction may be slower than 'movhlps + addsd'.
7855    Result = DAG.getNode(X86ISD::FHADD, dl, MVT::v2f64, Sub, Sub);
7856  } else {
7857    SDValue S2F = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Sub);
7858    SDValue Shuffle = getTargetShuffleNode(X86ISD::PSHUFD, dl, MVT::v4i32,
7859                                           S2F, 0x4E, DAG);
7860    Result = DAG.getNode(ISD::FADD, dl, MVT::v2f64,
7861                         DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Shuffle),
7862                         Sub);
7863  }
7864
7865  return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Result,
7866                     DAG.getIntPtrConstant(0));
7867}
7868
7869// LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
7870SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
7871                                               SelectionDAG &DAG) const {
7872  DebugLoc dl = Op.getDebugLoc();
7873  // FP constant to bias correct the final result.
7874  SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
7875                                   MVT::f64);
7876
7877  // Load the 32-bit value into an XMM register.
7878  SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
7879                             Op.getOperand(0));
7880
7881  // Zero out the upper parts of the register.
7882  Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget, DAG);
7883
7884  Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
7885                     DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Load),
7886                     DAG.getIntPtrConstant(0));
7887
7888  // Or the load with the bias.
7889  SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
7890                           DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
7891                                       DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
7892                                                   MVT::v2f64, Load)),
7893                           DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
7894                                       DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
7895                                                   MVT::v2f64, Bias)));
7896  Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
7897                   DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or),
7898                   DAG.getIntPtrConstant(0));
7899
7900  // Subtract the bias.
7901  SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
7902
7903  // Handle final rounding.
7904  EVT DestVT = Op.getValueType();
7905
7906  if (DestVT.bitsLT(MVT::f64))
7907    return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
7908                       DAG.getIntPtrConstant(0));
7909  if (DestVT.bitsGT(MVT::f64))
7910    return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
7911
7912  // Handle final rounding.
7913  return Sub;
7914}
7915
7916SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
7917                                           SelectionDAG &DAG) const {
7918  SDValue N0 = Op.getOperand(0);
7919  DebugLoc dl = Op.getDebugLoc();
7920
7921  // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
7922  // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
7923  // the optimization here.
7924  if (DAG.SignBitIsZero(N0))
7925    return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
7926
7927  EVT SrcVT = N0.getValueType();
7928  EVT DstVT = Op.getValueType();
7929  if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
7930    return LowerUINT_TO_FP_i64(Op, DAG);
7931  if (SrcVT == MVT::i32 && X86ScalarSSEf64)
7932    return LowerUINT_TO_FP_i32(Op, DAG);
7933  if (Subtarget->is64Bit() && SrcVT == MVT::i64 && DstVT == MVT::f32)
7934    return SDValue();
7935
7936  // Make a 64-bit buffer, and use it to build an FILD.
7937  SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
7938  if (SrcVT == MVT::i32) {
7939    SDValue WordOff = DAG.getConstant(4, getPointerTy());
7940    SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
7941                                     getPointerTy(), StackSlot, WordOff);
7942    SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
7943                                  StackSlot, MachinePointerInfo(),
7944                                  false, false, 0);
7945    SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
7946                                  OffsetSlot, MachinePointerInfo(),
7947                                  false, false, 0);
7948    SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
7949    return Fild;
7950  }
7951
7952  assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
7953  SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
7954                               StackSlot, MachinePointerInfo(),
7955                               false, false, 0);
7956  // For i64 source, we need to add the appropriate power of 2 if the input
7957  // was negative.  This is the same as the optimization in
7958  // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
7959  // we must be careful to do the computation in x87 extended precision, not
7960  // in SSE. (The generic code can't know it's OK to do this, or how to.)
7961  int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
7962  MachineMemOperand *MMO =
7963    DAG.getMachineFunction()
7964    .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7965                          MachineMemOperand::MOLoad, 8, 8);
7966
7967  SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
7968  SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
7969  SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops, 3,
7970                                         MVT::i64, MMO);
7971
7972  APInt FF(32, 0x5F800000ULL);
7973
7974  // Check whether the sign bit is set.
7975  SDValue SignSet = DAG.getSetCC(dl, getSetCCResultType(MVT::i64),
7976                                 Op.getOperand(0), DAG.getConstant(0, MVT::i64),
7977                                 ISD::SETLT);
7978
7979  // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
7980  SDValue FudgePtr = DAG.getConstantPool(
7981                             ConstantInt::get(*DAG.getContext(), FF.zext(64)),
7982                                         getPointerTy());
7983
7984  // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
7985  SDValue Zero = DAG.getIntPtrConstant(0);
7986  SDValue Four = DAG.getIntPtrConstant(4);
7987  SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
7988                               Zero, Four);
7989  FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
7990
7991  // Load the value out, extending it from f32 to f80.
7992  // FIXME: Avoid the extend by constructing the right constant pool?
7993  SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(),
7994                                 FudgePtr, MachinePointerInfo::getConstantPool(),
7995                                 MVT::f32, false, false, 4);
7996  // Extend everything to 80 bits to force it to be done on x87.
7997  SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
7998  return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add, DAG.getIntPtrConstant(0));
7999}
8000
8001std::pair<SDValue,SDValue> X86TargetLowering::
8002FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG, bool IsSigned, bool IsReplace) const {
8003  DebugLoc DL = Op.getDebugLoc();
8004
8005  EVT DstTy = Op.getValueType();
8006
8007  if (!IsSigned && !isIntegerTypeFTOL(DstTy)) {
8008    assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
8009    DstTy = MVT::i64;
8010  }
8011
8012  assert(DstTy.getSimpleVT() <= MVT::i64 &&
8013         DstTy.getSimpleVT() >= MVT::i16 &&
8014         "Unknown FP_TO_INT to lower!");
8015
8016  // These are really Legal.
8017  if (DstTy == MVT::i32 &&
8018      isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
8019    return std::make_pair(SDValue(), SDValue());
8020  if (Subtarget->is64Bit() &&
8021      DstTy == MVT::i64 &&
8022      isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
8023    return std::make_pair(SDValue(), SDValue());
8024
8025  // We lower FP->int64 either into FISTP64 followed by a load from a temporary
8026  // stack slot, or into the FTOL runtime function.
8027  MachineFunction &MF = DAG.getMachineFunction();
8028  unsigned MemSize = DstTy.getSizeInBits()/8;
8029  int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
8030  SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8031
8032  unsigned Opc;
8033  if (!IsSigned && isIntegerTypeFTOL(DstTy))
8034    Opc = X86ISD::WIN_FTOL;
8035  else
8036    switch (DstTy.getSimpleVT().SimpleTy) {
8037    default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
8038    case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
8039    case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
8040    case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
8041    }
8042
8043  SDValue Chain = DAG.getEntryNode();
8044  SDValue Value = Op.getOperand(0);
8045  EVT TheVT = Op.getOperand(0).getValueType();
8046  // FIXME This causes a redundant load/store if the SSE-class value is already
8047  // in memory, such as if it is on the callstack.
8048  if (isScalarFPTypeInSSEReg(TheVT)) {
8049    assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
8050    Chain = DAG.getStore(Chain, DL, Value, StackSlot,
8051                         MachinePointerInfo::getFixedStack(SSFI),
8052                         false, false, 0);
8053    SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
8054    SDValue Ops[] = {
8055      Chain, StackSlot, DAG.getValueType(TheVT)
8056    };
8057
8058    MachineMemOperand *MMO =
8059      MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8060                              MachineMemOperand::MOLoad, MemSize, MemSize);
8061    Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, 3,
8062                                    DstTy, MMO);
8063    Chain = Value.getValue(1);
8064    SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
8065    StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8066  }
8067
8068  MachineMemOperand *MMO =
8069    MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8070                            MachineMemOperand::MOStore, MemSize, MemSize);
8071
8072  if (Opc != X86ISD::WIN_FTOL) {
8073    // Build the FP_TO_INT*_IN_MEM
8074    SDValue Ops[] = { Chain, Value, StackSlot };
8075    SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
8076                                           Ops, 3, DstTy, MMO);
8077    return std::make_pair(FIST, StackSlot);
8078  } else {
8079    SDValue ftol = DAG.getNode(X86ISD::WIN_FTOL, DL,
8080      DAG.getVTList(MVT::Other, MVT::Glue),
8081      Chain, Value);
8082    SDValue eax = DAG.getCopyFromReg(ftol, DL, X86::EAX,
8083      MVT::i32, ftol.getValue(1));
8084    SDValue edx = DAG.getCopyFromReg(eax.getValue(1), DL, X86::EDX,
8085      MVT::i32, eax.getValue(2));
8086    SDValue Ops[] = { eax, edx };
8087    SDValue pair = IsReplace
8088      ? DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops, 2)
8089      : DAG.getMergeValues(Ops, 2, DL);
8090    return std::make_pair(pair, SDValue());
8091  }
8092}
8093
8094SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
8095                                           SelectionDAG &DAG) const {
8096  if (Op.getValueType().isVector())
8097    return SDValue();
8098
8099  std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
8100    /*IsSigned=*/ true, /*IsReplace=*/ false);
8101  SDValue FIST = Vals.first, StackSlot = Vals.second;
8102  // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
8103  if (FIST.getNode() == 0) return Op;
8104
8105  if (StackSlot.getNode())
8106    // Load the result.
8107    return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
8108                       FIST, StackSlot, MachinePointerInfo(),
8109                       false, false, false, 0);
8110
8111  // The node is the result.
8112  return FIST;
8113}
8114
8115SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
8116                                           SelectionDAG &DAG) const {
8117  std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
8118    /*IsSigned=*/ false, /*IsReplace=*/ false);
8119  SDValue FIST = Vals.first, StackSlot = Vals.second;
8120  assert(FIST.getNode() && "Unexpected failure");
8121
8122  if (StackSlot.getNode())
8123    // Load the result.
8124    return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
8125                       FIST, StackSlot, MachinePointerInfo(),
8126                       false, false, false, 0);
8127
8128  // The node is the result.
8129  return FIST;
8130}
8131
8132SDValue X86TargetLowering::LowerFABS(SDValue Op,
8133                                     SelectionDAG &DAG) const {
8134  LLVMContext *Context = DAG.getContext();
8135  DebugLoc dl = Op.getDebugLoc();
8136  EVT VT = Op.getValueType();
8137  EVT EltVT = VT;
8138  if (VT.isVector())
8139    EltVT = VT.getVectorElementType();
8140  Constant *C;
8141  if (EltVT == MVT::f64) {
8142    C = ConstantVector::getSplat(2,
8143                ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63)))));
8144  } else {
8145    C = ConstantVector::getSplat(4,
8146               ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31)))));
8147  }
8148  SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8149  SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8150                             MachinePointerInfo::getConstantPool(),
8151                             false, false, false, 16);
8152  return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
8153}
8154
8155SDValue X86TargetLowering::LowerFNEG(SDValue Op, SelectionDAG &DAG) const {
8156  LLVMContext *Context = DAG.getContext();
8157  DebugLoc dl = Op.getDebugLoc();
8158  EVT VT = Op.getValueType();
8159  EVT EltVT = VT;
8160  unsigned NumElts = VT == MVT::f64 ? 2 : 4;
8161  if (VT.isVector()) {
8162    EltVT = VT.getVectorElementType();
8163    NumElts = VT.getVectorNumElements();
8164  }
8165  Constant *C;
8166  if (EltVT == MVT::f64)
8167    C = ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63)));
8168  else
8169    C = ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31)));
8170  C = ConstantVector::getSplat(NumElts, C);
8171  SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8172  SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8173                             MachinePointerInfo::getConstantPool(),
8174                             false, false, false, 16);
8175  if (VT.isVector()) {
8176    MVT XORVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
8177    return DAG.getNode(ISD::BITCAST, dl, VT,
8178                       DAG.getNode(ISD::XOR, dl, XORVT,
8179                                   DAG.getNode(ISD::BITCAST, dl, XORVT,
8180                                               Op.getOperand(0)),
8181                                   DAG.getNode(ISD::BITCAST, dl, XORVT, Mask)));
8182  }
8183
8184  return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
8185}
8186
8187SDValue X86TargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
8188  LLVMContext *Context = DAG.getContext();
8189  SDValue Op0 = Op.getOperand(0);
8190  SDValue Op1 = Op.getOperand(1);
8191  DebugLoc dl = Op.getDebugLoc();
8192  EVT VT = Op.getValueType();
8193  EVT SrcVT = Op1.getValueType();
8194
8195  // If second operand is smaller, extend it first.
8196  if (SrcVT.bitsLT(VT)) {
8197    Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
8198    SrcVT = VT;
8199  }
8200  // And if it is bigger, shrink it first.
8201  if (SrcVT.bitsGT(VT)) {
8202    Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
8203    SrcVT = VT;
8204  }
8205
8206  // At this point the operands and the result should have the same
8207  // type, and that won't be f80 since that is not custom lowered.
8208
8209  // First get the sign bit of second operand.
8210  SmallVector<Constant*,4> CV;
8211  if (SrcVT == MVT::f64) {
8212    CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63))));
8213    CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
8214  } else {
8215    CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31))));
8216    CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8217    CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8218    CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8219  }
8220  Constant *C = ConstantVector::get(CV);
8221  SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8222  SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
8223                              MachinePointerInfo::getConstantPool(),
8224                              false, false, false, 16);
8225  SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
8226
8227  // Shift sign bit right or left if the two operands have different types.
8228  if (SrcVT.bitsGT(VT)) {
8229    // Op0 is MVT::f32, Op1 is MVT::f64.
8230    SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
8231    SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
8232                          DAG.getConstant(32, MVT::i32));
8233    SignBit = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, SignBit);
8234    SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
8235                          DAG.getIntPtrConstant(0));
8236  }
8237
8238  // Clear first operand sign bit.
8239  CV.clear();
8240  if (VT == MVT::f64) {
8241    CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63)))));
8242    CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
8243  } else {
8244    CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31)))));
8245    CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8246    CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8247    CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8248  }
8249  C = ConstantVector::get(CV);
8250  CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8251  SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8252                              MachinePointerInfo::getConstantPool(),
8253                              false, false, false, 16);
8254  SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
8255
8256  // Or the value with the sign bit.
8257  return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
8258}
8259
8260SDValue X86TargetLowering::LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) const {
8261  SDValue N0 = Op.getOperand(0);
8262  DebugLoc dl = Op.getDebugLoc();
8263  EVT VT = Op.getValueType();
8264
8265  // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
8266  SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
8267                                  DAG.getConstant(1, VT));
8268  return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, VT));
8269}
8270
8271/// Emit nodes that will be selected as "test Op0,Op0", or something
8272/// equivalent.
8273SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC,
8274                                    SelectionDAG &DAG) const {
8275  DebugLoc dl = Op.getDebugLoc();
8276
8277  // CF and OF aren't always set the way we want. Determine which
8278  // of these we need.
8279  bool NeedCF = false;
8280  bool NeedOF = false;
8281  switch (X86CC) {
8282  default: break;
8283  case X86::COND_A: case X86::COND_AE:
8284  case X86::COND_B: case X86::COND_BE:
8285    NeedCF = true;
8286    break;
8287  case X86::COND_G: case X86::COND_GE:
8288  case X86::COND_L: case X86::COND_LE:
8289  case X86::COND_O: case X86::COND_NO:
8290    NeedOF = true;
8291    break;
8292  }
8293
8294  // See if we can use the EFLAGS value from the operand instead of
8295  // doing a separate TEST. TEST always sets OF and CF to 0, so unless
8296  // we prove that the arithmetic won't overflow, we can't use OF or CF.
8297  if (Op.getResNo() != 0 || NeedOF || NeedCF)
8298    // Emit a CMP with 0, which is the TEST pattern.
8299    return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
8300                       DAG.getConstant(0, Op.getValueType()));
8301
8302  unsigned Opcode = 0;
8303  unsigned NumOperands = 0;
8304
8305  // Truncate operations may prevent the merge of the SETCC instruction
8306  // and the arithmetic intruction before it. Attempt to truncate the operands
8307  // of the arithmetic instruction and use a reduced bit-width instruction.
8308  bool NeedTruncation = false;
8309  SDValue ArithOp = Op;
8310  if (Op->getOpcode() == ISD::TRUNCATE && Op->hasOneUse()) {
8311    SDValue Arith = Op->getOperand(0);
8312    // Both the trunc and the arithmetic op need to have one user each.
8313    if (Arith->hasOneUse())
8314      switch (Arith.getOpcode()) {
8315        default: break;
8316        case ISD::ADD:
8317        case ISD::SUB:
8318        case ISD::AND:
8319        case ISD::OR:
8320        case ISD::XOR: {
8321          NeedTruncation = true;
8322          ArithOp = Arith;
8323        }
8324      }
8325  }
8326
8327  // NOTICE: In the code below we use ArithOp to hold the arithmetic operation
8328  // which may be the result of a CAST.  We use the variable 'Op', which is the
8329  // non-casted variable when we check for possible users.
8330  switch (ArithOp.getOpcode()) {
8331  case ISD::ADD:
8332    // Due to an isel shortcoming, be conservative if this add is likely to be
8333    // selected as part of a load-modify-store instruction. When the root node
8334    // in a match is a store, isel doesn't know how to remap non-chain non-flag
8335    // uses of other nodes in the match, such as the ADD in this case. This
8336    // leads to the ADD being left around and reselected, with the result being
8337    // two adds in the output.  Alas, even if none our users are stores, that
8338    // doesn't prove we're O.K.  Ergo, if we have any parents that aren't
8339    // CopyToReg or SETCC, eschew INC/DEC.  A better fix seems to require
8340    // climbing the DAG back to the root, and it doesn't seem to be worth the
8341    // effort.
8342    for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
8343         UE = Op.getNode()->use_end(); UI != UE; ++UI)
8344      if (UI->getOpcode() != ISD::CopyToReg &&
8345          UI->getOpcode() != ISD::SETCC &&
8346          UI->getOpcode() != ISD::STORE)
8347        goto default_case;
8348
8349    if (ConstantSDNode *C =
8350        dyn_cast<ConstantSDNode>(ArithOp.getNode()->getOperand(1))) {
8351      // An add of one will be selected as an INC.
8352      if (C->getAPIntValue() == 1) {
8353        Opcode = X86ISD::INC;
8354        NumOperands = 1;
8355        break;
8356      }
8357
8358      // An add of negative one (subtract of one) will be selected as a DEC.
8359      if (C->getAPIntValue().isAllOnesValue()) {
8360        Opcode = X86ISD::DEC;
8361        NumOperands = 1;
8362        break;
8363      }
8364    }
8365
8366    // Otherwise use a regular EFLAGS-setting add.
8367    Opcode = X86ISD::ADD;
8368    NumOperands = 2;
8369    break;
8370  case ISD::AND: {
8371    // If the primary and result isn't used, don't bother using X86ISD::AND,
8372    // because a TEST instruction will be better.
8373    bool NonFlagUse = false;
8374    for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
8375           UE = Op.getNode()->use_end(); UI != UE; ++UI) {
8376      SDNode *User = *UI;
8377      unsigned UOpNo = UI.getOperandNo();
8378      if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
8379        // Look pass truncate.
8380        UOpNo = User->use_begin().getOperandNo();
8381        User = *User->use_begin();
8382      }
8383
8384      if (User->getOpcode() != ISD::BRCOND &&
8385          User->getOpcode() != ISD::SETCC &&
8386          !(User->getOpcode() == ISD::SELECT && UOpNo == 0)) {
8387        NonFlagUse = true;
8388        break;
8389      }
8390    }
8391
8392    if (!NonFlagUse)
8393      break;
8394  }
8395    // FALL THROUGH
8396  case ISD::SUB:
8397  case ISD::OR:
8398  case ISD::XOR:
8399    // Due to the ISEL shortcoming noted above, be conservative if this op is
8400    // likely to be selected as part of a load-modify-store instruction.
8401    for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
8402           UE = Op.getNode()->use_end(); UI != UE; ++UI)
8403      if (UI->getOpcode() == ISD::STORE)
8404        goto default_case;
8405
8406    // Otherwise use a regular EFLAGS-setting instruction.
8407    switch (ArithOp.getOpcode()) {
8408    default: llvm_unreachable("unexpected operator!");
8409    case ISD::SUB: Opcode = X86ISD::SUB; break;
8410    case ISD::OR:  Opcode = X86ISD::OR;  break;
8411    case ISD::XOR: Opcode = X86ISD::XOR; break;
8412    case ISD::AND: Opcode = X86ISD::AND; break;
8413    }
8414
8415    NumOperands = 2;
8416    break;
8417  case X86ISD::ADD:
8418  case X86ISD::SUB:
8419  case X86ISD::INC:
8420  case X86ISD::DEC:
8421  case X86ISD::OR:
8422  case X86ISD::XOR:
8423  case X86ISD::AND:
8424    return SDValue(Op.getNode(), 1);
8425  default:
8426  default_case:
8427    break;
8428  }
8429
8430  // If we found that truncation is beneficial, perform the truncation and
8431  // update 'Op'.
8432  if (NeedTruncation) {
8433    EVT VT = Op.getValueType();
8434    SDValue WideVal = Op->getOperand(0);
8435    EVT WideVT = WideVal.getValueType();
8436    unsigned ConvertedOp = 0;
8437    // Use a target machine opcode to prevent further DAGCombine
8438    // optimizations that may separate the arithmetic operations
8439    // from the setcc node.
8440    switch (WideVal.getOpcode()) {
8441      default: break;
8442      case ISD::ADD: ConvertedOp = X86ISD::ADD; break;
8443      case ISD::SUB: ConvertedOp = X86ISD::SUB; break;
8444      case ISD::AND: ConvertedOp = X86ISD::AND; break;
8445      case ISD::OR:  ConvertedOp = X86ISD::OR;  break;
8446      case ISD::XOR: ConvertedOp = X86ISD::XOR; break;
8447    }
8448
8449    if (ConvertedOp) {
8450      const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8451      if (TLI.isOperationLegal(WideVal.getOpcode(), WideVT)) {
8452        SDValue V0 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(0));
8453        SDValue V1 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(1));
8454        Op = DAG.getNode(ConvertedOp, dl, VT, V0, V1);
8455      }
8456    }
8457  }
8458
8459  if (Opcode == 0)
8460    // Emit a CMP with 0, which is the TEST pattern.
8461    return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
8462                       DAG.getConstant(0, Op.getValueType()));
8463
8464  SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
8465  SmallVector<SDValue, 4> Ops;
8466  for (unsigned i = 0; i != NumOperands; ++i)
8467    Ops.push_back(Op.getOperand(i));
8468
8469  SDValue New = DAG.getNode(Opcode, dl, VTs, &Ops[0], NumOperands);
8470  DAG.ReplaceAllUsesWith(Op, New);
8471  return SDValue(New.getNode(), 1);
8472}
8473
8474/// Emit nodes that will be selected as "cmp Op0,Op1", or something
8475/// equivalent.
8476SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
8477                                   SelectionDAG &DAG) const {
8478  if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1))
8479    if (C->getAPIntValue() == 0)
8480      return EmitTest(Op0, X86CC, DAG);
8481
8482  DebugLoc dl = Op0.getDebugLoc();
8483  if ((Op0.getValueType() == MVT::i8 || Op0.getValueType() == MVT::i16 ||
8484       Op0.getValueType() == MVT::i32 || Op0.getValueType() == MVT::i64)) {
8485    // Use SUB instead of CMP to enable CSE between SUB and CMP.
8486    SDVTList VTs = DAG.getVTList(Op0.getValueType(), MVT::i32);
8487    SDValue Sub = DAG.getNode(X86ISD::SUB, dl, VTs,
8488                              Op0, Op1);
8489    return SDValue(Sub.getNode(), 1);
8490  }
8491  return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
8492}
8493
8494/// Convert a comparison if required by the subtarget.
8495SDValue X86TargetLowering::ConvertCmpIfNecessary(SDValue Cmp,
8496                                                 SelectionDAG &DAG) const {
8497  // If the subtarget does not support the FUCOMI instruction, floating-point
8498  // comparisons have to be converted.
8499  if (Subtarget->hasCMov() ||
8500      Cmp.getOpcode() != X86ISD::CMP ||
8501      !Cmp.getOperand(0).getValueType().isFloatingPoint() ||
8502      !Cmp.getOperand(1).getValueType().isFloatingPoint())
8503    return Cmp;
8504
8505  // The instruction selector will select an FUCOM instruction instead of
8506  // FUCOMI, which writes the comparison result to FPSW instead of EFLAGS. Hence
8507  // build an SDNode sequence that transfers the result from FPSW into EFLAGS:
8508  // (X86sahf (trunc (srl (X86fp_stsw (trunc (X86cmp ...)), 8))))
8509  DebugLoc dl = Cmp.getDebugLoc();
8510  SDValue TruncFPSW = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, Cmp);
8511  SDValue FNStSW = DAG.getNode(X86ISD::FNSTSW16r, dl, MVT::i16, TruncFPSW);
8512  SDValue Srl = DAG.getNode(ISD::SRL, dl, MVT::i16, FNStSW,
8513                            DAG.getConstant(8, MVT::i8));
8514  SDValue TruncSrl = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Srl);
8515  return DAG.getNode(X86ISD::SAHF, dl, MVT::i32, TruncSrl);
8516}
8517
8518/// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
8519/// if it's possible.
8520SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
8521                                     DebugLoc dl, SelectionDAG &DAG) const {
8522  SDValue Op0 = And.getOperand(0);
8523  SDValue Op1 = And.getOperand(1);
8524  if (Op0.getOpcode() == ISD::TRUNCATE)
8525    Op0 = Op0.getOperand(0);
8526  if (Op1.getOpcode() == ISD::TRUNCATE)
8527    Op1 = Op1.getOperand(0);
8528
8529  SDValue LHS, RHS;
8530  if (Op1.getOpcode() == ISD::SHL)
8531    std::swap(Op0, Op1);
8532  if (Op0.getOpcode() == ISD::SHL) {
8533    if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
8534      if (And00C->getZExtValue() == 1) {
8535        // If we looked past a truncate, check that it's only truncating away
8536        // known zeros.
8537        unsigned BitWidth = Op0.getValueSizeInBits();
8538        unsigned AndBitWidth = And.getValueSizeInBits();
8539        if (BitWidth > AndBitWidth) {
8540          APInt Zeros, Ones;
8541          DAG.ComputeMaskedBits(Op0, Zeros, Ones);
8542          if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
8543            return SDValue();
8544        }
8545        LHS = Op1;
8546        RHS = Op0.getOperand(1);
8547      }
8548  } else if (Op1.getOpcode() == ISD::Constant) {
8549    ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
8550    uint64_t AndRHSVal = AndRHS->getZExtValue();
8551    SDValue AndLHS = Op0;
8552
8553    if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) {
8554      LHS = AndLHS.getOperand(0);
8555      RHS = AndLHS.getOperand(1);
8556    }
8557
8558    // Use BT if the immediate can't be encoded in a TEST instruction.
8559    if (!isUInt<32>(AndRHSVal) && isPowerOf2_64(AndRHSVal)) {
8560      LHS = AndLHS;
8561      RHS = DAG.getConstant(Log2_64_Ceil(AndRHSVal), LHS.getValueType());
8562    }
8563  }
8564
8565  if (LHS.getNode()) {
8566    // If LHS is i8, promote it to i32 with any_extend.  There is no i8 BT
8567    // instruction.  Since the shift amount is in-range-or-undefined, we know
8568    // that doing a bittest on the i32 value is ok.  We extend to i32 because
8569    // the encoding for the i16 version is larger than the i32 version.
8570    // Also promote i16 to i32 for performance / code size reason.
8571    if (LHS.getValueType() == MVT::i8 ||
8572        LHS.getValueType() == MVT::i16)
8573      LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
8574
8575    // If the operand types disagree, extend the shift amount to match.  Since
8576    // BT ignores high bits (like shifts) we can use anyextend.
8577    if (LHS.getValueType() != RHS.getValueType())
8578      RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
8579
8580    SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
8581    unsigned Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
8582    return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
8583                       DAG.getConstant(Cond, MVT::i8), BT);
8584  }
8585
8586  return SDValue();
8587}
8588
8589SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
8590
8591  if (Op.getValueType().isVector()) return LowerVSETCC(Op, DAG);
8592
8593  assert(Op.getValueType() == MVT::i8 && "SetCC type must be 8-bit integer");
8594  SDValue Op0 = Op.getOperand(0);
8595  SDValue Op1 = Op.getOperand(1);
8596  DebugLoc dl = Op.getDebugLoc();
8597  ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
8598
8599  // Optimize to BT if possible.
8600  // Lower (X & (1 << N)) == 0 to BT(X, N).
8601  // Lower ((X >>u N) & 1) != 0 to BT(X, N).
8602  // Lower ((X >>s N) & 1) != 0 to BT(X, N).
8603  if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
8604      Op1.getOpcode() == ISD::Constant &&
8605      cast<ConstantSDNode>(Op1)->isNullValue() &&
8606      (CC == ISD::SETEQ || CC == ISD::SETNE)) {
8607    SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
8608    if (NewSetCC.getNode())
8609      return NewSetCC;
8610  }
8611
8612  // Look for X == 0, X == 1, X != 0, or X != 1.  We can simplify some forms of
8613  // these.
8614  if (Op1.getOpcode() == ISD::Constant &&
8615      (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
8616       cast<ConstantSDNode>(Op1)->isNullValue()) &&
8617      (CC == ISD::SETEQ || CC == ISD::SETNE)) {
8618
8619    // If the input is a setcc, then reuse the input setcc or use a new one with
8620    // the inverted condition.
8621    if (Op0.getOpcode() == X86ISD::SETCC) {
8622      X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
8623      bool Invert = (CC == ISD::SETNE) ^
8624        cast<ConstantSDNode>(Op1)->isNullValue();
8625      if (!Invert) return Op0;
8626
8627      CCode = X86::GetOppositeBranchCondition(CCode);
8628      return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
8629                         DAG.getConstant(CCode, MVT::i8), Op0.getOperand(1));
8630    }
8631  }
8632
8633  bool isFP = Op1.getValueType().isFloatingPoint();
8634  unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
8635  if (X86CC == X86::COND_INVALID)
8636    return SDValue();
8637
8638  SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, DAG);
8639  EFLAGS = ConvertCmpIfNecessary(EFLAGS, DAG);
8640  return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
8641                     DAG.getConstant(X86CC, MVT::i8), EFLAGS);
8642}
8643
8644// Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
8645// ones, and then concatenate the result back.
8646static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
8647  EVT VT = Op.getValueType();
8648
8649  assert(VT.is256BitVector() && Op.getOpcode() == ISD::SETCC &&
8650         "Unsupported value type for operation");
8651
8652  unsigned NumElems = VT.getVectorNumElements();
8653  DebugLoc dl = Op.getDebugLoc();
8654  SDValue CC = Op.getOperand(2);
8655
8656  // Extract the LHS vectors
8657  SDValue LHS = Op.getOperand(0);
8658  SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
8659  SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
8660
8661  // Extract the RHS vectors
8662  SDValue RHS = Op.getOperand(1);
8663  SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
8664  SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
8665
8666  // Issue the operation on the smaller types and concatenate the result back
8667  MVT EltVT = VT.getVectorElementType().getSimpleVT();
8668  EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
8669  return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
8670                     DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
8671                     DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
8672}
8673
8674
8675SDValue X86TargetLowering::LowerVSETCC(SDValue Op, SelectionDAG &DAG) const {
8676  SDValue Cond;
8677  SDValue Op0 = Op.getOperand(0);
8678  SDValue Op1 = Op.getOperand(1);
8679  SDValue CC = Op.getOperand(2);
8680  EVT VT = Op.getValueType();
8681  ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
8682  bool isFP = Op.getOperand(1).getValueType().isFloatingPoint();
8683  DebugLoc dl = Op.getDebugLoc();
8684
8685  if (isFP) {
8686#ifndef NDEBUG
8687    EVT EltVT = Op0.getValueType().getVectorElementType();
8688    assert(EltVT == MVT::f32 || EltVT == MVT::f64);
8689#endif
8690
8691    unsigned SSECC;
8692    bool Swap = false;
8693
8694    // SSE Condition code mapping:
8695    //  0 - EQ
8696    //  1 - LT
8697    //  2 - LE
8698    //  3 - UNORD
8699    //  4 - NEQ
8700    //  5 - NLT
8701    //  6 - NLE
8702    //  7 - ORD
8703    switch (SetCCOpcode) {
8704    default: llvm_unreachable("Unexpected SETCC condition");
8705    case ISD::SETOEQ:
8706    case ISD::SETEQ:  SSECC = 0; break;
8707    case ISD::SETOGT:
8708    case ISD::SETGT: Swap = true; // Fallthrough
8709    case ISD::SETLT:
8710    case ISD::SETOLT: SSECC = 1; break;
8711    case ISD::SETOGE:
8712    case ISD::SETGE: Swap = true; // Fallthrough
8713    case ISD::SETLE:
8714    case ISD::SETOLE: SSECC = 2; break;
8715    case ISD::SETUO:  SSECC = 3; break;
8716    case ISD::SETUNE:
8717    case ISD::SETNE:  SSECC = 4; break;
8718    case ISD::SETULE: Swap = true; // Fallthrough
8719    case ISD::SETUGE: SSECC = 5; break;
8720    case ISD::SETULT: Swap = true; // Fallthrough
8721    case ISD::SETUGT: SSECC = 6; break;
8722    case ISD::SETO:   SSECC = 7; break;
8723    case ISD::SETUEQ:
8724    case ISD::SETONE: SSECC = 8; break;
8725    }
8726    if (Swap)
8727      std::swap(Op0, Op1);
8728
8729    // In the two special cases we can't handle, emit two comparisons.
8730    if (SSECC == 8) {
8731      unsigned CC0, CC1;
8732      unsigned CombineOpc;
8733      if (SetCCOpcode == ISD::SETUEQ) {
8734        CC0 = 3; CC1 = 0; CombineOpc = ISD::OR;
8735      } else {
8736        assert(SetCCOpcode == ISD::SETONE);
8737        CC0 = 7; CC1 = 4; CombineOpc = ISD::AND;
8738      }
8739
8740      SDValue Cmp0 = DAG.getNode(X86ISD::CMPP, dl, VT, Op0, Op1,
8741                                 DAG.getConstant(CC0, MVT::i8));
8742      SDValue Cmp1 = DAG.getNode(X86ISD::CMPP, dl, VT, Op0, Op1,
8743                                 DAG.getConstant(CC1, MVT::i8));
8744      return DAG.getNode(CombineOpc, dl, VT, Cmp0, Cmp1);
8745    }
8746    // Handle all other FP comparisons here.
8747    return DAG.getNode(X86ISD::CMPP, dl, VT, Op0, Op1,
8748                       DAG.getConstant(SSECC, MVT::i8));
8749  }
8750
8751  // Break 256-bit integer vector compare into smaller ones.
8752  if (VT.is256BitVector() && !Subtarget->hasAVX2())
8753    return Lower256IntVSETCC(Op, DAG);
8754
8755  // We are handling one of the integer comparisons here.  Since SSE only has
8756  // GT and EQ comparisons for integer, swapping operands and multiple
8757  // operations may be required for some comparisons.
8758  unsigned Opc;
8759  bool Swap = false, Invert = false, FlipSigns = false;
8760
8761  switch (SetCCOpcode) {
8762  default: llvm_unreachable("Unexpected SETCC condition");
8763  case ISD::SETNE:  Invert = true;
8764  case ISD::SETEQ:  Opc = X86ISD::PCMPEQ; break;
8765  case ISD::SETLT:  Swap = true;
8766  case ISD::SETGT:  Opc = X86ISD::PCMPGT; break;
8767  case ISD::SETGE:  Swap = true;
8768  case ISD::SETLE:  Opc = X86ISD::PCMPGT; Invert = true; break;
8769  case ISD::SETULT: Swap = true;
8770  case ISD::SETUGT: Opc = X86ISD::PCMPGT; FlipSigns = true; break;
8771  case ISD::SETUGE: Swap = true;
8772  case ISD::SETULE: Opc = X86ISD::PCMPGT; FlipSigns = true; Invert = true; break;
8773  }
8774  if (Swap)
8775    std::swap(Op0, Op1);
8776
8777  // Check that the operation in question is available (most are plain SSE2,
8778  // but PCMPGTQ and PCMPEQQ have different requirements).
8779  if (VT == MVT::v2i64) {
8780    if (Opc == X86ISD::PCMPGT && !Subtarget->hasSSE42())
8781      return SDValue();
8782    if (Opc == X86ISD::PCMPEQ && !Subtarget->hasSSE41())
8783      return SDValue();
8784  }
8785
8786  // Since SSE has no unsigned integer comparisons, we need to flip  the sign
8787  // bits of the inputs before performing those operations.
8788  if (FlipSigns) {
8789    EVT EltVT = VT.getVectorElementType();
8790    SDValue SignBit = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()),
8791                                      EltVT);
8792    std::vector<SDValue> SignBits(VT.getVectorNumElements(), SignBit);
8793    SDValue SignVec = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &SignBits[0],
8794                                    SignBits.size());
8795    Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SignVec);
8796    Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SignVec);
8797  }
8798
8799  SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
8800
8801  // If the logical-not of the result is required, perform that now.
8802  if (Invert)
8803    Result = DAG.getNOT(dl, Result, VT);
8804
8805  return Result;
8806}
8807
8808// isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
8809static bool isX86LogicalCmp(SDValue Op) {
8810  unsigned Opc = Op.getNode()->getOpcode();
8811  if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI ||
8812      Opc == X86ISD::SAHF)
8813    return true;
8814  if (Op.getResNo() == 1 &&
8815      (Opc == X86ISD::ADD ||
8816       Opc == X86ISD::SUB ||
8817       Opc == X86ISD::ADC ||
8818       Opc == X86ISD::SBB ||
8819       Opc == X86ISD::SMUL ||
8820       Opc == X86ISD::UMUL ||
8821       Opc == X86ISD::INC ||
8822       Opc == X86ISD::DEC ||
8823       Opc == X86ISD::OR ||
8824       Opc == X86ISD::XOR ||
8825       Opc == X86ISD::AND))
8826    return true;
8827
8828  if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
8829    return true;
8830
8831  return false;
8832}
8833
8834static bool isZero(SDValue V) {
8835  ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
8836  return C && C->isNullValue();
8837}
8838
8839static bool isAllOnes(SDValue V) {
8840  ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
8841  return C && C->isAllOnesValue();
8842}
8843
8844static bool isTruncWithZeroHighBitsInput(SDValue V, SelectionDAG &DAG) {
8845  if (V.getOpcode() != ISD::TRUNCATE)
8846    return false;
8847
8848  SDValue VOp0 = V.getOperand(0);
8849  unsigned InBits = VOp0.getValueSizeInBits();
8850  unsigned Bits = V.getValueSizeInBits();
8851  return DAG.MaskedValueIsZero(VOp0, APInt::getHighBitsSet(InBits,InBits-Bits));
8852}
8853
8854SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
8855  bool addTest = true;
8856  SDValue Cond  = Op.getOperand(0);
8857  SDValue Op1 = Op.getOperand(1);
8858  SDValue Op2 = Op.getOperand(2);
8859  DebugLoc DL = Op.getDebugLoc();
8860  SDValue CC;
8861
8862  if (Cond.getOpcode() == ISD::SETCC) {
8863    SDValue NewCond = LowerSETCC(Cond, DAG);
8864    if (NewCond.getNode())
8865      Cond = NewCond;
8866  }
8867
8868  // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
8869  // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
8870  // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
8871  // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
8872  if (Cond.getOpcode() == X86ISD::SETCC &&
8873      Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
8874      isZero(Cond.getOperand(1).getOperand(1))) {
8875    SDValue Cmp = Cond.getOperand(1);
8876
8877    unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
8878
8879    if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
8880        (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
8881      SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
8882
8883      SDValue CmpOp0 = Cmp.getOperand(0);
8884      // Apply further optimizations for special cases
8885      // (select (x != 0), -1, 0) -> neg & sbb
8886      // (select (x == 0), 0, -1) -> neg & sbb
8887      if (ConstantSDNode *YC = dyn_cast<ConstantSDNode>(Y))
8888        if (YC->isNullValue() &&
8889            (isAllOnes(Op1) == (CondCode == X86::COND_NE))) {
8890          SDVTList VTs = DAG.getVTList(CmpOp0.getValueType(), MVT::i32);
8891          SDValue Neg = DAG.getNode(X86ISD::SUB, DL, VTs,
8892                                    DAG.getConstant(0, CmpOp0.getValueType()),
8893                                    CmpOp0);
8894          SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
8895                                    DAG.getConstant(X86::COND_B, MVT::i8),
8896                                    SDValue(Neg.getNode(), 1));
8897          return Res;
8898        }
8899
8900      Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
8901                        CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
8902      Cmp = ConvertCmpIfNecessary(Cmp, DAG);
8903
8904      SDValue Res =   // Res = 0 or -1.
8905        DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
8906                    DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
8907
8908      if (isAllOnes(Op1) != (CondCode == X86::COND_E))
8909        Res = DAG.getNOT(DL, Res, Res.getValueType());
8910
8911      ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
8912      if (N2C == 0 || !N2C->isNullValue())
8913        Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
8914      return Res;
8915    }
8916  }
8917
8918  // Look past (and (setcc_carry (cmp ...)), 1).
8919  if (Cond.getOpcode() == ISD::AND &&
8920      Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
8921    ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
8922    if (C && C->getAPIntValue() == 1)
8923      Cond = Cond.getOperand(0);
8924  }
8925
8926  // If condition flag is set by a X86ISD::CMP, then use it as the condition
8927  // setting operand in place of the X86ISD::SETCC.
8928  unsigned CondOpcode = Cond.getOpcode();
8929  if (CondOpcode == X86ISD::SETCC ||
8930      CondOpcode == X86ISD::SETCC_CARRY) {
8931    CC = Cond.getOperand(0);
8932
8933    SDValue Cmp = Cond.getOperand(1);
8934    unsigned Opc = Cmp.getOpcode();
8935    EVT VT = Op.getValueType();
8936
8937    bool IllegalFPCMov = false;
8938    if (VT.isFloatingPoint() && !VT.isVector() &&
8939        !isScalarFPTypeInSSEReg(VT))  // FPStack?
8940      IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
8941
8942    if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
8943        Opc == X86ISD::BT) { // FIXME
8944      Cond = Cmp;
8945      addTest = false;
8946    }
8947  } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
8948             CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
8949             ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
8950              Cond.getOperand(0).getValueType() != MVT::i8)) {
8951    SDValue LHS = Cond.getOperand(0);
8952    SDValue RHS = Cond.getOperand(1);
8953    unsigned X86Opcode;
8954    unsigned X86Cond;
8955    SDVTList VTs;
8956    switch (CondOpcode) {
8957    case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
8958    case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
8959    case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
8960    case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
8961    case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
8962    case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
8963    default: llvm_unreachable("unexpected overflowing operator");
8964    }
8965    if (CondOpcode == ISD::UMULO)
8966      VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
8967                          MVT::i32);
8968    else
8969      VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
8970
8971    SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS);
8972
8973    if (CondOpcode == ISD::UMULO)
8974      Cond = X86Op.getValue(2);
8975    else
8976      Cond = X86Op.getValue(1);
8977
8978    CC = DAG.getConstant(X86Cond, MVT::i8);
8979    addTest = false;
8980  }
8981
8982  if (addTest) {
8983    // Look pass the truncate if the high bits are known zero.
8984    if (isTruncWithZeroHighBitsInput(Cond, DAG))
8985        Cond = Cond.getOperand(0);
8986
8987    // We know the result of AND is compared against zero. Try to match
8988    // it to BT.
8989    if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
8990      SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
8991      if (NewSetCC.getNode()) {
8992        CC = NewSetCC.getOperand(0);
8993        Cond = NewSetCC.getOperand(1);
8994        addTest = false;
8995      }
8996    }
8997  }
8998
8999  if (addTest) {
9000    CC = DAG.getConstant(X86::COND_NE, MVT::i8);
9001    Cond = EmitTest(Cond, X86::COND_NE, DAG);
9002  }
9003
9004  // a <  b ? -1 :  0 -> RES = ~setcc_carry
9005  // a <  b ?  0 : -1 -> RES = setcc_carry
9006  // a >= b ? -1 :  0 -> RES = setcc_carry
9007  // a >= b ?  0 : -1 -> RES = ~setcc_carry
9008  if (Cond.getOpcode() == X86ISD::SUB) {
9009    Cond = ConvertCmpIfNecessary(Cond, DAG);
9010    unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
9011
9012    if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
9013        (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
9014      SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
9015                                DAG.getConstant(X86::COND_B, MVT::i8), Cond);
9016      if (isAllOnes(Op1) != (CondCode == X86::COND_B))
9017        return DAG.getNOT(DL, Res, Res.getValueType());
9018      return Res;
9019    }
9020  }
9021
9022  // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
9023  // condition is true.
9024  SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
9025  SDValue Ops[] = { Op2, Op1, CC, Cond };
9026  return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops, array_lengthof(Ops));
9027}
9028
9029// isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
9030// ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
9031// from the AND / OR.
9032static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
9033  Opc = Op.getOpcode();
9034  if (Opc != ISD::OR && Opc != ISD::AND)
9035    return false;
9036  return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
9037          Op.getOperand(0).hasOneUse() &&
9038          Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
9039          Op.getOperand(1).hasOneUse());
9040}
9041
9042// isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
9043// 1 and that the SETCC node has a single use.
9044static bool isXor1OfSetCC(SDValue Op) {
9045  if (Op.getOpcode() != ISD::XOR)
9046    return false;
9047  ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
9048  if (N1C && N1C->getAPIntValue() == 1) {
9049    return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
9050      Op.getOperand(0).hasOneUse();
9051  }
9052  return false;
9053}
9054
9055SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
9056  bool addTest = true;
9057  SDValue Chain = Op.getOperand(0);
9058  SDValue Cond  = Op.getOperand(1);
9059  SDValue Dest  = Op.getOperand(2);
9060  DebugLoc dl = Op.getDebugLoc();
9061  SDValue CC;
9062  bool Inverted = false;
9063
9064  if (Cond.getOpcode() == ISD::SETCC) {
9065    // Check for setcc([su]{add,sub,mul}o == 0).
9066    if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
9067        isa<ConstantSDNode>(Cond.getOperand(1)) &&
9068        cast<ConstantSDNode>(Cond.getOperand(1))->isNullValue() &&
9069        Cond.getOperand(0).getResNo() == 1 &&
9070        (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
9071         Cond.getOperand(0).getOpcode() == ISD::UADDO ||
9072         Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
9073         Cond.getOperand(0).getOpcode() == ISD::USUBO ||
9074         Cond.getOperand(0).getOpcode() == ISD::SMULO ||
9075         Cond.getOperand(0).getOpcode() == ISD::UMULO)) {
9076      Inverted = true;
9077      Cond = Cond.getOperand(0);
9078    } else {
9079      SDValue NewCond = LowerSETCC(Cond, DAG);
9080      if (NewCond.getNode())
9081        Cond = NewCond;
9082    }
9083  }
9084#if 0
9085  // FIXME: LowerXALUO doesn't handle these!!
9086  else if (Cond.getOpcode() == X86ISD::ADD  ||
9087           Cond.getOpcode() == X86ISD::SUB  ||
9088           Cond.getOpcode() == X86ISD::SMUL ||
9089           Cond.getOpcode() == X86ISD::UMUL)
9090    Cond = LowerXALUO(Cond, DAG);
9091#endif
9092
9093  // Look pass (and (setcc_carry (cmp ...)), 1).
9094  if (Cond.getOpcode() == ISD::AND &&
9095      Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
9096    ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
9097    if (C && C->getAPIntValue() == 1)
9098      Cond = Cond.getOperand(0);
9099  }
9100
9101  // If condition flag is set by a X86ISD::CMP, then use it as the condition
9102  // setting operand in place of the X86ISD::SETCC.
9103  unsigned CondOpcode = Cond.getOpcode();
9104  if (CondOpcode == X86ISD::SETCC ||
9105      CondOpcode == X86ISD::SETCC_CARRY) {
9106    CC = Cond.getOperand(0);
9107
9108    SDValue Cmp = Cond.getOperand(1);
9109    unsigned Opc = Cmp.getOpcode();
9110    // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
9111    if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
9112      Cond = Cmp;
9113      addTest = false;
9114    } else {
9115      switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
9116      default: break;
9117      case X86::COND_O:
9118      case X86::COND_B:
9119        // These can only come from an arithmetic instruction with overflow,
9120        // e.g. SADDO, UADDO.
9121        Cond = Cond.getNode()->getOperand(1);
9122        addTest = false;
9123        break;
9124      }
9125    }
9126  }
9127  CondOpcode = Cond.getOpcode();
9128  if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
9129      CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
9130      ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
9131       Cond.getOperand(0).getValueType() != MVT::i8)) {
9132    SDValue LHS = Cond.getOperand(0);
9133    SDValue RHS = Cond.getOperand(1);
9134    unsigned X86Opcode;
9135    unsigned X86Cond;
9136    SDVTList VTs;
9137    switch (CondOpcode) {
9138    case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
9139    case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
9140    case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
9141    case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
9142    case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
9143    case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
9144    default: llvm_unreachable("unexpected overflowing operator");
9145    }
9146    if (Inverted)
9147      X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond);
9148    if (CondOpcode == ISD::UMULO)
9149      VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
9150                          MVT::i32);
9151    else
9152      VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
9153
9154    SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS);
9155
9156    if (CondOpcode == ISD::UMULO)
9157      Cond = X86Op.getValue(2);
9158    else
9159      Cond = X86Op.getValue(1);
9160
9161    CC = DAG.getConstant(X86Cond, MVT::i8);
9162    addTest = false;
9163  } else {
9164    unsigned CondOpc;
9165    if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
9166      SDValue Cmp = Cond.getOperand(0).getOperand(1);
9167      if (CondOpc == ISD::OR) {
9168        // Also, recognize the pattern generated by an FCMP_UNE. We can emit
9169        // two branches instead of an explicit OR instruction with a
9170        // separate test.
9171        if (Cmp == Cond.getOperand(1).getOperand(1) &&
9172            isX86LogicalCmp(Cmp)) {
9173          CC = Cond.getOperand(0).getOperand(0);
9174          Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9175                              Chain, Dest, CC, Cmp);
9176          CC = Cond.getOperand(1).getOperand(0);
9177          Cond = Cmp;
9178          addTest = false;
9179        }
9180      } else { // ISD::AND
9181        // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
9182        // two branches instead of an explicit AND instruction with a
9183        // separate test. However, we only do this if this block doesn't
9184        // have a fall-through edge, because this requires an explicit
9185        // jmp when the condition is false.
9186        if (Cmp == Cond.getOperand(1).getOperand(1) &&
9187            isX86LogicalCmp(Cmp) &&
9188            Op.getNode()->hasOneUse()) {
9189          X86::CondCode CCode =
9190            (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
9191          CCode = X86::GetOppositeBranchCondition(CCode);
9192          CC = DAG.getConstant(CCode, MVT::i8);
9193          SDNode *User = *Op.getNode()->use_begin();
9194          // Look for an unconditional branch following this conditional branch.
9195          // We need this because we need to reverse the successors in order
9196          // to implement FCMP_OEQ.
9197          if (User->getOpcode() == ISD::BR) {
9198            SDValue FalseBB = User->getOperand(1);
9199            SDNode *NewBR =
9200              DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
9201            assert(NewBR == User);
9202            (void)NewBR;
9203            Dest = FalseBB;
9204
9205            Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9206                                Chain, Dest, CC, Cmp);
9207            X86::CondCode CCode =
9208              (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
9209            CCode = X86::GetOppositeBranchCondition(CCode);
9210            CC = DAG.getConstant(CCode, MVT::i8);
9211            Cond = Cmp;
9212            addTest = false;
9213          }
9214        }
9215      }
9216    } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
9217      // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
9218      // It should be transformed during dag combiner except when the condition
9219      // is set by a arithmetics with overflow node.
9220      X86::CondCode CCode =
9221        (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
9222      CCode = X86::GetOppositeBranchCondition(CCode);
9223      CC = DAG.getConstant(CCode, MVT::i8);
9224      Cond = Cond.getOperand(0).getOperand(1);
9225      addTest = false;
9226    } else if (Cond.getOpcode() == ISD::SETCC &&
9227               cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) {
9228      // For FCMP_OEQ, we can emit
9229      // two branches instead of an explicit AND instruction with a
9230      // separate test. However, we only do this if this block doesn't
9231      // have a fall-through edge, because this requires an explicit
9232      // jmp when the condition is false.
9233      if (Op.getNode()->hasOneUse()) {
9234        SDNode *User = *Op.getNode()->use_begin();
9235        // Look for an unconditional branch following this conditional branch.
9236        // We need this because we need to reverse the successors in order
9237        // to implement FCMP_OEQ.
9238        if (User->getOpcode() == ISD::BR) {
9239          SDValue FalseBB = User->getOperand(1);
9240          SDNode *NewBR =
9241            DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
9242          assert(NewBR == User);
9243          (void)NewBR;
9244          Dest = FalseBB;
9245
9246          SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
9247                                    Cond.getOperand(0), Cond.getOperand(1));
9248          Cmp = ConvertCmpIfNecessary(Cmp, DAG);
9249          CC = DAG.getConstant(X86::COND_NE, MVT::i8);
9250          Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9251                              Chain, Dest, CC, Cmp);
9252          CC = DAG.getConstant(X86::COND_P, MVT::i8);
9253          Cond = Cmp;
9254          addTest = false;
9255        }
9256      }
9257    } else if (Cond.getOpcode() == ISD::SETCC &&
9258               cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) {
9259      // For FCMP_UNE, we can emit
9260      // two branches instead of an explicit AND instruction with a
9261      // separate test. However, we only do this if this block doesn't
9262      // have a fall-through edge, because this requires an explicit
9263      // jmp when the condition is false.
9264      if (Op.getNode()->hasOneUse()) {
9265        SDNode *User = *Op.getNode()->use_begin();
9266        // Look for an unconditional branch following this conditional branch.
9267        // We need this because we need to reverse the successors in order
9268        // to implement FCMP_UNE.
9269        if (User->getOpcode() == ISD::BR) {
9270          SDValue FalseBB = User->getOperand(1);
9271          SDNode *NewBR =
9272            DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
9273          assert(NewBR == User);
9274          (void)NewBR;
9275
9276          SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
9277                                    Cond.getOperand(0), Cond.getOperand(1));
9278          Cmp = ConvertCmpIfNecessary(Cmp, DAG);
9279          CC = DAG.getConstant(X86::COND_NE, MVT::i8);
9280          Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9281                              Chain, Dest, CC, Cmp);
9282          CC = DAG.getConstant(X86::COND_NP, MVT::i8);
9283          Cond = Cmp;
9284          addTest = false;
9285          Dest = FalseBB;
9286        }
9287      }
9288    }
9289  }
9290
9291  if (addTest) {
9292    // Look pass the truncate if the high bits are known zero.
9293    if (isTruncWithZeroHighBitsInput(Cond, DAG))
9294        Cond = Cond.getOperand(0);
9295
9296    // We know the result of AND is compared against zero. Try to match
9297    // it to BT.
9298    if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
9299      SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
9300      if (NewSetCC.getNode()) {
9301        CC = NewSetCC.getOperand(0);
9302        Cond = NewSetCC.getOperand(1);
9303        addTest = false;
9304      }
9305    }
9306  }
9307
9308  if (addTest) {
9309    CC = DAG.getConstant(X86::COND_NE, MVT::i8);
9310    Cond = EmitTest(Cond, X86::COND_NE, DAG);
9311  }
9312  Cond = ConvertCmpIfNecessary(Cond, DAG);
9313  return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9314                     Chain, Dest, CC, Cond);
9315}
9316
9317
9318// Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
9319// Calls to _alloca is needed to probe the stack when allocating more than 4k
9320// bytes in one go. Touching the stack at 4K increments is necessary to ensure
9321// that the guard pages used by the OS virtual memory manager are allocated in
9322// correct sequence.
9323SDValue
9324X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
9325                                           SelectionDAG &DAG) const {
9326  assert((Subtarget->isTargetCygMing() || Subtarget->isTargetWindows() ||
9327          getTargetMachine().Options.EnableSegmentedStacks) &&
9328         "This should be used only on Windows targets or when segmented stacks "
9329         "are being used");
9330  assert(!Subtarget->isTargetEnvMacho() && "Not implemented");
9331  DebugLoc dl = Op.getDebugLoc();
9332
9333  // Get the inputs.
9334  SDValue Chain = Op.getOperand(0);
9335  SDValue Size  = Op.getOperand(1);
9336  // FIXME: Ensure alignment here
9337
9338  bool Is64Bit = Subtarget->is64Bit();
9339  EVT SPTy = Is64Bit ? MVT::i64 : MVT::i32;
9340
9341  if (getTargetMachine().Options.EnableSegmentedStacks) {
9342    MachineFunction &MF = DAG.getMachineFunction();
9343    MachineRegisterInfo &MRI = MF.getRegInfo();
9344
9345    if (Is64Bit) {
9346      // The 64 bit implementation of segmented stacks needs to clobber both r10
9347      // r11. This makes it impossible to use it along with nested parameters.
9348      const Function *F = MF.getFunction();
9349
9350      for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
9351           I != E; ++I)
9352        if (I->hasNestAttr())
9353          report_fatal_error("Cannot use segmented stacks with functions that "
9354                             "have nested arguments.");
9355    }
9356
9357    const TargetRegisterClass *AddrRegClass =
9358      getRegClassFor(Subtarget->is64Bit() ? MVT::i64:MVT::i32);
9359    unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
9360    Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
9361    SDValue Value = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
9362                                DAG.getRegister(Vreg, SPTy));
9363    SDValue Ops1[2] = { Value, Chain };
9364    return DAG.getMergeValues(Ops1, 2, dl);
9365  } else {
9366    SDValue Flag;
9367    unsigned Reg = (Subtarget->is64Bit() ? X86::RAX : X86::EAX);
9368
9369    Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
9370    Flag = Chain.getValue(1);
9371    SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
9372
9373    Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
9374    Flag = Chain.getValue(1);
9375
9376    Chain = DAG.getCopyFromReg(Chain, dl, X86StackPtr, SPTy).getValue(1);
9377
9378    SDValue Ops1[2] = { Chain.getValue(0), Chain };
9379    return DAG.getMergeValues(Ops1, 2, dl);
9380  }
9381}
9382
9383SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
9384  MachineFunction &MF = DAG.getMachineFunction();
9385  X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
9386
9387  const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
9388  DebugLoc DL = Op.getDebugLoc();
9389
9390  if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
9391    // vastart just stores the address of the VarArgsFrameIndex slot into the
9392    // memory location argument.
9393    SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
9394                                   getPointerTy());
9395    return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
9396                        MachinePointerInfo(SV), false, false, 0);
9397  }
9398
9399  // __va_list_tag:
9400  //   gp_offset         (0 - 6 * 8)
9401  //   fp_offset         (48 - 48 + 8 * 16)
9402  //   overflow_arg_area (point to parameters coming in memory).
9403  //   reg_save_area
9404  SmallVector<SDValue, 8> MemOps;
9405  SDValue FIN = Op.getOperand(1);
9406  // Store gp_offset
9407  SDValue Store = DAG.getStore(Op.getOperand(0), DL,
9408                               DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
9409                                               MVT::i32),
9410                               FIN, MachinePointerInfo(SV), false, false, 0);
9411  MemOps.push_back(Store);
9412
9413  // Store fp_offset
9414  FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
9415                    FIN, DAG.getIntPtrConstant(4));
9416  Store = DAG.getStore(Op.getOperand(0), DL,
9417                       DAG.getConstant(FuncInfo->getVarArgsFPOffset(),
9418                                       MVT::i32),
9419                       FIN, MachinePointerInfo(SV, 4), false, false, 0);
9420  MemOps.push_back(Store);
9421
9422  // Store ptr to overflow_arg_area
9423  FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
9424                    FIN, DAG.getIntPtrConstant(4));
9425  SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
9426                                    getPointerTy());
9427  Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
9428                       MachinePointerInfo(SV, 8),
9429                       false, false, 0);
9430  MemOps.push_back(Store);
9431
9432  // Store ptr to reg_save_area.
9433  FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
9434                    FIN, DAG.getIntPtrConstant(8));
9435  SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
9436                                    getPointerTy());
9437  Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
9438                       MachinePointerInfo(SV, 16), false, false, 0);
9439  MemOps.push_back(Store);
9440  return DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
9441                     &MemOps[0], MemOps.size());
9442}
9443
9444SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
9445  assert(Subtarget->is64Bit() &&
9446         "LowerVAARG only handles 64-bit va_arg!");
9447  assert((Subtarget->isTargetLinux() ||
9448          Subtarget->isTargetDarwin()) &&
9449          "Unhandled target in LowerVAARG");
9450  assert(Op.getNode()->getNumOperands() == 4);
9451  SDValue Chain = Op.getOperand(0);
9452  SDValue SrcPtr = Op.getOperand(1);
9453  const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
9454  unsigned Align = Op.getConstantOperandVal(3);
9455  DebugLoc dl = Op.getDebugLoc();
9456
9457  EVT ArgVT = Op.getNode()->getValueType(0);
9458  Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
9459  uint32_t ArgSize = getTargetData()->getTypeAllocSize(ArgTy);
9460  uint8_t ArgMode;
9461
9462  // Decide which area this value should be read from.
9463  // TODO: Implement the AMD64 ABI in its entirety. This simple
9464  // selection mechanism works only for the basic types.
9465  if (ArgVT == MVT::f80) {
9466    llvm_unreachable("va_arg for f80 not yet implemented");
9467  } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
9468    ArgMode = 2;  // Argument passed in XMM register. Use fp_offset.
9469  } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
9470    ArgMode = 1;  // Argument passed in GPR64 register(s). Use gp_offset.
9471  } else {
9472    llvm_unreachable("Unhandled argument type in LowerVAARG");
9473  }
9474
9475  if (ArgMode == 2) {
9476    // Sanity Check: Make sure using fp_offset makes sense.
9477    assert(!getTargetMachine().Options.UseSoftFloat &&
9478           !(DAG.getMachineFunction()
9479                .getFunction()->hasFnAttr(Attribute::NoImplicitFloat)) &&
9480           Subtarget->hasSSE1());
9481  }
9482
9483  // Insert VAARG_64 node into the DAG
9484  // VAARG_64 returns two values: Variable Argument Address, Chain
9485  SmallVector<SDValue, 11> InstOps;
9486  InstOps.push_back(Chain);
9487  InstOps.push_back(SrcPtr);
9488  InstOps.push_back(DAG.getConstant(ArgSize, MVT::i32));
9489  InstOps.push_back(DAG.getConstant(ArgMode, MVT::i8));
9490  InstOps.push_back(DAG.getConstant(Align, MVT::i32));
9491  SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other);
9492  SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
9493                                          VTs, &InstOps[0], InstOps.size(),
9494                                          MVT::i64,
9495                                          MachinePointerInfo(SV),
9496                                          /*Align=*/0,
9497                                          /*Volatile=*/false,
9498                                          /*ReadMem=*/true,
9499                                          /*WriteMem=*/true);
9500  Chain = VAARG.getValue(1);
9501
9502  // Load the next argument and return it
9503  return DAG.getLoad(ArgVT, dl,
9504                     Chain,
9505                     VAARG,
9506                     MachinePointerInfo(),
9507                     false, false, false, 0);
9508}
9509
9510SDValue X86TargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) const {
9511  // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
9512  assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
9513  SDValue Chain = Op.getOperand(0);
9514  SDValue DstPtr = Op.getOperand(1);
9515  SDValue SrcPtr = Op.getOperand(2);
9516  const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
9517  const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
9518  DebugLoc DL = Op.getDebugLoc();
9519
9520  return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
9521                       DAG.getIntPtrConstant(24), 8, /*isVolatile*/false,
9522                       false,
9523                       MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
9524}
9525
9526// getTargetVShiftNOde - Handle vector element shifts where the shift amount
9527// may or may not be a constant. Takes immediate version of shift as input.
9528static SDValue getTargetVShiftNode(unsigned Opc, DebugLoc dl, EVT VT,
9529                                   SDValue SrcOp, SDValue ShAmt,
9530                                   SelectionDAG &DAG) {
9531  assert(ShAmt.getValueType() == MVT::i32 && "ShAmt is not i32");
9532
9533  if (isa<ConstantSDNode>(ShAmt)) {
9534    // Constant may be a TargetConstant. Use a regular constant.
9535    uint32_t ShiftAmt = cast<ConstantSDNode>(ShAmt)->getZExtValue();
9536    switch (Opc) {
9537      default: llvm_unreachable("Unknown target vector shift node");
9538      case X86ISD::VSHLI:
9539      case X86ISD::VSRLI:
9540      case X86ISD::VSRAI:
9541        return DAG.getNode(Opc, dl, VT, SrcOp,
9542                           DAG.getConstant(ShiftAmt, MVT::i32));
9543    }
9544  }
9545
9546  // Change opcode to non-immediate version
9547  switch (Opc) {
9548    default: llvm_unreachable("Unknown target vector shift node");
9549    case X86ISD::VSHLI: Opc = X86ISD::VSHL; break;
9550    case X86ISD::VSRLI: Opc = X86ISD::VSRL; break;
9551    case X86ISD::VSRAI: Opc = X86ISD::VSRA; break;
9552  }
9553
9554  // Need to build a vector containing shift amount
9555  // Shift amount is 32-bits, but SSE instructions read 64-bit, so fill with 0
9556  SDValue ShOps[4];
9557  ShOps[0] = ShAmt;
9558  ShOps[1] = DAG.getConstant(0, MVT::i32);
9559  ShOps[2] = ShOps[3] = DAG.getUNDEF(MVT::i32);
9560  ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, &ShOps[0], 4);
9561
9562  // The return type has to be a 128-bit type with the same element
9563  // type as the input type.
9564  MVT EltVT = VT.getVectorElementType().getSimpleVT();
9565  EVT ShVT = MVT::getVectorVT(EltVT, 128/EltVT.getSizeInBits());
9566
9567  ShAmt = DAG.getNode(ISD::BITCAST, dl, ShVT, ShAmt);
9568  return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
9569}
9570
9571SDValue
9572X86TargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) const {
9573  DebugLoc dl = Op.getDebugLoc();
9574  unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9575  switch (IntNo) {
9576  default: return SDValue();    // Don't custom lower most intrinsics.
9577  // Comparison intrinsics.
9578  case Intrinsic::x86_sse_comieq_ss:
9579  case Intrinsic::x86_sse_comilt_ss:
9580  case Intrinsic::x86_sse_comile_ss:
9581  case Intrinsic::x86_sse_comigt_ss:
9582  case Intrinsic::x86_sse_comige_ss:
9583  case Intrinsic::x86_sse_comineq_ss:
9584  case Intrinsic::x86_sse_ucomieq_ss:
9585  case Intrinsic::x86_sse_ucomilt_ss:
9586  case Intrinsic::x86_sse_ucomile_ss:
9587  case Intrinsic::x86_sse_ucomigt_ss:
9588  case Intrinsic::x86_sse_ucomige_ss:
9589  case Intrinsic::x86_sse_ucomineq_ss:
9590  case Intrinsic::x86_sse2_comieq_sd:
9591  case Intrinsic::x86_sse2_comilt_sd:
9592  case Intrinsic::x86_sse2_comile_sd:
9593  case Intrinsic::x86_sse2_comigt_sd:
9594  case Intrinsic::x86_sse2_comige_sd:
9595  case Intrinsic::x86_sse2_comineq_sd:
9596  case Intrinsic::x86_sse2_ucomieq_sd:
9597  case Intrinsic::x86_sse2_ucomilt_sd:
9598  case Intrinsic::x86_sse2_ucomile_sd:
9599  case Intrinsic::x86_sse2_ucomigt_sd:
9600  case Intrinsic::x86_sse2_ucomige_sd:
9601  case Intrinsic::x86_sse2_ucomineq_sd: {
9602    unsigned Opc;
9603    ISD::CondCode CC;
9604    switch (IntNo) {
9605    default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
9606    case Intrinsic::x86_sse_comieq_ss:
9607    case Intrinsic::x86_sse2_comieq_sd:
9608      Opc = X86ISD::COMI;
9609      CC = ISD::SETEQ;
9610      break;
9611    case Intrinsic::x86_sse_comilt_ss:
9612    case Intrinsic::x86_sse2_comilt_sd:
9613      Opc = X86ISD::COMI;
9614      CC = ISD::SETLT;
9615      break;
9616    case Intrinsic::x86_sse_comile_ss:
9617    case Intrinsic::x86_sse2_comile_sd:
9618      Opc = X86ISD::COMI;
9619      CC = ISD::SETLE;
9620      break;
9621    case Intrinsic::x86_sse_comigt_ss:
9622    case Intrinsic::x86_sse2_comigt_sd:
9623      Opc = X86ISD::COMI;
9624      CC = ISD::SETGT;
9625      break;
9626    case Intrinsic::x86_sse_comige_ss:
9627    case Intrinsic::x86_sse2_comige_sd:
9628      Opc = X86ISD::COMI;
9629      CC = ISD::SETGE;
9630      break;
9631    case Intrinsic::x86_sse_comineq_ss:
9632    case Intrinsic::x86_sse2_comineq_sd:
9633      Opc = X86ISD::COMI;
9634      CC = ISD::SETNE;
9635      break;
9636    case Intrinsic::x86_sse_ucomieq_ss:
9637    case Intrinsic::x86_sse2_ucomieq_sd:
9638      Opc = X86ISD::UCOMI;
9639      CC = ISD::SETEQ;
9640      break;
9641    case Intrinsic::x86_sse_ucomilt_ss:
9642    case Intrinsic::x86_sse2_ucomilt_sd:
9643      Opc = X86ISD::UCOMI;
9644      CC = ISD::SETLT;
9645      break;
9646    case Intrinsic::x86_sse_ucomile_ss:
9647    case Intrinsic::x86_sse2_ucomile_sd:
9648      Opc = X86ISD::UCOMI;
9649      CC = ISD::SETLE;
9650      break;
9651    case Intrinsic::x86_sse_ucomigt_ss:
9652    case Intrinsic::x86_sse2_ucomigt_sd:
9653      Opc = X86ISD::UCOMI;
9654      CC = ISD::SETGT;
9655      break;
9656    case Intrinsic::x86_sse_ucomige_ss:
9657    case Intrinsic::x86_sse2_ucomige_sd:
9658      Opc = X86ISD::UCOMI;
9659      CC = ISD::SETGE;
9660      break;
9661    case Intrinsic::x86_sse_ucomineq_ss:
9662    case Intrinsic::x86_sse2_ucomineq_sd:
9663      Opc = X86ISD::UCOMI;
9664      CC = ISD::SETNE;
9665      break;
9666    }
9667
9668    SDValue LHS = Op.getOperand(1);
9669    SDValue RHS = Op.getOperand(2);
9670    unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
9671    assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
9672    SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS);
9673    SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
9674                                DAG.getConstant(X86CC, MVT::i8), Cond);
9675    return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
9676  }
9677
9678  // Arithmetic intrinsics.
9679  case Intrinsic::x86_sse2_pmulu_dq:
9680  case Intrinsic::x86_avx2_pmulu_dq:
9681    return DAG.getNode(X86ISD::PMULUDQ, dl, Op.getValueType(),
9682                       Op.getOperand(1), Op.getOperand(2));
9683
9684  // SSE3/AVX horizontal add/sub intrinsics
9685  case Intrinsic::x86_sse3_hadd_ps:
9686  case Intrinsic::x86_sse3_hadd_pd:
9687  case Intrinsic::x86_avx_hadd_ps_256:
9688  case Intrinsic::x86_avx_hadd_pd_256:
9689  case Intrinsic::x86_sse3_hsub_ps:
9690  case Intrinsic::x86_sse3_hsub_pd:
9691  case Intrinsic::x86_avx_hsub_ps_256:
9692  case Intrinsic::x86_avx_hsub_pd_256:
9693  case Intrinsic::x86_ssse3_phadd_w_128:
9694  case Intrinsic::x86_ssse3_phadd_d_128:
9695  case Intrinsic::x86_avx2_phadd_w:
9696  case Intrinsic::x86_avx2_phadd_d:
9697  case Intrinsic::x86_ssse3_phsub_w_128:
9698  case Intrinsic::x86_ssse3_phsub_d_128:
9699  case Intrinsic::x86_avx2_phsub_w:
9700  case Intrinsic::x86_avx2_phsub_d: {
9701    unsigned Opcode;
9702    switch (IntNo) {
9703    default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
9704    case Intrinsic::x86_sse3_hadd_ps:
9705    case Intrinsic::x86_sse3_hadd_pd:
9706    case Intrinsic::x86_avx_hadd_ps_256:
9707    case Intrinsic::x86_avx_hadd_pd_256:
9708      Opcode = X86ISD::FHADD;
9709      break;
9710    case Intrinsic::x86_sse3_hsub_ps:
9711    case Intrinsic::x86_sse3_hsub_pd:
9712    case Intrinsic::x86_avx_hsub_ps_256:
9713    case Intrinsic::x86_avx_hsub_pd_256:
9714      Opcode = X86ISD::FHSUB;
9715      break;
9716    case Intrinsic::x86_ssse3_phadd_w_128:
9717    case Intrinsic::x86_ssse3_phadd_d_128:
9718    case Intrinsic::x86_avx2_phadd_w:
9719    case Intrinsic::x86_avx2_phadd_d:
9720      Opcode = X86ISD::HADD;
9721      break;
9722    case Intrinsic::x86_ssse3_phsub_w_128:
9723    case Intrinsic::x86_ssse3_phsub_d_128:
9724    case Intrinsic::x86_avx2_phsub_w:
9725    case Intrinsic::x86_avx2_phsub_d:
9726      Opcode = X86ISD::HSUB;
9727      break;
9728    }
9729    return DAG.getNode(Opcode, dl, Op.getValueType(),
9730                       Op.getOperand(1), Op.getOperand(2));
9731  }
9732
9733  // AVX2 variable shift intrinsics
9734  case Intrinsic::x86_avx2_psllv_d:
9735  case Intrinsic::x86_avx2_psllv_q:
9736  case Intrinsic::x86_avx2_psllv_d_256:
9737  case Intrinsic::x86_avx2_psllv_q_256:
9738  case Intrinsic::x86_avx2_psrlv_d:
9739  case Intrinsic::x86_avx2_psrlv_q:
9740  case Intrinsic::x86_avx2_psrlv_d_256:
9741  case Intrinsic::x86_avx2_psrlv_q_256:
9742  case Intrinsic::x86_avx2_psrav_d:
9743  case Intrinsic::x86_avx2_psrav_d_256: {
9744    unsigned Opcode;
9745    switch (IntNo) {
9746    default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
9747    case Intrinsic::x86_avx2_psllv_d:
9748    case Intrinsic::x86_avx2_psllv_q:
9749    case Intrinsic::x86_avx2_psllv_d_256:
9750    case Intrinsic::x86_avx2_psllv_q_256:
9751      Opcode = ISD::SHL;
9752      break;
9753    case Intrinsic::x86_avx2_psrlv_d:
9754    case Intrinsic::x86_avx2_psrlv_q:
9755    case Intrinsic::x86_avx2_psrlv_d_256:
9756    case Intrinsic::x86_avx2_psrlv_q_256:
9757      Opcode = ISD::SRL;
9758      break;
9759    case Intrinsic::x86_avx2_psrav_d:
9760    case Intrinsic::x86_avx2_psrav_d_256:
9761      Opcode = ISD::SRA;
9762      break;
9763    }
9764    return DAG.getNode(Opcode, dl, Op.getValueType(),
9765                       Op.getOperand(1), Op.getOperand(2));
9766  }
9767
9768  case Intrinsic::x86_ssse3_pshuf_b_128:
9769  case Intrinsic::x86_avx2_pshuf_b:
9770    return DAG.getNode(X86ISD::PSHUFB, dl, Op.getValueType(),
9771                       Op.getOperand(1), Op.getOperand(2));
9772
9773  case Intrinsic::x86_ssse3_psign_b_128:
9774  case Intrinsic::x86_ssse3_psign_w_128:
9775  case Intrinsic::x86_ssse3_psign_d_128:
9776  case Intrinsic::x86_avx2_psign_b:
9777  case Intrinsic::x86_avx2_psign_w:
9778  case Intrinsic::x86_avx2_psign_d:
9779    return DAG.getNode(X86ISD::PSIGN, dl, Op.getValueType(),
9780                       Op.getOperand(1), Op.getOperand(2));
9781
9782  case Intrinsic::x86_sse41_insertps:
9783    return DAG.getNode(X86ISD::INSERTPS, dl, Op.getValueType(),
9784                       Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
9785
9786  case Intrinsic::x86_avx_vperm2f128_ps_256:
9787  case Intrinsic::x86_avx_vperm2f128_pd_256:
9788  case Intrinsic::x86_avx_vperm2f128_si_256:
9789  case Intrinsic::x86_avx2_vperm2i128:
9790    return DAG.getNode(X86ISD::VPERM2X128, dl, Op.getValueType(),
9791                       Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
9792
9793  case Intrinsic::x86_avx2_permd:
9794  case Intrinsic::x86_avx2_permps:
9795    // Operands intentionally swapped. Mask is last operand to intrinsic,
9796    // but second operand for node/intruction.
9797    return DAG.getNode(X86ISD::VPERMV, dl, Op.getValueType(),
9798                       Op.getOperand(2), Op.getOperand(1));
9799
9800  // ptest and testp intrinsics. The intrinsic these come from are designed to
9801  // return an integer value, not just an instruction so lower it to the ptest
9802  // or testp pattern and a setcc for the result.
9803  case Intrinsic::x86_sse41_ptestz:
9804  case Intrinsic::x86_sse41_ptestc:
9805  case Intrinsic::x86_sse41_ptestnzc:
9806  case Intrinsic::x86_avx_ptestz_256:
9807  case Intrinsic::x86_avx_ptestc_256:
9808  case Intrinsic::x86_avx_ptestnzc_256:
9809  case Intrinsic::x86_avx_vtestz_ps:
9810  case Intrinsic::x86_avx_vtestc_ps:
9811  case Intrinsic::x86_avx_vtestnzc_ps:
9812  case Intrinsic::x86_avx_vtestz_pd:
9813  case Intrinsic::x86_avx_vtestc_pd:
9814  case Intrinsic::x86_avx_vtestnzc_pd:
9815  case Intrinsic::x86_avx_vtestz_ps_256:
9816  case Intrinsic::x86_avx_vtestc_ps_256:
9817  case Intrinsic::x86_avx_vtestnzc_ps_256:
9818  case Intrinsic::x86_avx_vtestz_pd_256:
9819  case Intrinsic::x86_avx_vtestc_pd_256:
9820  case Intrinsic::x86_avx_vtestnzc_pd_256: {
9821    bool IsTestPacked = false;
9822    unsigned X86CC;
9823    switch (IntNo) {
9824    default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
9825    case Intrinsic::x86_avx_vtestz_ps:
9826    case Intrinsic::x86_avx_vtestz_pd:
9827    case Intrinsic::x86_avx_vtestz_ps_256:
9828    case Intrinsic::x86_avx_vtestz_pd_256:
9829      IsTestPacked = true; // Fallthrough
9830    case Intrinsic::x86_sse41_ptestz:
9831    case Intrinsic::x86_avx_ptestz_256:
9832      // ZF = 1
9833      X86CC = X86::COND_E;
9834      break;
9835    case Intrinsic::x86_avx_vtestc_ps:
9836    case Intrinsic::x86_avx_vtestc_pd:
9837    case Intrinsic::x86_avx_vtestc_ps_256:
9838    case Intrinsic::x86_avx_vtestc_pd_256:
9839      IsTestPacked = true; // Fallthrough
9840    case Intrinsic::x86_sse41_ptestc:
9841    case Intrinsic::x86_avx_ptestc_256:
9842      // CF = 1
9843      X86CC = X86::COND_B;
9844      break;
9845    case Intrinsic::x86_avx_vtestnzc_ps:
9846    case Intrinsic::x86_avx_vtestnzc_pd:
9847    case Intrinsic::x86_avx_vtestnzc_ps_256:
9848    case Intrinsic::x86_avx_vtestnzc_pd_256:
9849      IsTestPacked = true; // Fallthrough
9850    case Intrinsic::x86_sse41_ptestnzc:
9851    case Intrinsic::x86_avx_ptestnzc_256:
9852      // ZF and CF = 0
9853      X86CC = X86::COND_A;
9854      break;
9855    }
9856
9857    SDValue LHS = Op.getOperand(1);
9858    SDValue RHS = Op.getOperand(2);
9859    unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
9860    SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
9861    SDValue CC = DAG.getConstant(X86CC, MVT::i8);
9862    SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
9863    return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
9864  }
9865
9866  // SSE/AVX shift intrinsics
9867  case Intrinsic::x86_sse2_psll_w:
9868  case Intrinsic::x86_sse2_psll_d:
9869  case Intrinsic::x86_sse2_psll_q:
9870  case Intrinsic::x86_avx2_psll_w:
9871  case Intrinsic::x86_avx2_psll_d:
9872  case Intrinsic::x86_avx2_psll_q:
9873  case Intrinsic::x86_sse2_psrl_w:
9874  case Intrinsic::x86_sse2_psrl_d:
9875  case Intrinsic::x86_sse2_psrl_q:
9876  case Intrinsic::x86_avx2_psrl_w:
9877  case Intrinsic::x86_avx2_psrl_d:
9878  case Intrinsic::x86_avx2_psrl_q:
9879  case Intrinsic::x86_sse2_psra_w:
9880  case Intrinsic::x86_sse2_psra_d:
9881  case Intrinsic::x86_avx2_psra_w:
9882  case Intrinsic::x86_avx2_psra_d: {
9883    unsigned Opcode;
9884    switch (IntNo) {
9885    default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
9886    case Intrinsic::x86_sse2_psll_w:
9887    case Intrinsic::x86_sse2_psll_d:
9888    case Intrinsic::x86_sse2_psll_q:
9889    case Intrinsic::x86_avx2_psll_w:
9890    case Intrinsic::x86_avx2_psll_d:
9891    case Intrinsic::x86_avx2_psll_q:
9892      Opcode = X86ISD::VSHL;
9893      break;
9894    case Intrinsic::x86_sse2_psrl_w:
9895    case Intrinsic::x86_sse2_psrl_d:
9896    case Intrinsic::x86_sse2_psrl_q:
9897    case Intrinsic::x86_avx2_psrl_w:
9898    case Intrinsic::x86_avx2_psrl_d:
9899    case Intrinsic::x86_avx2_psrl_q:
9900      Opcode = X86ISD::VSRL;
9901      break;
9902    case Intrinsic::x86_sse2_psra_w:
9903    case Intrinsic::x86_sse2_psra_d:
9904    case Intrinsic::x86_avx2_psra_w:
9905    case Intrinsic::x86_avx2_psra_d:
9906      Opcode = X86ISD::VSRA;
9907      break;
9908    }
9909    return DAG.getNode(Opcode, dl, Op.getValueType(),
9910                       Op.getOperand(1), Op.getOperand(2));
9911  }
9912
9913  // SSE/AVX immediate shift intrinsics
9914  case Intrinsic::x86_sse2_pslli_w:
9915  case Intrinsic::x86_sse2_pslli_d:
9916  case Intrinsic::x86_sse2_pslli_q:
9917  case Intrinsic::x86_avx2_pslli_w:
9918  case Intrinsic::x86_avx2_pslli_d:
9919  case Intrinsic::x86_avx2_pslli_q:
9920  case Intrinsic::x86_sse2_psrli_w:
9921  case Intrinsic::x86_sse2_psrli_d:
9922  case Intrinsic::x86_sse2_psrli_q:
9923  case Intrinsic::x86_avx2_psrli_w:
9924  case Intrinsic::x86_avx2_psrli_d:
9925  case Intrinsic::x86_avx2_psrli_q:
9926  case Intrinsic::x86_sse2_psrai_w:
9927  case Intrinsic::x86_sse2_psrai_d:
9928  case Intrinsic::x86_avx2_psrai_w:
9929  case Intrinsic::x86_avx2_psrai_d: {
9930    unsigned Opcode;
9931    switch (IntNo) {
9932    default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
9933    case Intrinsic::x86_sse2_pslli_w:
9934    case Intrinsic::x86_sse2_pslli_d:
9935    case Intrinsic::x86_sse2_pslli_q:
9936    case Intrinsic::x86_avx2_pslli_w:
9937    case Intrinsic::x86_avx2_pslli_d:
9938    case Intrinsic::x86_avx2_pslli_q:
9939      Opcode = X86ISD::VSHLI;
9940      break;
9941    case Intrinsic::x86_sse2_psrli_w:
9942    case Intrinsic::x86_sse2_psrli_d:
9943    case Intrinsic::x86_sse2_psrli_q:
9944    case Intrinsic::x86_avx2_psrli_w:
9945    case Intrinsic::x86_avx2_psrli_d:
9946    case Intrinsic::x86_avx2_psrli_q:
9947      Opcode = X86ISD::VSRLI;
9948      break;
9949    case Intrinsic::x86_sse2_psrai_w:
9950    case Intrinsic::x86_sse2_psrai_d:
9951    case Intrinsic::x86_avx2_psrai_w:
9952    case Intrinsic::x86_avx2_psrai_d:
9953      Opcode = X86ISD::VSRAI;
9954      break;
9955    }
9956    return getTargetVShiftNode(Opcode, dl, Op.getValueType(),
9957                               Op.getOperand(1), Op.getOperand(2), DAG);
9958  }
9959
9960  case Intrinsic::x86_sse42_pcmpistria128:
9961  case Intrinsic::x86_sse42_pcmpestria128:
9962  case Intrinsic::x86_sse42_pcmpistric128:
9963  case Intrinsic::x86_sse42_pcmpestric128:
9964  case Intrinsic::x86_sse42_pcmpistrio128:
9965  case Intrinsic::x86_sse42_pcmpestrio128:
9966  case Intrinsic::x86_sse42_pcmpistris128:
9967  case Intrinsic::x86_sse42_pcmpestris128:
9968  case Intrinsic::x86_sse42_pcmpistriz128:
9969  case Intrinsic::x86_sse42_pcmpestriz128: {
9970    unsigned Opcode;
9971    unsigned X86CC;
9972    switch (IntNo) {
9973    default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
9974    case Intrinsic::x86_sse42_pcmpistria128:
9975      Opcode = X86ISD::PCMPISTRI;
9976      X86CC = X86::COND_A;
9977      break;
9978    case Intrinsic::x86_sse42_pcmpestria128:
9979      Opcode = X86ISD::PCMPESTRI;
9980      X86CC = X86::COND_A;
9981      break;
9982    case Intrinsic::x86_sse42_pcmpistric128:
9983      Opcode = X86ISD::PCMPISTRI;
9984      X86CC = X86::COND_B;
9985      break;
9986    case Intrinsic::x86_sse42_pcmpestric128:
9987      Opcode = X86ISD::PCMPESTRI;
9988      X86CC = X86::COND_B;
9989      break;
9990    case Intrinsic::x86_sse42_pcmpistrio128:
9991      Opcode = X86ISD::PCMPISTRI;
9992      X86CC = X86::COND_O;
9993      break;
9994    case Intrinsic::x86_sse42_pcmpestrio128:
9995      Opcode = X86ISD::PCMPESTRI;
9996      X86CC = X86::COND_O;
9997      break;
9998    case Intrinsic::x86_sse42_pcmpistris128:
9999      Opcode = X86ISD::PCMPISTRI;
10000      X86CC = X86::COND_S;
10001      break;
10002    case Intrinsic::x86_sse42_pcmpestris128:
10003      Opcode = X86ISD::PCMPESTRI;
10004      X86CC = X86::COND_S;
10005      break;
10006    case Intrinsic::x86_sse42_pcmpistriz128:
10007      Opcode = X86ISD::PCMPISTRI;
10008      X86CC = X86::COND_E;
10009      break;
10010    case Intrinsic::x86_sse42_pcmpestriz128:
10011      Opcode = X86ISD::PCMPESTRI;
10012      X86CC = X86::COND_E;
10013      break;
10014    }
10015    SmallVector<SDValue, 5> NewOps;
10016    NewOps.append(Op->op_begin()+1, Op->op_end());
10017    SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
10018    SDValue PCMP = DAG.getNode(Opcode, dl, VTs, NewOps.data(), NewOps.size());
10019    SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
10020                                DAG.getConstant(X86CC, MVT::i8),
10021                                SDValue(PCMP.getNode(), 1));
10022    return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
10023  }
10024
10025  case Intrinsic::x86_sse42_pcmpistri128:
10026  case Intrinsic::x86_sse42_pcmpestri128: {
10027    unsigned Opcode;
10028    if (IntNo == Intrinsic::x86_sse42_pcmpistri128)
10029      Opcode = X86ISD::PCMPISTRI;
10030    else
10031      Opcode = X86ISD::PCMPESTRI;
10032
10033    SmallVector<SDValue, 5> NewOps;
10034    NewOps.append(Op->op_begin()+1, Op->op_end());
10035    SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
10036    return DAG.getNode(Opcode, dl, VTs, NewOps.data(), NewOps.size());
10037  }
10038  case Intrinsic::x86_fma_vfmadd_ps:
10039  case Intrinsic::x86_fma_vfmadd_pd:
10040  case Intrinsic::x86_fma_vfmsub_ps:
10041  case Intrinsic::x86_fma_vfmsub_pd:
10042  case Intrinsic::x86_fma_vfnmadd_ps:
10043  case Intrinsic::x86_fma_vfnmadd_pd:
10044  case Intrinsic::x86_fma_vfnmsub_ps:
10045  case Intrinsic::x86_fma_vfnmsub_pd:
10046  case Intrinsic::x86_fma_vfmaddsub_ps:
10047  case Intrinsic::x86_fma_vfmaddsub_pd:
10048  case Intrinsic::x86_fma_vfmsubadd_ps:
10049  case Intrinsic::x86_fma_vfmsubadd_pd:
10050  case Intrinsic::x86_fma_vfmadd_ps_256:
10051  case Intrinsic::x86_fma_vfmadd_pd_256:
10052  case Intrinsic::x86_fma_vfmsub_ps_256:
10053  case Intrinsic::x86_fma_vfmsub_pd_256:
10054  case Intrinsic::x86_fma_vfnmadd_ps_256:
10055  case Intrinsic::x86_fma_vfnmadd_pd_256:
10056  case Intrinsic::x86_fma_vfnmsub_ps_256:
10057  case Intrinsic::x86_fma_vfnmsub_pd_256:
10058  case Intrinsic::x86_fma_vfmaddsub_ps_256:
10059  case Intrinsic::x86_fma_vfmaddsub_pd_256:
10060  case Intrinsic::x86_fma_vfmsubadd_ps_256:
10061  case Intrinsic::x86_fma_vfmsubadd_pd_256: {
10062    unsigned Opc;
10063    switch (IntNo) {
10064    default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
10065    case Intrinsic::x86_fma_vfmadd_ps:
10066    case Intrinsic::x86_fma_vfmadd_pd:
10067    case Intrinsic::x86_fma_vfmadd_ps_256:
10068    case Intrinsic::x86_fma_vfmadd_pd_256:
10069      Opc = X86ISD::FMADD;
10070      break;
10071    case Intrinsic::x86_fma_vfmsub_ps:
10072    case Intrinsic::x86_fma_vfmsub_pd:
10073    case Intrinsic::x86_fma_vfmsub_ps_256:
10074    case Intrinsic::x86_fma_vfmsub_pd_256:
10075      Opc = X86ISD::FMSUB;
10076      break;
10077    case Intrinsic::x86_fma_vfnmadd_ps:
10078    case Intrinsic::x86_fma_vfnmadd_pd:
10079    case Intrinsic::x86_fma_vfnmadd_ps_256:
10080    case Intrinsic::x86_fma_vfnmadd_pd_256:
10081      Opc = X86ISD::FNMADD;
10082      break;
10083    case Intrinsic::x86_fma_vfnmsub_ps:
10084    case Intrinsic::x86_fma_vfnmsub_pd:
10085    case Intrinsic::x86_fma_vfnmsub_ps_256:
10086    case Intrinsic::x86_fma_vfnmsub_pd_256:
10087      Opc = X86ISD::FNMSUB;
10088      break;
10089    case Intrinsic::x86_fma_vfmaddsub_ps:
10090    case Intrinsic::x86_fma_vfmaddsub_pd:
10091    case Intrinsic::x86_fma_vfmaddsub_ps_256:
10092    case Intrinsic::x86_fma_vfmaddsub_pd_256:
10093      Opc = X86ISD::FMADDSUB;
10094      break;
10095    case Intrinsic::x86_fma_vfmsubadd_ps:
10096    case Intrinsic::x86_fma_vfmsubadd_pd:
10097    case Intrinsic::x86_fma_vfmsubadd_ps_256:
10098    case Intrinsic::x86_fma_vfmsubadd_pd_256:
10099      Opc = X86ISD::FMSUBADD;
10100      break;
10101    }
10102
10103    return DAG.getNode(Opc, dl, Op.getValueType(), Op.getOperand(1),
10104                       Op.getOperand(2), Op.getOperand(3));
10105  }
10106  }
10107}
10108
10109SDValue
10110X86TargetLowering::LowerINTRINSIC_W_CHAIN(SDValue Op, SelectionDAG &DAG) const {
10111  DebugLoc dl = Op.getDebugLoc();
10112  unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10113  switch (IntNo) {
10114  default: return SDValue();    // Don't custom lower most intrinsics.
10115
10116  // RDRAND intrinsics.
10117  case Intrinsic::x86_rdrand_16:
10118  case Intrinsic::x86_rdrand_32:
10119  case Intrinsic::x86_rdrand_64: {
10120    // Emit the node with the right value type.
10121    SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Glue, MVT::Other);
10122    SDValue Result = DAG.getNode(X86ISD::RDRAND, dl, VTs, Op.getOperand(0));
10123
10124    // If the value returned by RDRAND was valid (CF=1), return 1. Otherwise
10125    // return the value from Rand, which is always 0, casted to i32.
10126    SDValue Ops[] = { DAG.getZExtOrTrunc(Result, dl, Op->getValueType(1)),
10127                      DAG.getConstant(1, Op->getValueType(1)),
10128                      DAG.getConstant(X86::COND_B, MVT::i32),
10129                      SDValue(Result.getNode(), 1) };
10130    SDValue isValid = DAG.getNode(X86ISD::CMOV, dl,
10131                                  DAG.getVTList(Op->getValueType(1), MVT::Glue),
10132                                  Ops, 4);
10133
10134    // Return { result, isValid, chain }.
10135    return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), Result, isValid,
10136                       SDValue(Result.getNode(), 2));
10137  }
10138  }
10139}
10140
10141SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
10142                                           SelectionDAG &DAG) const {
10143  MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
10144  MFI->setReturnAddressIsTaken(true);
10145
10146  unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
10147  DebugLoc dl = Op.getDebugLoc();
10148
10149  if (Depth > 0) {
10150    SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
10151    SDValue Offset =
10152      DAG.getConstant(TD->getPointerSize(),
10153                      Subtarget->is64Bit() ? MVT::i64 : MVT::i32);
10154    return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
10155                       DAG.getNode(ISD::ADD, dl, getPointerTy(),
10156                                   FrameAddr, Offset),
10157                       MachinePointerInfo(), false, false, false, 0);
10158  }
10159
10160  // Just load the return address.
10161  SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
10162  return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
10163                     RetAddrFI, MachinePointerInfo(), false, false, false, 0);
10164}
10165
10166SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
10167  MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
10168  MFI->setFrameAddressIsTaken(true);
10169
10170  EVT VT = Op.getValueType();
10171  DebugLoc dl = Op.getDebugLoc();  // FIXME probably not meaningful
10172  unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
10173  unsigned FrameReg = Subtarget->is64Bit() ? X86::RBP : X86::EBP;
10174  SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
10175  while (Depth--)
10176    FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
10177                            MachinePointerInfo(),
10178                            false, false, false, 0);
10179  return FrameAddr;
10180}
10181
10182SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
10183                                                     SelectionDAG &DAG) const {
10184  return DAG.getIntPtrConstant(2*TD->getPointerSize());
10185}
10186
10187SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
10188  SDValue Chain     = Op.getOperand(0);
10189  SDValue Offset    = Op.getOperand(1);
10190  SDValue Handler   = Op.getOperand(2);
10191  DebugLoc dl       = Op.getDebugLoc();
10192
10193  SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl,
10194                                     Subtarget->is64Bit() ? X86::RBP : X86::EBP,
10195                                     getPointerTy());
10196  unsigned StoreAddrReg = (Subtarget->is64Bit() ? X86::RCX : X86::ECX);
10197
10198  SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), Frame,
10199                                  DAG.getIntPtrConstant(TD->getPointerSize()));
10200  StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), StoreAddr, Offset);
10201  Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
10202                       false, false, 0);
10203  Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
10204
10205  return DAG.getNode(X86ISD::EH_RETURN, dl,
10206                     MVT::Other,
10207                     Chain, DAG.getRegister(StoreAddrReg, getPointerTy()));
10208}
10209
10210SDValue X86TargetLowering::LowerADJUST_TRAMPOLINE(SDValue Op,
10211                                                  SelectionDAG &DAG) const {
10212  return Op.getOperand(0);
10213}
10214
10215SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
10216                                                SelectionDAG &DAG) const {
10217  SDValue Root = Op.getOperand(0);
10218  SDValue Trmp = Op.getOperand(1); // trampoline
10219  SDValue FPtr = Op.getOperand(2); // nested function
10220  SDValue Nest = Op.getOperand(3); // 'nest' parameter value
10221  DebugLoc dl  = Op.getDebugLoc();
10222
10223  const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
10224
10225  if (Subtarget->is64Bit()) {
10226    SDValue OutChains[6];
10227
10228    // Large code-model.
10229    const unsigned char JMP64r  = 0xFF; // 64-bit jmp through register opcode.
10230    const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
10231
10232    const unsigned char N86R10 = X86_MC::getX86RegNum(X86::R10);
10233    const unsigned char N86R11 = X86_MC::getX86RegNum(X86::R11);
10234
10235    const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
10236
10237    // Load the pointer to the nested function into R11.
10238    unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
10239    SDValue Addr = Trmp;
10240    OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
10241                                Addr, MachinePointerInfo(TrmpAddr),
10242                                false, false, 0);
10243
10244    Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
10245                       DAG.getConstant(2, MVT::i64));
10246    OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
10247                                MachinePointerInfo(TrmpAddr, 2),
10248                                false, false, 2);
10249
10250    // Load the 'nest' parameter value into R10.
10251    // R10 is specified in X86CallingConv.td
10252    OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
10253    Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
10254                       DAG.getConstant(10, MVT::i64));
10255    OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
10256                                Addr, MachinePointerInfo(TrmpAddr, 10),
10257                                false, false, 0);
10258
10259    Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
10260                       DAG.getConstant(12, MVT::i64));
10261    OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
10262                                MachinePointerInfo(TrmpAddr, 12),
10263                                false, false, 2);
10264
10265    // Jump to the nested function.
10266    OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
10267    Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
10268                       DAG.getConstant(20, MVT::i64));
10269    OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
10270                                Addr, MachinePointerInfo(TrmpAddr, 20),
10271                                false, false, 0);
10272
10273    unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
10274    Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
10275                       DAG.getConstant(22, MVT::i64));
10276    OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
10277                                MachinePointerInfo(TrmpAddr, 22),
10278                                false, false, 0);
10279
10280    return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 6);
10281  } else {
10282    const Function *Func =
10283      cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
10284    CallingConv::ID CC = Func->getCallingConv();
10285    unsigned NestReg;
10286
10287    switch (CC) {
10288    default:
10289      llvm_unreachable("Unsupported calling convention");
10290    case CallingConv::C:
10291    case CallingConv::X86_StdCall: {
10292      // Pass 'nest' parameter in ECX.
10293      // Must be kept in sync with X86CallingConv.td
10294      NestReg = X86::ECX;
10295
10296      // Check that ECX wasn't needed by an 'inreg' parameter.
10297      FunctionType *FTy = Func->getFunctionType();
10298      const AttrListPtr &Attrs = Func->getAttributes();
10299
10300      if (!Attrs.isEmpty() && !Func->isVarArg()) {
10301        unsigned InRegCount = 0;
10302        unsigned Idx = 1;
10303
10304        for (FunctionType::param_iterator I = FTy->param_begin(),
10305             E = FTy->param_end(); I != E; ++I, ++Idx)
10306          if (Attrs.paramHasAttr(Idx, Attribute::InReg))
10307            // FIXME: should only count parameters that are lowered to integers.
10308            InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
10309
10310        if (InRegCount > 2) {
10311          report_fatal_error("Nest register in use - reduce number of inreg"
10312                             " parameters!");
10313        }
10314      }
10315      break;
10316    }
10317    case CallingConv::X86_FastCall:
10318    case CallingConv::X86_ThisCall:
10319    case CallingConv::Fast:
10320      // Pass 'nest' parameter in EAX.
10321      // Must be kept in sync with X86CallingConv.td
10322      NestReg = X86::EAX;
10323      break;
10324    }
10325
10326    SDValue OutChains[4];
10327    SDValue Addr, Disp;
10328
10329    Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
10330                       DAG.getConstant(10, MVT::i32));
10331    Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
10332
10333    // This is storing the opcode for MOV32ri.
10334    const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
10335    const unsigned char N86Reg = X86_MC::getX86RegNum(NestReg);
10336    OutChains[0] = DAG.getStore(Root, dl,
10337                                DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
10338                                Trmp, MachinePointerInfo(TrmpAddr),
10339                                false, false, 0);
10340
10341    Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
10342                       DAG.getConstant(1, MVT::i32));
10343    OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
10344                                MachinePointerInfo(TrmpAddr, 1),
10345                                false, false, 1);
10346
10347    const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
10348    Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
10349                       DAG.getConstant(5, MVT::i32));
10350    OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
10351                                MachinePointerInfo(TrmpAddr, 5),
10352                                false, false, 1);
10353
10354    Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
10355                       DAG.getConstant(6, MVT::i32));
10356    OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
10357                                MachinePointerInfo(TrmpAddr, 6),
10358                                false, false, 1);
10359
10360    return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 4);
10361  }
10362}
10363
10364SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
10365                                            SelectionDAG &DAG) const {
10366  /*
10367   The rounding mode is in bits 11:10 of FPSR, and has the following
10368   settings:
10369     00 Round to nearest
10370     01 Round to -inf
10371     10 Round to +inf
10372     11 Round to 0
10373
10374  FLT_ROUNDS, on the other hand, expects the following:
10375    -1 Undefined
10376     0 Round to 0
10377     1 Round to nearest
10378     2 Round to +inf
10379     3 Round to -inf
10380
10381  To perform the conversion, we do:
10382    (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
10383  */
10384
10385  MachineFunction &MF = DAG.getMachineFunction();
10386  const TargetMachine &TM = MF.getTarget();
10387  const TargetFrameLowering &TFI = *TM.getFrameLowering();
10388  unsigned StackAlignment = TFI.getStackAlignment();
10389  EVT VT = Op.getValueType();
10390  DebugLoc DL = Op.getDebugLoc();
10391
10392  // Save FP Control Word to stack slot
10393  int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
10394  SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
10395
10396
10397  MachineMemOperand *MMO =
10398   MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
10399                           MachineMemOperand::MOStore, 2, 2);
10400
10401  SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
10402  SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
10403                                          DAG.getVTList(MVT::Other),
10404                                          Ops, 2, MVT::i16, MMO);
10405
10406  // Load FP Control Word from stack slot
10407  SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
10408                            MachinePointerInfo(), false, false, false, 0);
10409
10410  // Transform as necessary
10411  SDValue CWD1 =
10412    DAG.getNode(ISD::SRL, DL, MVT::i16,
10413                DAG.getNode(ISD::AND, DL, MVT::i16,
10414                            CWD, DAG.getConstant(0x800, MVT::i16)),
10415                DAG.getConstant(11, MVT::i8));
10416  SDValue CWD2 =
10417    DAG.getNode(ISD::SRL, DL, MVT::i16,
10418                DAG.getNode(ISD::AND, DL, MVT::i16,
10419                            CWD, DAG.getConstant(0x400, MVT::i16)),
10420                DAG.getConstant(9, MVT::i8));
10421
10422  SDValue RetVal =
10423    DAG.getNode(ISD::AND, DL, MVT::i16,
10424                DAG.getNode(ISD::ADD, DL, MVT::i16,
10425                            DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
10426                            DAG.getConstant(1, MVT::i16)),
10427                DAG.getConstant(3, MVT::i16));
10428
10429
10430  return DAG.getNode((VT.getSizeInBits() < 16 ?
10431                      ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
10432}
10433
10434SDValue X86TargetLowering::LowerCTLZ(SDValue Op, SelectionDAG &DAG) const {
10435  EVT VT = Op.getValueType();
10436  EVT OpVT = VT;
10437  unsigned NumBits = VT.getSizeInBits();
10438  DebugLoc dl = Op.getDebugLoc();
10439
10440  Op = Op.getOperand(0);
10441  if (VT == MVT::i8) {
10442    // Zero extend to i32 since there is not an i8 bsr.
10443    OpVT = MVT::i32;
10444    Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
10445  }
10446
10447  // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
10448  SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
10449  Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
10450
10451  // If src is zero (i.e. bsr sets ZF), returns NumBits.
10452  SDValue Ops[] = {
10453    Op,
10454    DAG.getConstant(NumBits+NumBits-1, OpVT),
10455    DAG.getConstant(X86::COND_E, MVT::i8),
10456    Op.getValue(1)
10457  };
10458  Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
10459
10460  // Finally xor with NumBits-1.
10461  Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
10462
10463  if (VT == MVT::i8)
10464    Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
10465  return Op;
10466}
10467
10468SDValue X86TargetLowering::LowerCTLZ_ZERO_UNDEF(SDValue Op,
10469                                                SelectionDAG &DAG) const {
10470  EVT VT = Op.getValueType();
10471  EVT OpVT = VT;
10472  unsigned NumBits = VT.getSizeInBits();
10473  DebugLoc dl = Op.getDebugLoc();
10474
10475  Op = Op.getOperand(0);
10476  if (VT == MVT::i8) {
10477    // Zero extend to i32 since there is not an i8 bsr.
10478    OpVT = MVT::i32;
10479    Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
10480  }
10481
10482  // Issue a bsr (scan bits in reverse).
10483  SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
10484  Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
10485
10486  // And xor with NumBits-1.
10487  Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
10488
10489  if (VT == MVT::i8)
10490    Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
10491  return Op;
10492}
10493
10494SDValue X86TargetLowering::LowerCTTZ(SDValue Op, SelectionDAG &DAG) const {
10495  EVT VT = Op.getValueType();
10496  unsigned NumBits = VT.getSizeInBits();
10497  DebugLoc dl = Op.getDebugLoc();
10498  Op = Op.getOperand(0);
10499
10500  // Issue a bsf (scan bits forward) which also sets EFLAGS.
10501  SDVTList VTs = DAG.getVTList(VT, MVT::i32);
10502  Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
10503
10504  // If src is zero (i.e. bsf sets ZF), returns NumBits.
10505  SDValue Ops[] = {
10506    Op,
10507    DAG.getConstant(NumBits, VT),
10508    DAG.getConstant(X86::COND_E, MVT::i8),
10509    Op.getValue(1)
10510  };
10511  return DAG.getNode(X86ISD::CMOV, dl, VT, Ops, array_lengthof(Ops));
10512}
10513
10514// Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
10515// ones, and then concatenate the result back.
10516static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
10517  EVT VT = Op.getValueType();
10518
10519  assert(VT.is256BitVector() && VT.isInteger() &&
10520         "Unsupported value type for operation");
10521
10522  unsigned NumElems = VT.getVectorNumElements();
10523  DebugLoc dl = Op.getDebugLoc();
10524
10525  // Extract the LHS vectors
10526  SDValue LHS = Op.getOperand(0);
10527  SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
10528  SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
10529
10530  // Extract the RHS vectors
10531  SDValue RHS = Op.getOperand(1);
10532  SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
10533  SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
10534
10535  MVT EltVT = VT.getVectorElementType().getSimpleVT();
10536  EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
10537
10538  return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
10539                     DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
10540                     DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
10541}
10542
10543SDValue X86TargetLowering::LowerADD(SDValue Op, SelectionDAG &DAG) const {
10544  assert(Op.getValueType().is256BitVector() &&
10545         Op.getValueType().isInteger() &&
10546         "Only handle AVX 256-bit vector integer operation");
10547  return Lower256IntArith(Op, DAG);
10548}
10549
10550SDValue X86TargetLowering::LowerSUB(SDValue Op, SelectionDAG &DAG) const {
10551  assert(Op.getValueType().is256BitVector() &&
10552         Op.getValueType().isInteger() &&
10553         "Only handle AVX 256-bit vector integer operation");
10554  return Lower256IntArith(Op, DAG);
10555}
10556
10557SDValue X86TargetLowering::LowerMUL(SDValue Op, SelectionDAG &DAG) const {
10558  EVT VT = Op.getValueType();
10559
10560  // Decompose 256-bit ops into smaller 128-bit ops.
10561  if (VT.is256BitVector() && !Subtarget->hasAVX2())
10562    return Lower256IntArith(Op, DAG);
10563
10564  assert((VT == MVT::v2i64 || VT == MVT::v4i64) &&
10565         "Only know how to lower V2I64/V4I64 multiply");
10566
10567  DebugLoc dl = Op.getDebugLoc();
10568
10569  //  Ahi = psrlqi(a, 32);
10570  //  Bhi = psrlqi(b, 32);
10571  //
10572  //  AloBlo = pmuludq(a, b);
10573  //  AloBhi = pmuludq(a, Bhi);
10574  //  AhiBlo = pmuludq(Ahi, b);
10575
10576  //  AloBhi = psllqi(AloBhi, 32);
10577  //  AhiBlo = psllqi(AhiBlo, 32);
10578  //  return AloBlo + AloBhi + AhiBlo;
10579
10580  SDValue A = Op.getOperand(0);
10581  SDValue B = Op.getOperand(1);
10582
10583  SDValue ShAmt = DAG.getConstant(32, MVT::i32);
10584
10585  SDValue Ahi = DAG.getNode(X86ISD::VSRLI, dl, VT, A, ShAmt);
10586  SDValue Bhi = DAG.getNode(X86ISD::VSRLI, dl, VT, B, ShAmt);
10587
10588  // Bit cast to 32-bit vectors for MULUDQ
10589  EVT MulVT = (VT == MVT::v2i64) ? MVT::v4i32 : MVT::v8i32;
10590  A = DAG.getNode(ISD::BITCAST, dl, MulVT, A);
10591  B = DAG.getNode(ISD::BITCAST, dl, MulVT, B);
10592  Ahi = DAG.getNode(ISD::BITCAST, dl, MulVT, Ahi);
10593  Bhi = DAG.getNode(ISD::BITCAST, dl, MulVT, Bhi);
10594
10595  SDValue AloBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, B);
10596  SDValue AloBhi = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, Bhi);
10597  SDValue AhiBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, Ahi, B);
10598
10599  AloBhi = DAG.getNode(X86ISD::VSHLI, dl, VT, AloBhi, ShAmt);
10600  AhiBlo = DAG.getNode(X86ISD::VSHLI, dl, VT, AhiBlo, ShAmt);
10601
10602  SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
10603  return DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
10604}
10605
10606SDValue X86TargetLowering::LowerShift(SDValue Op, SelectionDAG &DAG) const {
10607
10608  EVT VT = Op.getValueType();
10609  DebugLoc dl = Op.getDebugLoc();
10610  SDValue R = Op.getOperand(0);
10611  SDValue Amt = Op.getOperand(1);
10612  LLVMContext *Context = DAG.getContext();
10613
10614  if (!Subtarget->hasSSE2())
10615    return SDValue();
10616
10617  // Optimize shl/srl/sra with constant shift amount.
10618  if (isSplatVector(Amt.getNode())) {
10619    SDValue SclrAmt = Amt->getOperand(0);
10620    if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt)) {
10621      uint64_t ShiftAmt = C->getZExtValue();
10622
10623      if (VT == MVT::v2i64 || VT == MVT::v4i32 || VT == MVT::v8i16 ||
10624          (Subtarget->hasAVX2() &&
10625           (VT == MVT::v4i64 || VT == MVT::v8i32 || VT == MVT::v16i16))) {
10626        if (Op.getOpcode() == ISD::SHL)
10627          return DAG.getNode(X86ISD::VSHLI, dl, VT, R,
10628                             DAG.getConstant(ShiftAmt, MVT::i32));
10629        if (Op.getOpcode() == ISD::SRL)
10630          return DAG.getNode(X86ISD::VSRLI, dl, VT, R,
10631                             DAG.getConstant(ShiftAmt, MVT::i32));
10632        if (Op.getOpcode() == ISD::SRA && VT != MVT::v2i64 && VT != MVT::v4i64)
10633          return DAG.getNode(X86ISD::VSRAI, dl, VT, R,
10634                             DAG.getConstant(ShiftAmt, MVT::i32));
10635      }
10636
10637      if (VT == MVT::v16i8) {
10638        if (Op.getOpcode() == ISD::SHL) {
10639          // Make a large shift.
10640          SDValue SHL = DAG.getNode(X86ISD::VSHLI, dl, MVT::v8i16, R,
10641                                    DAG.getConstant(ShiftAmt, MVT::i32));
10642          SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
10643          // Zero out the rightmost bits.
10644          SmallVector<SDValue, 16> V(16,
10645                                     DAG.getConstant(uint8_t(-1U << ShiftAmt),
10646                                                     MVT::i8));
10647          return DAG.getNode(ISD::AND, dl, VT, SHL,
10648                             DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16));
10649        }
10650        if (Op.getOpcode() == ISD::SRL) {
10651          // Make a large shift.
10652          SDValue SRL = DAG.getNode(X86ISD::VSRLI, dl, MVT::v8i16, R,
10653                                    DAG.getConstant(ShiftAmt, MVT::i32));
10654          SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
10655          // Zero out the leftmost bits.
10656          SmallVector<SDValue, 16> V(16,
10657                                     DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
10658                                                     MVT::i8));
10659          return DAG.getNode(ISD::AND, dl, VT, SRL,
10660                             DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16));
10661        }
10662        if (Op.getOpcode() == ISD::SRA) {
10663          if (ShiftAmt == 7) {
10664            // R s>> 7  ===  R s< 0
10665            SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
10666            return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
10667          }
10668
10669          // R s>> a === ((R u>> a) ^ m) - m
10670          SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
10671          SmallVector<SDValue, 16> V(16, DAG.getConstant(128 >> ShiftAmt,
10672                                                         MVT::i8));
10673          SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16);
10674          Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
10675          Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
10676          return Res;
10677        }
10678        llvm_unreachable("Unknown shift opcode.");
10679      }
10680
10681      if (Subtarget->hasAVX2() && VT == MVT::v32i8) {
10682        if (Op.getOpcode() == ISD::SHL) {
10683          // Make a large shift.
10684          SDValue SHL = DAG.getNode(X86ISD::VSHLI, dl, MVT::v16i16, R,
10685                                    DAG.getConstant(ShiftAmt, MVT::i32));
10686          SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
10687          // Zero out the rightmost bits.
10688          SmallVector<SDValue, 32> V(32,
10689                                     DAG.getConstant(uint8_t(-1U << ShiftAmt),
10690                                                     MVT::i8));
10691          return DAG.getNode(ISD::AND, dl, VT, SHL,
10692                             DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32));
10693        }
10694        if (Op.getOpcode() == ISD::SRL) {
10695          // Make a large shift.
10696          SDValue SRL = DAG.getNode(X86ISD::VSRLI, dl, MVT::v16i16, R,
10697                                    DAG.getConstant(ShiftAmt, MVT::i32));
10698          SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
10699          // Zero out the leftmost bits.
10700          SmallVector<SDValue, 32> V(32,
10701                                     DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
10702                                                     MVT::i8));
10703          return DAG.getNode(ISD::AND, dl, VT, SRL,
10704                             DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32));
10705        }
10706        if (Op.getOpcode() == ISD::SRA) {
10707          if (ShiftAmt == 7) {
10708            // R s>> 7  ===  R s< 0
10709            SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
10710            return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
10711          }
10712
10713          // R s>> a === ((R u>> a) ^ m) - m
10714          SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
10715          SmallVector<SDValue, 32> V(32, DAG.getConstant(128 >> ShiftAmt,
10716                                                         MVT::i8));
10717          SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32);
10718          Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
10719          Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
10720          return Res;
10721        }
10722        llvm_unreachable("Unknown shift opcode.");
10723      }
10724    }
10725  }
10726
10727  // Lower SHL with variable shift amount.
10728  if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
10729    Op = DAG.getNode(X86ISD::VSHLI, dl, VT, Op.getOperand(1),
10730                     DAG.getConstant(23, MVT::i32));
10731
10732    const uint32_t CV[] = { 0x3f800000U, 0x3f800000U, 0x3f800000U, 0x3f800000U};
10733    Constant *C = ConstantDataVector::get(*Context, CV);
10734    SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
10735    SDValue Addend = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
10736                                 MachinePointerInfo::getConstantPool(),
10737                                 false, false, false, 16);
10738
10739    Op = DAG.getNode(ISD::ADD, dl, VT, Op, Addend);
10740    Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, Op);
10741    Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
10742    return DAG.getNode(ISD::MUL, dl, VT, Op, R);
10743  }
10744  if (VT == MVT::v16i8 && Op->getOpcode() == ISD::SHL) {
10745    assert(Subtarget->hasSSE2() && "Need SSE2 for pslli/pcmpeq.");
10746
10747    // a = a << 5;
10748    Op = DAG.getNode(X86ISD::VSHLI, dl, MVT::v8i16, Op.getOperand(1),
10749                     DAG.getConstant(5, MVT::i32));
10750    Op = DAG.getNode(ISD::BITCAST, dl, VT, Op);
10751
10752    // Turn 'a' into a mask suitable for VSELECT
10753    SDValue VSelM = DAG.getConstant(0x80, VT);
10754    SDValue OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
10755    OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
10756
10757    SDValue CM1 = DAG.getConstant(0x0f, VT);
10758    SDValue CM2 = DAG.getConstant(0x3f, VT);
10759
10760    // r = VSELECT(r, psllw(r & (char16)15, 4), a);
10761    SDValue M = DAG.getNode(ISD::AND, dl, VT, R, CM1);
10762    M = getTargetVShiftNode(X86ISD::VSHLI, dl, MVT::v8i16, M,
10763                            DAG.getConstant(4, MVT::i32), DAG);
10764    M = DAG.getNode(ISD::BITCAST, dl, VT, M);
10765    R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
10766
10767    // a += a
10768    Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
10769    OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
10770    OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
10771
10772    // r = VSELECT(r, psllw(r & (char16)63, 2), a);
10773    M = DAG.getNode(ISD::AND, dl, VT, R, CM2);
10774    M = getTargetVShiftNode(X86ISD::VSHLI, dl, MVT::v8i16, M,
10775                            DAG.getConstant(2, MVT::i32), DAG);
10776    M = DAG.getNode(ISD::BITCAST, dl, VT, M);
10777    R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
10778
10779    // a += a
10780    Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
10781    OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
10782    OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
10783
10784    // return VSELECT(r, r+r, a);
10785    R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel,
10786                    DAG.getNode(ISD::ADD, dl, VT, R, R), R);
10787    return R;
10788  }
10789
10790  // Decompose 256-bit shifts into smaller 128-bit shifts.
10791  if (VT.is256BitVector()) {
10792    unsigned NumElems = VT.getVectorNumElements();
10793    MVT EltVT = VT.getVectorElementType().getSimpleVT();
10794    EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
10795
10796    // Extract the two vectors
10797    SDValue V1 = Extract128BitVector(R, 0, DAG, dl);
10798    SDValue V2 = Extract128BitVector(R, NumElems/2, DAG, dl);
10799
10800    // Recreate the shift amount vectors
10801    SDValue Amt1, Amt2;
10802    if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
10803      // Constant shift amount
10804      SmallVector<SDValue, 4> Amt1Csts;
10805      SmallVector<SDValue, 4> Amt2Csts;
10806      for (unsigned i = 0; i != NumElems/2; ++i)
10807        Amt1Csts.push_back(Amt->getOperand(i));
10808      for (unsigned i = NumElems/2; i != NumElems; ++i)
10809        Amt2Csts.push_back(Amt->getOperand(i));
10810
10811      Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT,
10812                                 &Amt1Csts[0], NumElems/2);
10813      Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT,
10814                                 &Amt2Csts[0], NumElems/2);
10815    } else {
10816      // Variable shift amount
10817      Amt1 = Extract128BitVector(Amt, 0, DAG, dl);
10818      Amt2 = Extract128BitVector(Amt, NumElems/2, DAG, dl);
10819    }
10820
10821    // Issue new vector shifts for the smaller types
10822    V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
10823    V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
10824
10825    // Concatenate the result back
10826    return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
10827  }
10828
10829  return SDValue();
10830}
10831
10832SDValue X86TargetLowering::LowerXALUO(SDValue Op, SelectionDAG &DAG) const {
10833  // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
10834  // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
10835  // looks for this combo and may remove the "setcc" instruction if the "setcc"
10836  // has only one use.
10837  SDNode *N = Op.getNode();
10838  SDValue LHS = N->getOperand(0);
10839  SDValue RHS = N->getOperand(1);
10840  unsigned BaseOp = 0;
10841  unsigned Cond = 0;
10842  DebugLoc DL = Op.getDebugLoc();
10843  switch (Op.getOpcode()) {
10844  default: llvm_unreachable("Unknown ovf instruction!");
10845  case ISD::SADDO:
10846    // A subtract of one will be selected as a INC. Note that INC doesn't
10847    // set CF, so we can't do this for UADDO.
10848    if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
10849      if (C->isOne()) {
10850        BaseOp = X86ISD::INC;
10851        Cond = X86::COND_O;
10852        break;
10853      }
10854    BaseOp = X86ISD::ADD;
10855    Cond = X86::COND_O;
10856    break;
10857  case ISD::UADDO:
10858    BaseOp = X86ISD::ADD;
10859    Cond = X86::COND_B;
10860    break;
10861  case ISD::SSUBO:
10862    // A subtract of one will be selected as a DEC. Note that DEC doesn't
10863    // set CF, so we can't do this for USUBO.
10864    if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
10865      if (C->isOne()) {
10866        BaseOp = X86ISD::DEC;
10867        Cond = X86::COND_O;
10868        break;
10869      }
10870    BaseOp = X86ISD::SUB;
10871    Cond = X86::COND_O;
10872    break;
10873  case ISD::USUBO:
10874    BaseOp = X86ISD::SUB;
10875    Cond = X86::COND_B;
10876    break;
10877  case ISD::SMULO:
10878    BaseOp = X86ISD::SMUL;
10879    Cond = X86::COND_O;
10880    break;
10881  case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
10882    SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
10883                                 MVT::i32);
10884    SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
10885
10886    SDValue SetCC =
10887      DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
10888                  DAG.getConstant(X86::COND_O, MVT::i32),
10889                  SDValue(Sum.getNode(), 2));
10890
10891    return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
10892  }
10893  }
10894
10895  // Also sets EFLAGS.
10896  SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
10897  SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
10898
10899  SDValue SetCC =
10900    DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
10901                DAG.getConstant(Cond, MVT::i32),
10902                SDValue(Sum.getNode(), 1));
10903
10904  return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
10905}
10906
10907SDValue X86TargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op,
10908                                                  SelectionDAG &DAG) const {
10909  DebugLoc dl = Op.getDebugLoc();
10910  EVT ExtraVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
10911  EVT VT = Op.getValueType();
10912
10913  if (!Subtarget->hasSSE2() || !VT.isVector())
10914    return SDValue();
10915
10916  unsigned BitsDiff = VT.getScalarType().getSizeInBits() -
10917                      ExtraVT.getScalarType().getSizeInBits();
10918  SDValue ShAmt = DAG.getConstant(BitsDiff, MVT::i32);
10919
10920  switch (VT.getSimpleVT().SimpleTy) {
10921    default: return SDValue();
10922    case MVT::v8i32:
10923    case MVT::v16i16:
10924      if (!Subtarget->hasAVX())
10925        return SDValue();
10926      if (!Subtarget->hasAVX2()) {
10927        // needs to be split
10928        unsigned NumElems = VT.getVectorNumElements();
10929
10930        // Extract the LHS vectors
10931        SDValue LHS = Op.getOperand(0);
10932        SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
10933        SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
10934
10935        MVT EltVT = VT.getVectorElementType().getSimpleVT();
10936        EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
10937
10938        EVT ExtraEltVT = ExtraVT.getVectorElementType();
10939        unsigned ExtraNumElems = ExtraVT.getVectorNumElements();
10940        ExtraVT = EVT::getVectorVT(*DAG.getContext(), ExtraEltVT,
10941                                   ExtraNumElems/2);
10942        SDValue Extra = DAG.getValueType(ExtraVT);
10943
10944        LHS1 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, Extra);
10945        LHS2 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, Extra);
10946
10947        return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, LHS1, LHS2);;
10948      }
10949      // fall through
10950    case MVT::v4i32:
10951    case MVT::v8i16: {
10952      SDValue Tmp1 = getTargetVShiftNode(X86ISD::VSHLI, dl, VT,
10953                                         Op.getOperand(0), ShAmt, DAG);
10954      return getTargetVShiftNode(X86ISD::VSRAI, dl, VT, Tmp1, ShAmt, DAG);
10955    }
10956  }
10957}
10958
10959
10960SDValue X86TargetLowering::LowerMEMBARRIER(SDValue Op, SelectionDAG &DAG) const{
10961  DebugLoc dl = Op.getDebugLoc();
10962
10963  // Go ahead and emit the fence on x86-64 even if we asked for no-sse2.
10964  // There isn't any reason to disable it if the target processor supports it.
10965  if (!Subtarget->hasSSE2() && !Subtarget->is64Bit()) {
10966    SDValue Chain = Op.getOperand(0);
10967    SDValue Zero = DAG.getConstant(0, MVT::i32);
10968    SDValue Ops[] = {
10969      DAG.getRegister(X86::ESP, MVT::i32), // Base
10970      DAG.getTargetConstant(1, MVT::i8),   // Scale
10971      DAG.getRegister(0, MVT::i32),        // Index
10972      DAG.getTargetConstant(0, MVT::i32),  // Disp
10973      DAG.getRegister(0, MVT::i32),        // Segment.
10974      Zero,
10975      Chain
10976    };
10977    SDNode *Res =
10978      DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops,
10979                          array_lengthof(Ops));
10980    return SDValue(Res, 0);
10981  }
10982
10983  unsigned isDev = cast<ConstantSDNode>(Op.getOperand(5))->getZExtValue();
10984  if (!isDev)
10985    return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
10986
10987  unsigned Op1 = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10988  unsigned Op2 = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
10989  unsigned Op3 = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue();
10990  unsigned Op4 = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
10991
10992  // def : Pat<(membarrier (i8 0), (i8 0), (i8 0), (i8 1), (i8 1)), (SFENCE)>;
10993  if (!Op1 && !Op2 && !Op3 && Op4)
10994    return DAG.getNode(X86ISD::SFENCE, dl, MVT::Other, Op.getOperand(0));
10995
10996  // def : Pat<(membarrier (i8 1), (i8 0), (i8 0), (i8 0), (i8 1)), (LFENCE)>;
10997  if (Op1 && !Op2 && !Op3 && !Op4)
10998    return DAG.getNode(X86ISD::LFENCE, dl, MVT::Other, Op.getOperand(0));
10999
11000  // def : Pat<(membarrier (i8 imm), (i8 imm), (i8 imm), (i8 imm), (i8 1)),
11001  //           (MFENCE)>;
11002  return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
11003}
11004
11005SDValue X86TargetLowering::LowerATOMIC_FENCE(SDValue Op,
11006                                             SelectionDAG &DAG) const {
11007  DebugLoc dl = Op.getDebugLoc();
11008  AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
11009    cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
11010  SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
11011    cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
11012
11013  // The only fence that needs an instruction is a sequentially-consistent
11014  // cross-thread fence.
11015  if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
11016    // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
11017    // no-sse2). There isn't any reason to disable it if the target processor
11018    // supports it.
11019    if (Subtarget->hasSSE2() || Subtarget->is64Bit())
11020      return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
11021
11022    SDValue Chain = Op.getOperand(0);
11023    SDValue Zero = DAG.getConstant(0, MVT::i32);
11024    SDValue Ops[] = {
11025      DAG.getRegister(X86::ESP, MVT::i32), // Base
11026      DAG.getTargetConstant(1, MVT::i8),   // Scale
11027      DAG.getRegister(0, MVT::i32),        // Index
11028      DAG.getTargetConstant(0, MVT::i32),  // Disp
11029      DAG.getRegister(0, MVT::i32),        // Segment.
11030      Zero,
11031      Chain
11032    };
11033    SDNode *Res =
11034      DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops,
11035                         array_lengthof(Ops));
11036    return SDValue(Res, 0);
11037  }
11038
11039  // MEMBARRIER is a compiler barrier; it codegens to a no-op.
11040  return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
11041}
11042
11043
11044SDValue X86TargetLowering::LowerCMP_SWAP(SDValue Op, SelectionDAG &DAG) const {
11045  EVT T = Op.getValueType();
11046  DebugLoc DL = Op.getDebugLoc();
11047  unsigned Reg = 0;
11048  unsigned size = 0;
11049  switch(T.getSimpleVT().SimpleTy) {
11050  default: llvm_unreachable("Invalid value type!");
11051  case MVT::i8:  Reg = X86::AL;  size = 1; break;
11052  case MVT::i16: Reg = X86::AX;  size = 2; break;
11053  case MVT::i32: Reg = X86::EAX; size = 4; break;
11054  case MVT::i64:
11055    assert(Subtarget->is64Bit() && "Node not type legal!");
11056    Reg = X86::RAX; size = 8;
11057    break;
11058  }
11059  SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
11060                                    Op.getOperand(2), SDValue());
11061  SDValue Ops[] = { cpIn.getValue(0),
11062                    Op.getOperand(1),
11063                    Op.getOperand(3),
11064                    DAG.getTargetConstant(size, MVT::i8),
11065                    cpIn.getValue(1) };
11066  SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
11067  MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
11068  SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
11069                                           Ops, 5, T, MMO);
11070  SDValue cpOut =
11071    DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
11072  return cpOut;
11073}
11074
11075SDValue X86TargetLowering::LowerREADCYCLECOUNTER(SDValue Op,
11076                                                 SelectionDAG &DAG) const {
11077  assert(Subtarget->is64Bit() && "Result not type legalized?");
11078  SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
11079  SDValue TheChain = Op.getOperand(0);
11080  DebugLoc dl = Op.getDebugLoc();
11081  SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
11082  SDValue rax = DAG.getCopyFromReg(rd, dl, X86::RAX, MVT::i64, rd.getValue(1));
11083  SDValue rdx = DAG.getCopyFromReg(rax.getValue(1), dl, X86::RDX, MVT::i64,
11084                                   rax.getValue(2));
11085  SDValue Tmp = DAG.getNode(ISD::SHL, dl, MVT::i64, rdx,
11086                            DAG.getConstant(32, MVT::i8));
11087  SDValue Ops[] = {
11088    DAG.getNode(ISD::OR, dl, MVT::i64, rax, Tmp),
11089    rdx.getValue(1)
11090  };
11091  return DAG.getMergeValues(Ops, 2, dl);
11092}
11093
11094SDValue X86TargetLowering::LowerBITCAST(SDValue Op,
11095                                            SelectionDAG &DAG) const {
11096  EVT SrcVT = Op.getOperand(0).getValueType();
11097  EVT DstVT = Op.getValueType();
11098  assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
11099         Subtarget->hasMMX() && "Unexpected custom BITCAST");
11100  assert((DstVT == MVT::i64 ||
11101          (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
11102         "Unexpected custom BITCAST");
11103  // i64 <=> MMX conversions are Legal.
11104  if (SrcVT==MVT::i64 && DstVT.isVector())
11105    return Op;
11106  if (DstVT==MVT::i64 && SrcVT.isVector())
11107    return Op;
11108  // MMX <=> MMX conversions are Legal.
11109  if (SrcVT.isVector() && DstVT.isVector())
11110    return Op;
11111  // All other conversions need to be expanded.
11112  return SDValue();
11113}
11114
11115SDValue X86TargetLowering::LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) const {
11116  SDNode *Node = Op.getNode();
11117  DebugLoc dl = Node->getDebugLoc();
11118  EVT T = Node->getValueType(0);
11119  SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
11120                              DAG.getConstant(0, T), Node->getOperand(2));
11121  return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
11122                       cast<AtomicSDNode>(Node)->getMemoryVT(),
11123                       Node->getOperand(0),
11124                       Node->getOperand(1), negOp,
11125                       cast<AtomicSDNode>(Node)->getSrcValue(),
11126                       cast<AtomicSDNode>(Node)->getAlignment(),
11127                       cast<AtomicSDNode>(Node)->getOrdering(),
11128                       cast<AtomicSDNode>(Node)->getSynchScope());
11129}
11130
11131static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
11132  SDNode *Node = Op.getNode();
11133  DebugLoc dl = Node->getDebugLoc();
11134  EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
11135
11136  // Convert seq_cst store -> xchg
11137  // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
11138  // FIXME: On 32-bit, store -> fist or movq would be more efficient
11139  //        (The only way to get a 16-byte store is cmpxchg16b)
11140  // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
11141  if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
11142      !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
11143    SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
11144                                 cast<AtomicSDNode>(Node)->getMemoryVT(),
11145                                 Node->getOperand(0),
11146                                 Node->getOperand(1), Node->getOperand(2),
11147                                 cast<AtomicSDNode>(Node)->getMemOperand(),
11148                                 cast<AtomicSDNode>(Node)->getOrdering(),
11149                                 cast<AtomicSDNode>(Node)->getSynchScope());
11150    return Swap.getValue(1);
11151  }
11152  // Other atomic stores have a simple pattern.
11153  return Op;
11154}
11155
11156static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
11157  EVT VT = Op.getNode()->getValueType(0);
11158
11159  // Let legalize expand this if it isn't a legal type yet.
11160  if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
11161    return SDValue();
11162
11163  SDVTList VTs = DAG.getVTList(VT, MVT::i32);
11164
11165  unsigned Opc;
11166  bool ExtraOp = false;
11167  switch (Op.getOpcode()) {
11168  default: llvm_unreachable("Invalid code");
11169  case ISD::ADDC: Opc = X86ISD::ADD; break;
11170  case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
11171  case ISD::SUBC: Opc = X86ISD::SUB; break;
11172  case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
11173  }
11174
11175  if (!ExtraOp)
11176    return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
11177                       Op.getOperand(1));
11178  return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
11179                     Op.getOperand(1), Op.getOperand(2));
11180}
11181
11182/// LowerOperation - Provide custom lowering hooks for some operations.
11183///
11184SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
11185  switch (Op.getOpcode()) {
11186  default: llvm_unreachable("Should not custom lower this!");
11187  case ISD::SIGN_EXTEND_INREG:  return LowerSIGN_EXTEND_INREG(Op,DAG);
11188  case ISD::MEMBARRIER:         return LowerMEMBARRIER(Op,DAG);
11189  case ISD::ATOMIC_FENCE:       return LowerATOMIC_FENCE(Op,DAG);
11190  case ISD::ATOMIC_CMP_SWAP:    return LowerCMP_SWAP(Op,DAG);
11191  case ISD::ATOMIC_LOAD_SUB:    return LowerLOAD_SUB(Op,DAG);
11192  case ISD::ATOMIC_STORE:       return LowerATOMIC_STORE(Op,DAG);
11193  case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
11194  case ISD::CONCAT_VECTORS:     return LowerCONCAT_VECTORS(Op, DAG);
11195  case ISD::VECTOR_SHUFFLE:     return LowerVECTOR_SHUFFLE(Op, DAG);
11196  case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
11197  case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
11198  case ISD::EXTRACT_SUBVECTOR:  return LowerEXTRACT_SUBVECTOR(Op, DAG);
11199  case ISD::INSERT_SUBVECTOR:   return LowerINSERT_SUBVECTOR(Op, DAG);
11200  case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
11201  case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
11202  case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
11203  case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
11204  case ISD::ExternalSymbol:     return LowerExternalSymbol(Op, DAG);
11205  case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
11206  case ISD::SHL_PARTS:
11207  case ISD::SRA_PARTS:
11208  case ISD::SRL_PARTS:          return LowerShiftParts(Op, DAG);
11209  case ISD::SINT_TO_FP:         return LowerSINT_TO_FP(Op, DAG);
11210  case ISD::UINT_TO_FP:         return LowerUINT_TO_FP(Op, DAG);
11211  case ISD::FP_TO_SINT:         return LowerFP_TO_SINT(Op, DAG);
11212  case ISD::FP_TO_UINT:         return LowerFP_TO_UINT(Op, DAG);
11213  case ISD::FABS:               return LowerFABS(Op, DAG);
11214  case ISD::FNEG:               return LowerFNEG(Op, DAG);
11215  case ISD::FCOPYSIGN:          return LowerFCOPYSIGN(Op, DAG);
11216  case ISD::FGETSIGN:           return LowerFGETSIGN(Op, DAG);
11217  case ISD::SETCC:              return LowerSETCC(Op, DAG);
11218  case ISD::SELECT:             return LowerSELECT(Op, DAG);
11219  case ISD::BRCOND:             return LowerBRCOND(Op, DAG);
11220  case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
11221  case ISD::VASTART:            return LowerVASTART(Op, DAG);
11222  case ISD::VAARG:              return LowerVAARG(Op, DAG);
11223  case ISD::VACOPY:             return LowerVACOPY(Op, DAG);
11224  case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
11225  case ISD::INTRINSIC_W_CHAIN:  return LowerINTRINSIC_W_CHAIN(Op, DAG);
11226  case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
11227  case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
11228  case ISD::FRAME_TO_ARGS_OFFSET:
11229                                return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
11230  case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
11231  case ISD::EH_RETURN:          return LowerEH_RETURN(Op, DAG);
11232  case ISD::INIT_TRAMPOLINE:    return LowerINIT_TRAMPOLINE(Op, DAG);
11233  case ISD::ADJUST_TRAMPOLINE:  return LowerADJUST_TRAMPOLINE(Op, DAG);
11234  case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
11235  case ISD::CTLZ:               return LowerCTLZ(Op, DAG);
11236  case ISD::CTLZ_ZERO_UNDEF:    return LowerCTLZ_ZERO_UNDEF(Op, DAG);
11237  case ISD::CTTZ:               return LowerCTTZ(Op, DAG);
11238  case ISD::MUL:                return LowerMUL(Op, DAG);
11239  case ISD::SRA:
11240  case ISD::SRL:
11241  case ISD::SHL:                return LowerShift(Op, DAG);
11242  case ISD::SADDO:
11243  case ISD::UADDO:
11244  case ISD::SSUBO:
11245  case ISD::USUBO:
11246  case ISD::SMULO:
11247  case ISD::UMULO:              return LowerXALUO(Op, DAG);
11248  case ISD::READCYCLECOUNTER:   return LowerREADCYCLECOUNTER(Op, DAG);
11249  case ISD::BITCAST:            return LowerBITCAST(Op, DAG);
11250  case ISD::ADDC:
11251  case ISD::ADDE:
11252  case ISD::SUBC:
11253  case ISD::SUBE:               return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
11254  case ISD::ADD:                return LowerADD(Op, DAG);
11255  case ISD::SUB:                return LowerSUB(Op, DAG);
11256  }
11257}
11258
11259static void ReplaceATOMIC_LOAD(SDNode *Node,
11260                                  SmallVectorImpl<SDValue> &Results,
11261                                  SelectionDAG &DAG) {
11262  DebugLoc dl = Node->getDebugLoc();
11263  EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
11264
11265  // Convert wide load -> cmpxchg8b/cmpxchg16b
11266  // FIXME: On 32-bit, load -> fild or movq would be more efficient
11267  //        (The only way to get a 16-byte load is cmpxchg16b)
11268  // FIXME: 16-byte ATOMIC_CMP_SWAP isn't actually hooked up at the moment.
11269  SDValue Zero = DAG.getConstant(0, VT);
11270  SDValue Swap = DAG.getAtomic(ISD::ATOMIC_CMP_SWAP, dl, VT,
11271                               Node->getOperand(0),
11272                               Node->getOperand(1), Zero, Zero,
11273                               cast<AtomicSDNode>(Node)->getMemOperand(),
11274                               cast<AtomicSDNode>(Node)->getOrdering(),
11275                               cast<AtomicSDNode>(Node)->getSynchScope());
11276  Results.push_back(Swap.getValue(0));
11277  Results.push_back(Swap.getValue(1));
11278}
11279
11280static void
11281ReplaceATOMIC_BINARY_64(SDNode *Node, SmallVectorImpl<SDValue>&Results,
11282                        SelectionDAG &DAG, unsigned NewOp) {
11283  DebugLoc dl = Node->getDebugLoc();
11284  assert (Node->getValueType(0) == MVT::i64 &&
11285          "Only know how to expand i64 atomics");
11286
11287  SDValue Chain = Node->getOperand(0);
11288  SDValue In1 = Node->getOperand(1);
11289  SDValue In2L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
11290                             Node->getOperand(2), DAG.getIntPtrConstant(0));
11291  SDValue In2H = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
11292                             Node->getOperand(2), DAG.getIntPtrConstant(1));
11293  SDValue Ops[] = { Chain, In1, In2L, In2H };
11294  SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
11295  SDValue Result =
11296    DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops, 4, MVT::i64,
11297                            cast<MemSDNode>(Node)->getMemOperand());
11298  SDValue OpsF[] = { Result.getValue(0), Result.getValue(1)};
11299  Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
11300  Results.push_back(Result.getValue(2));
11301}
11302
11303/// ReplaceNodeResults - Replace a node with an illegal result type
11304/// with a new node built out of custom code.
11305void X86TargetLowering::ReplaceNodeResults(SDNode *N,
11306                                           SmallVectorImpl<SDValue>&Results,
11307                                           SelectionDAG &DAG) const {
11308  DebugLoc dl = N->getDebugLoc();
11309  switch (N->getOpcode()) {
11310  default:
11311    llvm_unreachable("Do not know how to custom type legalize this operation!");
11312  case ISD::SIGN_EXTEND_INREG:
11313  case ISD::ADDC:
11314  case ISD::ADDE:
11315  case ISD::SUBC:
11316  case ISD::SUBE:
11317    // We don't want to expand or promote these.
11318    return;
11319  case ISD::FP_TO_SINT:
11320  case ISD::FP_TO_UINT: {
11321    bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
11322
11323    if (!IsSigned && !isIntegerTypeFTOL(SDValue(N, 0).getValueType()))
11324      return;
11325
11326    std::pair<SDValue,SDValue> Vals =
11327        FP_TO_INTHelper(SDValue(N, 0), DAG, IsSigned, /*IsReplace=*/ true);
11328    SDValue FIST = Vals.first, StackSlot = Vals.second;
11329    if (FIST.getNode() != 0) {
11330      EVT VT = N->getValueType(0);
11331      // Return a load from the stack slot.
11332      if (StackSlot.getNode() != 0)
11333        Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
11334                                      MachinePointerInfo(),
11335                                      false, false, false, 0));
11336      else
11337        Results.push_back(FIST);
11338    }
11339    return;
11340  }
11341  case ISD::READCYCLECOUNTER: {
11342    SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
11343    SDValue TheChain = N->getOperand(0);
11344    SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
11345    SDValue eax = DAG.getCopyFromReg(rd, dl, X86::EAX, MVT::i32,
11346                                     rd.getValue(1));
11347    SDValue edx = DAG.getCopyFromReg(eax.getValue(1), dl, X86::EDX, MVT::i32,
11348                                     eax.getValue(2));
11349    // Use a buildpair to merge the two 32-bit values into a 64-bit one.
11350    SDValue Ops[] = { eax, edx };
11351    Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Ops, 2));
11352    Results.push_back(edx.getValue(1));
11353    return;
11354  }
11355  case ISD::ATOMIC_CMP_SWAP: {
11356    EVT T = N->getValueType(0);
11357    assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
11358    bool Regs64bit = T == MVT::i128;
11359    EVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
11360    SDValue cpInL, cpInH;
11361    cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
11362                        DAG.getConstant(0, HalfT));
11363    cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
11364                        DAG.getConstant(1, HalfT));
11365    cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
11366                             Regs64bit ? X86::RAX : X86::EAX,
11367                             cpInL, SDValue());
11368    cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
11369                             Regs64bit ? X86::RDX : X86::EDX,
11370                             cpInH, cpInL.getValue(1));
11371    SDValue swapInL, swapInH;
11372    swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
11373                          DAG.getConstant(0, HalfT));
11374    swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
11375                          DAG.getConstant(1, HalfT));
11376    swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
11377                               Regs64bit ? X86::RBX : X86::EBX,
11378                               swapInL, cpInH.getValue(1));
11379    swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
11380                               Regs64bit ? X86::RCX : X86::ECX,
11381                               swapInH, swapInL.getValue(1));
11382    SDValue Ops[] = { swapInH.getValue(0),
11383                      N->getOperand(1),
11384                      swapInH.getValue(1) };
11385    SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
11386    MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
11387    unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
11388                                  X86ISD::LCMPXCHG8_DAG;
11389    SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys,
11390                                             Ops, 3, T, MMO);
11391    SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
11392                                        Regs64bit ? X86::RAX : X86::EAX,
11393                                        HalfT, Result.getValue(1));
11394    SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
11395                                        Regs64bit ? X86::RDX : X86::EDX,
11396                                        HalfT, cpOutL.getValue(2));
11397    SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
11398    Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF, 2));
11399    Results.push_back(cpOutH.getValue(1));
11400    return;
11401  }
11402  case ISD::ATOMIC_LOAD_ADD:
11403  case ISD::ATOMIC_LOAD_AND:
11404  case ISD::ATOMIC_LOAD_NAND:
11405  case ISD::ATOMIC_LOAD_OR:
11406  case ISD::ATOMIC_LOAD_SUB:
11407  case ISD::ATOMIC_LOAD_XOR:
11408  case ISD::ATOMIC_SWAP: {
11409    unsigned Opc;
11410    switch (N->getOpcode()) {
11411    default: llvm_unreachable("Unexpected opcode");
11412    case ISD::ATOMIC_LOAD_ADD:
11413      Opc = X86ISD::ATOMADD64_DAG;
11414      break;
11415    case ISD::ATOMIC_LOAD_AND:
11416      Opc = X86ISD::ATOMAND64_DAG;
11417      break;
11418    case ISD::ATOMIC_LOAD_NAND:
11419      Opc = X86ISD::ATOMNAND64_DAG;
11420      break;
11421    case ISD::ATOMIC_LOAD_OR:
11422      Opc = X86ISD::ATOMOR64_DAG;
11423      break;
11424    case ISD::ATOMIC_LOAD_SUB:
11425      Opc = X86ISD::ATOMSUB64_DAG;
11426      break;
11427    case ISD::ATOMIC_LOAD_XOR:
11428      Opc = X86ISD::ATOMXOR64_DAG;
11429      break;
11430    case ISD::ATOMIC_SWAP:
11431      Opc = X86ISD::ATOMSWAP64_DAG;
11432      break;
11433    }
11434    ReplaceATOMIC_BINARY_64(N, Results, DAG, Opc);
11435    return;
11436  }
11437  case ISD::ATOMIC_LOAD:
11438    ReplaceATOMIC_LOAD(N, Results, DAG);
11439  }
11440}
11441
11442const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
11443  switch (Opcode) {
11444  default: return NULL;
11445  case X86ISD::BSF:                return "X86ISD::BSF";
11446  case X86ISD::BSR:                return "X86ISD::BSR";
11447  case X86ISD::SHLD:               return "X86ISD::SHLD";
11448  case X86ISD::SHRD:               return "X86ISD::SHRD";
11449  case X86ISD::FAND:               return "X86ISD::FAND";
11450  case X86ISD::FOR:                return "X86ISD::FOR";
11451  case X86ISD::FXOR:               return "X86ISD::FXOR";
11452  case X86ISD::FSRL:               return "X86ISD::FSRL";
11453  case X86ISD::FILD:               return "X86ISD::FILD";
11454  case X86ISD::FILD_FLAG:          return "X86ISD::FILD_FLAG";
11455  case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
11456  case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
11457  case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
11458  case X86ISD::FLD:                return "X86ISD::FLD";
11459  case X86ISD::FST:                return "X86ISD::FST";
11460  case X86ISD::CALL:               return "X86ISD::CALL";
11461  case X86ISD::RDTSC_DAG:          return "X86ISD::RDTSC_DAG";
11462  case X86ISD::BT:                 return "X86ISD::BT";
11463  case X86ISD::CMP:                return "X86ISD::CMP";
11464  case X86ISD::COMI:               return "X86ISD::COMI";
11465  case X86ISD::UCOMI:              return "X86ISD::UCOMI";
11466  case X86ISD::SETCC:              return "X86ISD::SETCC";
11467  case X86ISD::SETCC_CARRY:        return "X86ISD::SETCC_CARRY";
11468  case X86ISD::FSETCCsd:           return "X86ISD::FSETCCsd";
11469  case X86ISD::FSETCCss:           return "X86ISD::FSETCCss";
11470  case X86ISD::CMOV:               return "X86ISD::CMOV";
11471  case X86ISD::BRCOND:             return "X86ISD::BRCOND";
11472  case X86ISD::RET_FLAG:           return "X86ISD::RET_FLAG";
11473  case X86ISD::REP_STOS:           return "X86ISD::REP_STOS";
11474  case X86ISD::REP_MOVS:           return "X86ISD::REP_MOVS";
11475  case X86ISD::GlobalBaseReg:      return "X86ISD::GlobalBaseReg";
11476  case X86ISD::Wrapper:            return "X86ISD::Wrapper";
11477  case X86ISD::WrapperRIP:         return "X86ISD::WrapperRIP";
11478  case X86ISD::PEXTRB:             return "X86ISD::PEXTRB";
11479  case X86ISD::PEXTRW:             return "X86ISD::PEXTRW";
11480  case X86ISD::INSERTPS:           return "X86ISD::INSERTPS";
11481  case X86ISD::PINSRB:             return "X86ISD::PINSRB";
11482  case X86ISD::PINSRW:             return "X86ISD::PINSRW";
11483  case X86ISD::PSHUFB:             return "X86ISD::PSHUFB";
11484  case X86ISD::ANDNP:              return "X86ISD::ANDNP";
11485  case X86ISD::PSIGN:              return "X86ISD::PSIGN";
11486  case X86ISD::BLENDV:             return "X86ISD::BLENDV";
11487  case X86ISD::BLENDPW:            return "X86ISD::BLENDPW";
11488  case X86ISD::BLENDPS:            return "X86ISD::BLENDPS";
11489  case X86ISD::BLENDPD:            return "X86ISD::BLENDPD";
11490  case X86ISD::HADD:               return "X86ISD::HADD";
11491  case X86ISD::HSUB:               return "X86ISD::HSUB";
11492  case X86ISD::FHADD:              return "X86ISD::FHADD";
11493  case X86ISD::FHSUB:              return "X86ISD::FHSUB";
11494  case X86ISD::FMAX:               return "X86ISD::FMAX";
11495  case X86ISD::FMIN:               return "X86ISD::FMIN";
11496  case X86ISD::FMAXC:              return "X86ISD::FMAXC";
11497  case X86ISD::FMINC:              return "X86ISD::FMINC";
11498  case X86ISD::FRSQRT:             return "X86ISD::FRSQRT";
11499  case X86ISD::FRCP:               return "X86ISD::FRCP";
11500  case X86ISD::TLSADDR:            return "X86ISD::TLSADDR";
11501  case X86ISD::TLSBASEADDR:        return "X86ISD::TLSBASEADDR";
11502  case X86ISD::TLSCALL:            return "X86ISD::TLSCALL";
11503  case X86ISD::EH_RETURN:          return "X86ISD::EH_RETURN";
11504  case X86ISD::TC_RETURN:          return "X86ISD::TC_RETURN";
11505  case X86ISD::FNSTCW16m:          return "X86ISD::FNSTCW16m";
11506  case X86ISD::FNSTSW16r:          return "X86ISD::FNSTSW16r";
11507  case X86ISD::LCMPXCHG_DAG:       return "X86ISD::LCMPXCHG_DAG";
11508  case X86ISD::LCMPXCHG8_DAG:      return "X86ISD::LCMPXCHG8_DAG";
11509  case X86ISD::ATOMADD64_DAG:      return "X86ISD::ATOMADD64_DAG";
11510  case X86ISD::ATOMSUB64_DAG:      return "X86ISD::ATOMSUB64_DAG";
11511  case X86ISD::ATOMOR64_DAG:       return "X86ISD::ATOMOR64_DAG";
11512  case X86ISD::ATOMXOR64_DAG:      return "X86ISD::ATOMXOR64_DAG";
11513  case X86ISD::ATOMAND64_DAG:      return "X86ISD::ATOMAND64_DAG";
11514  case X86ISD::ATOMNAND64_DAG:     return "X86ISD::ATOMNAND64_DAG";
11515  case X86ISD::VZEXT_MOVL:         return "X86ISD::VZEXT_MOVL";
11516  case X86ISD::VSEXT_MOVL:         return "X86ISD::VSEXT_MOVL";
11517  case X86ISD::VZEXT_LOAD:         return "X86ISD::VZEXT_LOAD";
11518  case X86ISD::VFPEXT:             return "X86ISD::VFPEXT";
11519  case X86ISD::VSHLDQ:             return "X86ISD::VSHLDQ";
11520  case X86ISD::VSRLDQ:             return "X86ISD::VSRLDQ";
11521  case X86ISD::VSHL:               return "X86ISD::VSHL";
11522  case X86ISD::VSRL:               return "X86ISD::VSRL";
11523  case X86ISD::VSRA:               return "X86ISD::VSRA";
11524  case X86ISD::VSHLI:              return "X86ISD::VSHLI";
11525  case X86ISD::VSRLI:              return "X86ISD::VSRLI";
11526  case X86ISD::VSRAI:              return "X86ISD::VSRAI";
11527  case X86ISD::CMPP:               return "X86ISD::CMPP";
11528  case X86ISD::PCMPEQ:             return "X86ISD::PCMPEQ";
11529  case X86ISD::PCMPGT:             return "X86ISD::PCMPGT";
11530  case X86ISD::ADD:                return "X86ISD::ADD";
11531  case X86ISD::SUB:                return "X86ISD::SUB";
11532  case X86ISD::ADC:                return "X86ISD::ADC";
11533  case X86ISD::SBB:                return "X86ISD::SBB";
11534  case X86ISD::SMUL:               return "X86ISD::SMUL";
11535  case X86ISD::UMUL:               return "X86ISD::UMUL";
11536  case X86ISD::INC:                return "X86ISD::INC";
11537  case X86ISD::DEC:                return "X86ISD::DEC";
11538  case X86ISD::OR:                 return "X86ISD::OR";
11539  case X86ISD::XOR:                return "X86ISD::XOR";
11540  case X86ISD::AND:                return "X86ISD::AND";
11541  case X86ISD::ANDN:               return "X86ISD::ANDN";
11542  case X86ISD::BLSI:               return "X86ISD::BLSI";
11543  case X86ISD::BLSMSK:             return "X86ISD::BLSMSK";
11544  case X86ISD::BLSR:               return "X86ISD::BLSR";
11545  case X86ISD::MUL_IMM:            return "X86ISD::MUL_IMM";
11546  case X86ISD::PTEST:              return "X86ISD::PTEST";
11547  case X86ISD::TESTP:              return "X86ISD::TESTP";
11548  case X86ISD::PALIGN:             return "X86ISD::PALIGN";
11549  case X86ISD::PSHUFD:             return "X86ISD::PSHUFD";
11550  case X86ISD::PSHUFHW:            return "X86ISD::PSHUFHW";
11551  case X86ISD::PSHUFLW:            return "X86ISD::PSHUFLW";
11552  case X86ISD::SHUFP:              return "X86ISD::SHUFP";
11553  case X86ISD::MOVLHPS:            return "X86ISD::MOVLHPS";
11554  case X86ISD::MOVLHPD:            return "X86ISD::MOVLHPD";
11555  case X86ISD::MOVHLPS:            return "X86ISD::MOVHLPS";
11556  case X86ISD::MOVLPS:             return "X86ISD::MOVLPS";
11557  case X86ISD::MOVLPD:             return "X86ISD::MOVLPD";
11558  case X86ISD::MOVDDUP:            return "X86ISD::MOVDDUP";
11559  case X86ISD::MOVSHDUP:           return "X86ISD::MOVSHDUP";
11560  case X86ISD::MOVSLDUP:           return "X86ISD::MOVSLDUP";
11561  case X86ISD::MOVSD:              return "X86ISD::MOVSD";
11562  case X86ISD::MOVSS:              return "X86ISD::MOVSS";
11563  case X86ISD::UNPCKL:             return "X86ISD::UNPCKL";
11564  case X86ISD::UNPCKH:             return "X86ISD::UNPCKH";
11565  case X86ISD::VBROADCAST:         return "X86ISD::VBROADCAST";
11566  case X86ISD::VPERMILP:           return "X86ISD::VPERMILP";
11567  case X86ISD::VPERM2X128:         return "X86ISD::VPERM2X128";
11568  case X86ISD::VPERMV:             return "X86ISD::VPERMV";
11569  case X86ISD::VPERMI:             return "X86ISD::VPERMI";
11570  case X86ISD::PMULUDQ:            return "X86ISD::PMULUDQ";
11571  case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
11572  case X86ISD::VAARG_64:           return "X86ISD::VAARG_64";
11573  case X86ISD::WIN_ALLOCA:         return "X86ISD::WIN_ALLOCA";
11574  case X86ISD::MEMBARRIER:         return "X86ISD::MEMBARRIER";
11575  case X86ISD::SEG_ALLOCA:         return "X86ISD::SEG_ALLOCA";
11576  case X86ISD::WIN_FTOL:           return "X86ISD::WIN_FTOL";
11577  case X86ISD::SAHF:               return "X86ISD::SAHF";
11578  case X86ISD::RDRAND:             return "X86ISD::RDRAND";
11579  case X86ISD::FMADD:              return "X86ISD::FMADD";
11580  case X86ISD::FMSUB:              return "X86ISD::FMSUB";
11581  case X86ISD::FNMADD:             return "X86ISD::FNMADD";
11582  case X86ISD::FNMSUB:             return "X86ISD::FNMSUB";
11583  case X86ISD::FMADDSUB:           return "X86ISD::FMADDSUB";
11584  case X86ISD::FMSUBADD:           return "X86ISD::FMSUBADD";
11585  }
11586}
11587
11588// isLegalAddressingMode - Return true if the addressing mode represented
11589// by AM is legal for this target, for a load/store of the specified type.
11590bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
11591                                              Type *Ty) const {
11592  // X86 supports extremely general addressing modes.
11593  CodeModel::Model M = getTargetMachine().getCodeModel();
11594  Reloc::Model R = getTargetMachine().getRelocationModel();
11595
11596  // X86 allows a sign-extended 32-bit immediate field as a displacement.
11597  if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != NULL))
11598    return false;
11599
11600  if (AM.BaseGV) {
11601    unsigned GVFlags =
11602      Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
11603
11604    // If a reference to this global requires an extra load, we can't fold it.
11605    if (isGlobalStubReference(GVFlags))
11606      return false;
11607
11608    // If BaseGV requires a register for the PIC base, we cannot also have a
11609    // BaseReg specified.
11610    if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
11611      return false;
11612
11613    // If lower 4G is not available, then we must use rip-relative addressing.
11614    if ((M != CodeModel::Small || R != Reloc::Static) &&
11615        Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
11616      return false;
11617  }
11618
11619  switch (AM.Scale) {
11620  case 0:
11621  case 1:
11622  case 2:
11623  case 4:
11624  case 8:
11625    // These scales always work.
11626    break;
11627  case 3:
11628  case 5:
11629  case 9:
11630    // These scales are formed with basereg+scalereg.  Only accept if there is
11631    // no basereg yet.
11632    if (AM.HasBaseReg)
11633      return false;
11634    break;
11635  default:  // Other stuff never works.
11636    return false;
11637  }
11638
11639  return true;
11640}
11641
11642
11643bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
11644  if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
11645    return false;
11646  unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
11647  unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
11648  if (NumBits1 <= NumBits2)
11649    return false;
11650  return true;
11651}
11652
11653bool X86TargetLowering::isLegalICmpImmediate(int64_t Imm) const {
11654  return Imm == (int32_t)Imm;
11655}
11656
11657bool X86TargetLowering::isLegalAddImmediate(int64_t Imm) const {
11658  // Can also use sub to handle negated immediates.
11659  return Imm == (int32_t)Imm;
11660}
11661
11662bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
11663  if (!VT1.isInteger() || !VT2.isInteger())
11664    return false;
11665  unsigned NumBits1 = VT1.getSizeInBits();
11666  unsigned NumBits2 = VT2.getSizeInBits();
11667  if (NumBits1 <= NumBits2)
11668    return false;
11669  return true;
11670}
11671
11672bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
11673  // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
11674  return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
11675}
11676
11677bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
11678  // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
11679  return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
11680}
11681
11682bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
11683  // i16 instructions are longer (0x66 prefix) and potentially slower.
11684  return !(VT1 == MVT::i32 && VT2 == MVT::i16);
11685}
11686
11687/// isShuffleMaskLegal - Targets can use this to indicate that they only
11688/// support *some* VECTOR_SHUFFLE operations, those with specific masks.
11689/// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
11690/// are assumed to be legal.
11691bool
11692X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
11693                                      EVT VT) const {
11694  // Very little shuffling can be done for 64-bit vectors right now.
11695  if (VT.getSizeInBits() == 64)
11696    return false;
11697
11698  // FIXME: pshufb, blends, shifts.
11699  return (VT.getVectorNumElements() == 2 ||
11700          ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
11701          isMOVLMask(M, VT) ||
11702          isSHUFPMask(M, VT, Subtarget->hasAVX()) ||
11703          isPSHUFDMask(M, VT) ||
11704          isPSHUFHWMask(M, VT, Subtarget->hasAVX2()) ||
11705          isPSHUFLWMask(M, VT, Subtarget->hasAVX2()) ||
11706          isPALIGNRMask(M, VT, Subtarget) ||
11707          isUNPCKLMask(M, VT, Subtarget->hasAVX2()) ||
11708          isUNPCKHMask(M, VT, Subtarget->hasAVX2()) ||
11709          isUNPCKL_v_undef_Mask(M, VT, Subtarget->hasAVX2()) ||
11710          isUNPCKH_v_undef_Mask(M, VT, Subtarget->hasAVX2()));
11711}
11712
11713bool
11714X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
11715                                          EVT VT) const {
11716  unsigned NumElts = VT.getVectorNumElements();
11717  // FIXME: This collection of masks seems suspect.
11718  if (NumElts == 2)
11719    return true;
11720  if (NumElts == 4 && VT.is128BitVector()) {
11721    return (isMOVLMask(Mask, VT)  ||
11722            isCommutedMOVLMask(Mask, VT, true) ||
11723            isSHUFPMask(Mask, VT, Subtarget->hasAVX()) ||
11724            isSHUFPMask(Mask, VT, Subtarget->hasAVX(), /* Commuted */ true));
11725  }
11726  return false;
11727}
11728
11729//===----------------------------------------------------------------------===//
11730//                           X86 Scheduler Hooks
11731//===----------------------------------------------------------------------===//
11732
11733// private utility function
11734MachineBasicBlock *
11735X86TargetLowering::EmitAtomicBitwiseWithCustomInserter(MachineInstr *bInstr,
11736                                                       MachineBasicBlock *MBB,
11737                                                       unsigned regOpc,
11738                                                       unsigned immOpc,
11739                                                       unsigned LoadOpc,
11740                                                       unsigned CXchgOpc,
11741                                                       unsigned notOpc,
11742                                                       unsigned EAXreg,
11743                                                 const TargetRegisterClass *RC,
11744                                                       bool Invert) const {
11745  // For the atomic bitwise operator, we generate
11746  //   thisMBB:
11747  //   newMBB:
11748  //     ld  t1 = [bitinstr.addr]
11749  //     op  t2 = t1, [bitinstr.val]
11750  //     not t3 = t2  (if Invert)
11751  //     mov EAX = t1
11752  //     lcs dest = [bitinstr.addr], t3  [EAX is implicit]
11753  //     bz  newMBB
11754  //     fallthrough -->nextMBB
11755  const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11756  const BasicBlock *LLVM_BB = MBB->getBasicBlock();
11757  MachineFunction::iterator MBBIter = MBB;
11758  ++MBBIter;
11759
11760  /// First build the CFG
11761  MachineFunction *F = MBB->getParent();
11762  MachineBasicBlock *thisMBB = MBB;
11763  MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
11764  MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
11765  F->insert(MBBIter, newMBB);
11766  F->insert(MBBIter, nextMBB);
11767
11768  // Transfer the remainder of thisMBB and its successor edges to nextMBB.
11769  nextMBB->splice(nextMBB->begin(), thisMBB,
11770                  llvm::next(MachineBasicBlock::iterator(bInstr)),
11771                  thisMBB->end());
11772  nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
11773
11774  // Update thisMBB to fall through to newMBB
11775  thisMBB->addSuccessor(newMBB);
11776
11777  // newMBB jumps to itself and fall through to nextMBB
11778  newMBB->addSuccessor(nextMBB);
11779  newMBB->addSuccessor(newMBB);
11780
11781  // Insert instructions into newMBB based on incoming instruction
11782  assert(bInstr->getNumOperands() < X86::AddrNumOperands + 4 &&
11783         "unexpected number of operands");
11784  DebugLoc dl = bInstr->getDebugLoc();
11785  MachineOperand& destOper = bInstr->getOperand(0);
11786  MachineOperand* argOpers[2 + X86::AddrNumOperands];
11787  int numArgs = bInstr->getNumOperands() - 1;
11788  for (int i=0; i < numArgs; ++i)
11789    argOpers[i] = &bInstr->getOperand(i+1);
11790
11791  // x86 address has 4 operands: base, index, scale, and displacement
11792  int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
11793  int valArgIndx = lastAddrIndx + 1;
11794
11795  unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
11796  MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(LoadOpc), t1);
11797  for (int i=0; i <= lastAddrIndx; ++i)
11798    (*MIB).addOperand(*argOpers[i]);
11799
11800  unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
11801  assert((argOpers[valArgIndx]->isReg() ||
11802          argOpers[valArgIndx]->isImm()) &&
11803         "invalid operand");
11804  if (argOpers[valArgIndx]->isReg())
11805    MIB = BuildMI(newMBB, dl, TII->get(regOpc), t2);
11806  else
11807    MIB = BuildMI(newMBB, dl, TII->get(immOpc), t2);
11808  MIB.addReg(t1);
11809  (*MIB).addOperand(*argOpers[valArgIndx]);
11810
11811  unsigned t3 = F->getRegInfo().createVirtualRegister(RC);
11812  if (Invert) {
11813    MIB = BuildMI(newMBB, dl, TII->get(notOpc), t3).addReg(t2);
11814  }
11815  else
11816    t3 = t2;
11817
11818  MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), EAXreg);
11819  MIB.addReg(t1);
11820
11821  MIB = BuildMI(newMBB, dl, TII->get(CXchgOpc));
11822  for (int i=0; i <= lastAddrIndx; ++i)
11823    (*MIB).addOperand(*argOpers[i]);
11824  MIB.addReg(t3);
11825  assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
11826  (*MIB).setMemRefs(bInstr->memoperands_begin(),
11827                    bInstr->memoperands_end());
11828
11829  MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), destOper.getReg());
11830  MIB.addReg(EAXreg);
11831
11832  // insert branch
11833  BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
11834
11835  bInstr->eraseFromParent();   // The pseudo instruction is gone now.
11836  return nextMBB;
11837}
11838
11839// private utility function:  64 bit atomics on 32 bit host.
11840MachineBasicBlock *
11841X86TargetLowering::EmitAtomicBit6432WithCustomInserter(MachineInstr *bInstr,
11842                                                       MachineBasicBlock *MBB,
11843                                                       unsigned regOpcL,
11844                                                       unsigned regOpcH,
11845                                                       unsigned immOpcL,
11846                                                       unsigned immOpcH,
11847                                                       bool Invert) const {
11848  // For the atomic bitwise operator, we generate
11849  //   thisMBB (instructions are in pairs, except cmpxchg8b)
11850  //     ld t1,t2 = [bitinstr.addr]
11851  //   newMBB:
11852  //     out1, out2 = phi (thisMBB, t1/t2) (newMBB, t3/t4)
11853  //     op  t5, t6 <- out1, out2, [bitinstr.val]
11854  //      (for SWAP, substitute:  mov t5, t6 <- [bitinstr.val])
11855  //     neg t7, t8 < t5, t6  (if Invert)
11856  //     mov ECX, EBX <- t5, t6
11857  //     mov EAX, EDX <- t1, t2
11858  //     cmpxchg8b [bitinstr.addr]  [EAX, EDX, EBX, ECX implicit]
11859  //     mov t3, t4 <- EAX, EDX
11860  //     bz  newMBB
11861  //     result in out1, out2
11862  //     fallthrough -->nextMBB
11863
11864  const TargetRegisterClass *RC = &X86::GR32RegClass;
11865  const unsigned LoadOpc = X86::MOV32rm;
11866  const unsigned NotOpc = X86::NOT32r;
11867  const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11868  const BasicBlock *LLVM_BB = MBB->getBasicBlock();
11869  MachineFunction::iterator MBBIter = MBB;
11870  ++MBBIter;
11871
11872  /// First build the CFG
11873  MachineFunction *F = MBB->getParent();
11874  MachineBasicBlock *thisMBB = MBB;
11875  MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
11876  MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
11877  F->insert(MBBIter, newMBB);
11878  F->insert(MBBIter, nextMBB);
11879
11880  // Transfer the remainder of thisMBB and its successor edges to nextMBB.
11881  nextMBB->splice(nextMBB->begin(), thisMBB,
11882                  llvm::next(MachineBasicBlock::iterator(bInstr)),
11883                  thisMBB->end());
11884  nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
11885
11886  // Update thisMBB to fall through to newMBB
11887  thisMBB->addSuccessor(newMBB);
11888
11889  // newMBB jumps to itself and fall through to nextMBB
11890  newMBB->addSuccessor(nextMBB);
11891  newMBB->addSuccessor(newMBB);
11892
11893  DebugLoc dl = bInstr->getDebugLoc();
11894  // Insert instructions into newMBB based on incoming instruction
11895  // There are 8 "real" operands plus 9 implicit def/uses, ignored here.
11896  assert(bInstr->getNumOperands() < X86::AddrNumOperands + 14 &&
11897         "unexpected number of operands");
11898  MachineOperand& dest1Oper = bInstr->getOperand(0);
11899  MachineOperand& dest2Oper = bInstr->getOperand(1);
11900  MachineOperand* argOpers[2 + X86::AddrNumOperands];
11901  for (int i=0; i < 2 + X86::AddrNumOperands; ++i) {
11902    argOpers[i] = &bInstr->getOperand(i+2);
11903
11904    // We use some of the operands multiple times, so conservatively just
11905    // clear any kill flags that might be present.
11906    if (argOpers[i]->isReg() && argOpers[i]->isUse())
11907      argOpers[i]->setIsKill(false);
11908  }
11909
11910  // x86 address has 5 operands: base, index, scale, displacement, and segment.
11911  int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
11912
11913  unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
11914  MachineInstrBuilder MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t1);
11915  for (int i=0; i <= lastAddrIndx; ++i)
11916    (*MIB).addOperand(*argOpers[i]);
11917  unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
11918  MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t2);
11919  // add 4 to displacement.
11920  for (int i=0; i <= lastAddrIndx-2; ++i)
11921    (*MIB).addOperand(*argOpers[i]);
11922  MachineOperand newOp3 = *(argOpers[3]);
11923  if (newOp3.isImm())
11924    newOp3.setImm(newOp3.getImm()+4);
11925  else
11926    newOp3.setOffset(newOp3.getOffset()+4);
11927  (*MIB).addOperand(newOp3);
11928  (*MIB).addOperand(*argOpers[lastAddrIndx]);
11929
11930  // t3/4 are defined later, at the bottom of the loop
11931  unsigned t3 = F->getRegInfo().createVirtualRegister(RC);
11932  unsigned t4 = F->getRegInfo().createVirtualRegister(RC);
11933  BuildMI(newMBB, dl, TII->get(X86::PHI), dest1Oper.getReg())
11934    .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(newMBB);
11935  BuildMI(newMBB, dl, TII->get(X86::PHI), dest2Oper.getReg())
11936    .addReg(t2).addMBB(thisMBB).addReg(t4).addMBB(newMBB);
11937
11938  // The subsequent operations should be using the destination registers of
11939  // the PHI instructions.
11940  t1 = dest1Oper.getReg();
11941  t2 = dest2Oper.getReg();
11942
11943  int valArgIndx = lastAddrIndx + 1;
11944  assert((argOpers[valArgIndx]->isReg() ||
11945          argOpers[valArgIndx]->isImm()) &&
11946         "invalid operand");
11947  unsigned t5 = F->getRegInfo().createVirtualRegister(RC);
11948  unsigned t6 = F->getRegInfo().createVirtualRegister(RC);
11949  if (argOpers[valArgIndx]->isReg())
11950    MIB = BuildMI(newMBB, dl, TII->get(regOpcL), t5);
11951  else
11952    MIB = BuildMI(newMBB, dl, TII->get(immOpcL), t5);
11953  if (regOpcL != X86::MOV32rr)
11954    MIB.addReg(t1);
11955  (*MIB).addOperand(*argOpers[valArgIndx]);
11956  assert(argOpers[valArgIndx + 1]->isReg() ==
11957         argOpers[valArgIndx]->isReg());
11958  assert(argOpers[valArgIndx + 1]->isImm() ==
11959         argOpers[valArgIndx]->isImm());
11960  if (argOpers[valArgIndx + 1]->isReg())
11961    MIB = BuildMI(newMBB, dl, TII->get(regOpcH), t6);
11962  else
11963    MIB = BuildMI(newMBB, dl, TII->get(immOpcH), t6);
11964  if (regOpcH != X86::MOV32rr)
11965    MIB.addReg(t2);
11966  (*MIB).addOperand(*argOpers[valArgIndx + 1]);
11967
11968  unsigned t7, t8;
11969  if (Invert) {
11970    t7 = F->getRegInfo().createVirtualRegister(RC);
11971    t8 = F->getRegInfo().createVirtualRegister(RC);
11972    MIB = BuildMI(newMBB, dl, TII->get(NotOpc), t7).addReg(t5);
11973    MIB = BuildMI(newMBB, dl, TII->get(NotOpc), t8).addReg(t6);
11974  } else {
11975    t7 = t5;
11976    t8 = t6;
11977  }
11978
11979  MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EAX);
11980  MIB.addReg(t1);
11981  MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EDX);
11982  MIB.addReg(t2);
11983
11984  MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EBX);
11985  MIB.addReg(t7);
11986  MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::ECX);
11987  MIB.addReg(t8);
11988
11989  MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG8B));
11990  for (int i=0; i <= lastAddrIndx; ++i)
11991    (*MIB).addOperand(*argOpers[i]);
11992
11993  assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
11994  (*MIB).setMemRefs(bInstr->memoperands_begin(),
11995                    bInstr->memoperands_end());
11996
11997  MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t3);
11998  MIB.addReg(X86::EAX);
11999  MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t4);
12000  MIB.addReg(X86::EDX);
12001
12002  // insert branch
12003  BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
12004
12005  bInstr->eraseFromParent();   // The pseudo instruction is gone now.
12006  return nextMBB;
12007}
12008
12009// private utility function
12010MachineBasicBlock *
12011X86TargetLowering::EmitAtomicMinMaxWithCustomInserter(MachineInstr *mInstr,
12012                                                      MachineBasicBlock *MBB,
12013                                                      unsigned cmovOpc) const {
12014  // For the atomic min/max operator, we generate
12015  //   thisMBB:
12016  //   newMBB:
12017  //     ld t1 = [min/max.addr]
12018  //     mov t2 = [min/max.val]
12019  //     cmp  t1, t2
12020  //     cmov[cond] t2 = t1
12021  //     mov EAX = t1
12022  //     lcs dest = [bitinstr.addr], t2  [EAX is implicit]
12023  //     bz   newMBB
12024  //     fallthrough -->nextMBB
12025  //
12026  const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12027  const BasicBlock *LLVM_BB = MBB->getBasicBlock();
12028  MachineFunction::iterator MBBIter = MBB;
12029  ++MBBIter;
12030
12031  /// First build the CFG
12032  MachineFunction *F = MBB->getParent();
12033  MachineBasicBlock *thisMBB = MBB;
12034  MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
12035  MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
12036  F->insert(MBBIter, newMBB);
12037  F->insert(MBBIter, nextMBB);
12038
12039  // Transfer the remainder of thisMBB and its successor edges to nextMBB.
12040  nextMBB->splice(nextMBB->begin(), thisMBB,
12041                  llvm::next(MachineBasicBlock::iterator(mInstr)),
12042                  thisMBB->end());
12043  nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
12044
12045  // Update thisMBB to fall through to newMBB
12046  thisMBB->addSuccessor(newMBB);
12047
12048  // newMBB jumps to newMBB and fall through to nextMBB
12049  newMBB->addSuccessor(nextMBB);
12050  newMBB->addSuccessor(newMBB);
12051
12052  DebugLoc dl = mInstr->getDebugLoc();
12053  // Insert instructions into newMBB based on incoming instruction
12054  assert(mInstr->getNumOperands() < X86::AddrNumOperands + 4 &&
12055         "unexpected number of operands");
12056  MachineOperand& destOper = mInstr->getOperand(0);
12057  MachineOperand* argOpers[2 + X86::AddrNumOperands];
12058  int numArgs = mInstr->getNumOperands() - 1;
12059  for (int i=0; i < numArgs; ++i)
12060    argOpers[i] = &mInstr->getOperand(i+1);
12061
12062  // x86 address has 4 operands: base, index, scale, and displacement
12063  int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
12064  int valArgIndx = lastAddrIndx + 1;
12065
12066  unsigned t1 = F->getRegInfo().createVirtualRegister(&X86::GR32RegClass);
12067  MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rm), t1);
12068  for (int i=0; i <= lastAddrIndx; ++i)
12069    (*MIB).addOperand(*argOpers[i]);
12070
12071  // We only support register and immediate values
12072  assert((argOpers[valArgIndx]->isReg() ||
12073          argOpers[valArgIndx]->isImm()) &&
12074         "invalid operand");
12075
12076  unsigned t2 = F->getRegInfo().createVirtualRegister(&X86::GR32RegClass);
12077  if (argOpers[valArgIndx]->isReg())
12078    MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t2);
12079  else
12080    MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rr), t2);
12081  (*MIB).addOperand(*argOpers[valArgIndx]);
12082
12083  MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EAX);
12084  MIB.addReg(t1);
12085
12086  MIB = BuildMI(newMBB, dl, TII->get(X86::CMP32rr));
12087  MIB.addReg(t1);
12088  MIB.addReg(t2);
12089
12090  // Generate movc
12091  unsigned t3 = F->getRegInfo().createVirtualRegister(&X86::GR32RegClass);
12092  MIB = BuildMI(newMBB, dl, TII->get(cmovOpc),t3);
12093  MIB.addReg(t2);
12094  MIB.addReg(t1);
12095
12096  // Cmp and exchange if none has modified the memory location
12097  MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG32));
12098  for (int i=0; i <= lastAddrIndx; ++i)
12099    (*MIB).addOperand(*argOpers[i]);
12100  MIB.addReg(t3);
12101  assert(mInstr->hasOneMemOperand() && "Unexpected number of memoperand");
12102  (*MIB).setMemRefs(mInstr->memoperands_begin(),
12103                    mInstr->memoperands_end());
12104
12105  MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), destOper.getReg());
12106  MIB.addReg(X86::EAX);
12107
12108  // insert branch
12109  BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
12110
12111  mInstr->eraseFromParent();   // The pseudo instruction is gone now.
12112  return nextMBB;
12113}
12114
12115// FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
12116// or XMM0_V32I8 in AVX all of this code can be replaced with that
12117// in the .td file.
12118MachineBasicBlock *
12119X86TargetLowering::EmitPCMP(MachineInstr *MI, MachineBasicBlock *BB,
12120                            unsigned numArgs, bool memArg) const {
12121  assert(Subtarget->hasSSE42() &&
12122         "Target must have SSE4.2 or AVX features enabled");
12123
12124  DebugLoc dl = MI->getDebugLoc();
12125  const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12126  unsigned Opc;
12127  if (!Subtarget->hasAVX()) {
12128    if (memArg)
12129      Opc = numArgs == 3 ? X86::PCMPISTRM128rm : X86::PCMPESTRM128rm;
12130    else
12131      Opc = numArgs == 3 ? X86::PCMPISTRM128rr : X86::PCMPESTRM128rr;
12132  } else {
12133    if (memArg)
12134      Opc = numArgs == 3 ? X86::VPCMPISTRM128rm : X86::VPCMPESTRM128rm;
12135    else
12136      Opc = numArgs == 3 ? X86::VPCMPISTRM128rr : X86::VPCMPESTRM128rr;
12137  }
12138
12139  MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
12140  for (unsigned i = 0; i < numArgs; ++i) {
12141    MachineOperand &Op = MI->getOperand(i+1);
12142    if (!(Op.isReg() && Op.isImplicit()))
12143      MIB.addOperand(Op);
12144  }
12145  BuildMI(*BB, MI, dl,
12146    TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
12147    .addReg(X86::XMM0);
12148
12149  MI->eraseFromParent();
12150  return BB;
12151}
12152
12153MachineBasicBlock *
12154X86TargetLowering::EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB) const {
12155  DebugLoc dl = MI->getDebugLoc();
12156  const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12157
12158  // Address into RAX/EAX, other two args into ECX, EDX.
12159  unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
12160  unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
12161  MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
12162  for (int i = 0; i < X86::AddrNumOperands; ++i)
12163    MIB.addOperand(MI->getOperand(i));
12164
12165  unsigned ValOps = X86::AddrNumOperands;
12166  BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
12167    .addReg(MI->getOperand(ValOps).getReg());
12168  BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
12169    .addReg(MI->getOperand(ValOps+1).getReg());
12170
12171  // The instruction doesn't actually take any operands though.
12172  BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
12173
12174  MI->eraseFromParent(); // The pseudo is gone now.
12175  return BB;
12176}
12177
12178MachineBasicBlock *
12179X86TargetLowering::EmitVAARG64WithCustomInserter(
12180                   MachineInstr *MI,
12181                   MachineBasicBlock *MBB) const {
12182  // Emit va_arg instruction on X86-64.
12183
12184  // Operands to this pseudo-instruction:
12185  // 0  ) Output        : destination address (reg)
12186  // 1-5) Input         : va_list address (addr, i64mem)
12187  // 6  ) ArgSize       : Size (in bytes) of vararg type
12188  // 7  ) ArgMode       : 0=overflow only, 1=use gp_offset, 2=use fp_offset
12189  // 8  ) Align         : Alignment of type
12190  // 9  ) EFLAGS (implicit-def)
12191
12192  assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
12193  assert(X86::AddrNumOperands == 5 && "VAARG_64 assumes 5 address operands");
12194
12195  unsigned DestReg = MI->getOperand(0).getReg();
12196  MachineOperand &Base = MI->getOperand(1);
12197  MachineOperand &Scale = MI->getOperand(2);
12198  MachineOperand &Index = MI->getOperand(3);
12199  MachineOperand &Disp = MI->getOperand(4);
12200  MachineOperand &Segment = MI->getOperand(5);
12201  unsigned ArgSize = MI->getOperand(6).getImm();
12202  unsigned ArgMode = MI->getOperand(7).getImm();
12203  unsigned Align = MI->getOperand(8).getImm();
12204
12205  // Memory Reference
12206  assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
12207  MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
12208  MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
12209
12210  // Machine Information
12211  const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12212  MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
12213  const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
12214  const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
12215  DebugLoc DL = MI->getDebugLoc();
12216
12217  // struct va_list {
12218  //   i32   gp_offset
12219  //   i32   fp_offset
12220  //   i64   overflow_area (address)
12221  //   i64   reg_save_area (address)
12222  // }
12223  // sizeof(va_list) = 24
12224  // alignment(va_list) = 8
12225
12226  unsigned TotalNumIntRegs = 6;
12227  unsigned TotalNumXMMRegs = 8;
12228  bool UseGPOffset = (ArgMode == 1);
12229  bool UseFPOffset = (ArgMode == 2);
12230  unsigned MaxOffset = TotalNumIntRegs * 8 +
12231                       (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
12232
12233  /* Align ArgSize to a multiple of 8 */
12234  unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
12235  bool NeedsAlign = (Align > 8);
12236
12237  MachineBasicBlock *thisMBB = MBB;
12238  MachineBasicBlock *overflowMBB;
12239  MachineBasicBlock *offsetMBB;
12240  MachineBasicBlock *endMBB;
12241
12242  unsigned OffsetDestReg = 0;    // Argument address computed by offsetMBB
12243  unsigned OverflowDestReg = 0;  // Argument address computed by overflowMBB
12244  unsigned OffsetReg = 0;
12245
12246  if (!UseGPOffset && !UseFPOffset) {
12247    // If we only pull from the overflow region, we don't create a branch.
12248    // We don't need to alter control flow.
12249    OffsetDestReg = 0; // unused
12250    OverflowDestReg = DestReg;
12251
12252    offsetMBB = NULL;
12253    overflowMBB = thisMBB;
12254    endMBB = thisMBB;
12255  } else {
12256    // First emit code to check if gp_offset (or fp_offset) is below the bound.
12257    // If so, pull the argument from reg_save_area. (branch to offsetMBB)
12258    // If not, pull from overflow_area. (branch to overflowMBB)
12259    //
12260    //       thisMBB
12261    //         |     .
12262    //         |        .
12263    //     offsetMBB   overflowMBB
12264    //         |        .
12265    //         |     .
12266    //        endMBB
12267
12268    // Registers for the PHI in endMBB
12269    OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
12270    OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
12271
12272    const BasicBlock *LLVM_BB = MBB->getBasicBlock();
12273    MachineFunction *MF = MBB->getParent();
12274    overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
12275    offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
12276    endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
12277
12278    MachineFunction::iterator MBBIter = MBB;
12279    ++MBBIter;
12280
12281    // Insert the new basic blocks
12282    MF->insert(MBBIter, offsetMBB);
12283    MF->insert(MBBIter, overflowMBB);
12284    MF->insert(MBBIter, endMBB);
12285
12286    // Transfer the remainder of MBB and its successor edges to endMBB.
12287    endMBB->splice(endMBB->begin(), thisMBB,
12288                    llvm::next(MachineBasicBlock::iterator(MI)),
12289                    thisMBB->end());
12290    endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
12291
12292    // Make offsetMBB and overflowMBB successors of thisMBB
12293    thisMBB->addSuccessor(offsetMBB);
12294    thisMBB->addSuccessor(overflowMBB);
12295
12296    // endMBB is a successor of both offsetMBB and overflowMBB
12297    offsetMBB->addSuccessor(endMBB);
12298    overflowMBB->addSuccessor(endMBB);
12299
12300    // Load the offset value into a register
12301    OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
12302    BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
12303      .addOperand(Base)
12304      .addOperand(Scale)
12305      .addOperand(Index)
12306      .addDisp(Disp, UseFPOffset ? 4 : 0)
12307      .addOperand(Segment)
12308      .setMemRefs(MMOBegin, MMOEnd);
12309
12310    // Check if there is enough room left to pull this argument.
12311    BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
12312      .addReg(OffsetReg)
12313      .addImm(MaxOffset + 8 - ArgSizeA8);
12314
12315    // Branch to "overflowMBB" if offset >= max
12316    // Fall through to "offsetMBB" otherwise
12317    BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
12318      .addMBB(overflowMBB);
12319  }
12320
12321  // In offsetMBB, emit code to use the reg_save_area.
12322  if (offsetMBB) {
12323    assert(OffsetReg != 0);
12324
12325    // Read the reg_save_area address.
12326    unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
12327    BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
12328      .addOperand(Base)
12329      .addOperand(Scale)
12330      .addOperand(Index)
12331      .addDisp(Disp, 16)
12332      .addOperand(Segment)
12333      .setMemRefs(MMOBegin, MMOEnd);
12334
12335    // Zero-extend the offset
12336    unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
12337      BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
12338        .addImm(0)
12339        .addReg(OffsetReg)
12340        .addImm(X86::sub_32bit);
12341
12342    // Add the offset to the reg_save_area to get the final address.
12343    BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
12344      .addReg(OffsetReg64)
12345      .addReg(RegSaveReg);
12346
12347    // Compute the offset for the next argument
12348    unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
12349    BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
12350      .addReg(OffsetReg)
12351      .addImm(UseFPOffset ? 16 : 8);
12352
12353    // Store it back into the va_list.
12354    BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
12355      .addOperand(Base)
12356      .addOperand(Scale)
12357      .addOperand(Index)
12358      .addDisp(Disp, UseFPOffset ? 4 : 0)
12359      .addOperand(Segment)
12360      .addReg(NextOffsetReg)
12361      .setMemRefs(MMOBegin, MMOEnd);
12362
12363    // Jump to endMBB
12364    BuildMI(offsetMBB, DL, TII->get(X86::JMP_4))
12365      .addMBB(endMBB);
12366  }
12367
12368  //
12369  // Emit code to use overflow area
12370  //
12371
12372  // Load the overflow_area address into a register.
12373  unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
12374  BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
12375    .addOperand(Base)
12376    .addOperand(Scale)
12377    .addOperand(Index)
12378    .addDisp(Disp, 8)
12379    .addOperand(Segment)
12380    .setMemRefs(MMOBegin, MMOEnd);
12381
12382  // If we need to align it, do so. Otherwise, just copy the address
12383  // to OverflowDestReg.
12384  if (NeedsAlign) {
12385    // Align the overflow address
12386    assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
12387    unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
12388
12389    // aligned_addr = (addr + (align-1)) & ~(align-1)
12390    BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
12391      .addReg(OverflowAddrReg)
12392      .addImm(Align-1);
12393
12394    BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
12395      .addReg(TmpReg)
12396      .addImm(~(uint64_t)(Align-1));
12397  } else {
12398    BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
12399      .addReg(OverflowAddrReg);
12400  }
12401
12402  // Compute the next overflow address after this argument.
12403  // (the overflow address should be kept 8-byte aligned)
12404  unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
12405  BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
12406    .addReg(OverflowDestReg)
12407    .addImm(ArgSizeA8);
12408
12409  // Store the new overflow address.
12410  BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
12411    .addOperand(Base)
12412    .addOperand(Scale)
12413    .addOperand(Index)
12414    .addDisp(Disp, 8)
12415    .addOperand(Segment)
12416    .addReg(NextAddrReg)
12417    .setMemRefs(MMOBegin, MMOEnd);
12418
12419  // If we branched, emit the PHI to the front of endMBB.
12420  if (offsetMBB) {
12421    BuildMI(*endMBB, endMBB->begin(), DL,
12422            TII->get(X86::PHI), DestReg)
12423      .addReg(OffsetDestReg).addMBB(offsetMBB)
12424      .addReg(OverflowDestReg).addMBB(overflowMBB);
12425  }
12426
12427  // Erase the pseudo instruction
12428  MI->eraseFromParent();
12429
12430  return endMBB;
12431}
12432
12433MachineBasicBlock *
12434X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
12435                                                 MachineInstr *MI,
12436                                                 MachineBasicBlock *MBB) const {
12437  // Emit code to save XMM registers to the stack. The ABI says that the
12438  // number of registers to save is given in %al, so it's theoretically
12439  // possible to do an indirect jump trick to avoid saving all of them,
12440  // however this code takes a simpler approach and just executes all
12441  // of the stores if %al is non-zero. It's less code, and it's probably
12442  // easier on the hardware branch predictor, and stores aren't all that
12443  // expensive anyway.
12444
12445  // Create the new basic blocks. One block contains all the XMM stores,
12446  // and one block is the final destination regardless of whether any
12447  // stores were performed.
12448  const BasicBlock *LLVM_BB = MBB->getBasicBlock();
12449  MachineFunction *F = MBB->getParent();
12450  MachineFunction::iterator MBBIter = MBB;
12451  ++MBBIter;
12452  MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
12453  MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
12454  F->insert(MBBIter, XMMSaveMBB);
12455  F->insert(MBBIter, EndMBB);
12456
12457  // Transfer the remainder of MBB and its successor edges to EndMBB.
12458  EndMBB->splice(EndMBB->begin(), MBB,
12459                 llvm::next(MachineBasicBlock::iterator(MI)),
12460                 MBB->end());
12461  EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
12462
12463  // The original block will now fall through to the XMM save block.
12464  MBB->addSuccessor(XMMSaveMBB);
12465  // The XMMSaveMBB will fall through to the end block.
12466  XMMSaveMBB->addSuccessor(EndMBB);
12467
12468  // Now add the instructions.
12469  const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12470  DebugLoc DL = MI->getDebugLoc();
12471
12472  unsigned CountReg = MI->getOperand(0).getReg();
12473  int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
12474  int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
12475
12476  if (!Subtarget->isTargetWin64()) {
12477    // If %al is 0, branch around the XMM save block.
12478    BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
12479    BuildMI(MBB, DL, TII->get(X86::JE_4)).addMBB(EndMBB);
12480    MBB->addSuccessor(EndMBB);
12481  }
12482
12483  unsigned MOVOpc = Subtarget->hasAVX() ? X86::VMOVAPSmr : X86::MOVAPSmr;
12484  // In the XMM save block, save all the XMM argument registers.
12485  for (int i = 3, e = MI->getNumOperands(); i != e; ++i) {
12486    int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
12487    MachineMemOperand *MMO =
12488      F->getMachineMemOperand(
12489          MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
12490        MachineMemOperand::MOStore,
12491        /*Size=*/16, /*Align=*/16);
12492    BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
12493      .addFrameIndex(RegSaveFrameIndex)
12494      .addImm(/*Scale=*/1)
12495      .addReg(/*IndexReg=*/0)
12496      .addImm(/*Disp=*/Offset)
12497      .addReg(/*Segment=*/0)
12498      .addReg(MI->getOperand(i).getReg())
12499      .addMemOperand(MMO);
12500  }
12501
12502  MI->eraseFromParent();   // The pseudo instruction is gone now.
12503
12504  return EndMBB;
12505}
12506
12507// The EFLAGS operand of SelectItr might be missing a kill marker
12508// because there were multiple uses of EFLAGS, and ISel didn't know
12509// which to mark. Figure out whether SelectItr should have had a
12510// kill marker, and set it if it should. Returns the correct kill
12511// marker value.
12512static bool checkAndUpdateEFLAGSKill(MachineBasicBlock::iterator SelectItr,
12513                                     MachineBasicBlock* BB,
12514                                     const TargetRegisterInfo* TRI) {
12515  // Scan forward through BB for a use/def of EFLAGS.
12516  MachineBasicBlock::iterator miI(llvm::next(SelectItr));
12517  for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
12518    const MachineInstr& mi = *miI;
12519    if (mi.readsRegister(X86::EFLAGS))
12520      return false;
12521    if (mi.definesRegister(X86::EFLAGS))
12522      break; // Should have kill-flag - update below.
12523  }
12524
12525  // If we hit the end of the block, check whether EFLAGS is live into a
12526  // successor.
12527  if (miI == BB->end()) {
12528    for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
12529                                          sEnd = BB->succ_end();
12530         sItr != sEnd; ++sItr) {
12531      MachineBasicBlock* succ = *sItr;
12532      if (succ->isLiveIn(X86::EFLAGS))
12533        return false;
12534    }
12535  }
12536
12537  // We found a def, or hit the end of the basic block and EFLAGS wasn't live
12538  // out. SelectMI should have a kill flag on EFLAGS.
12539  SelectItr->addRegisterKilled(X86::EFLAGS, TRI);
12540  return true;
12541}
12542
12543MachineBasicBlock *
12544X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
12545                                     MachineBasicBlock *BB) const {
12546  const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12547  DebugLoc DL = MI->getDebugLoc();
12548
12549  // To "insert" a SELECT_CC instruction, we actually have to insert the
12550  // diamond control-flow pattern.  The incoming instruction knows the
12551  // destination vreg to set, the condition code register to branch on, the
12552  // true/false values to select between, and a branch opcode to use.
12553  const BasicBlock *LLVM_BB = BB->getBasicBlock();
12554  MachineFunction::iterator It = BB;
12555  ++It;
12556
12557  //  thisMBB:
12558  //  ...
12559  //   TrueVal = ...
12560  //   cmpTY ccX, r1, r2
12561  //   bCC copy1MBB
12562  //   fallthrough --> copy0MBB
12563  MachineBasicBlock *thisMBB = BB;
12564  MachineFunction *F = BB->getParent();
12565  MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
12566  MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
12567  F->insert(It, copy0MBB);
12568  F->insert(It, sinkMBB);
12569
12570  // If the EFLAGS register isn't dead in the terminator, then claim that it's
12571  // live into the sink and copy blocks.
12572  const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
12573  if (!MI->killsRegister(X86::EFLAGS) &&
12574      !checkAndUpdateEFLAGSKill(MI, BB, TRI)) {
12575    copy0MBB->addLiveIn(X86::EFLAGS);
12576    sinkMBB->addLiveIn(X86::EFLAGS);
12577  }
12578
12579  // Transfer the remainder of BB and its successor edges to sinkMBB.
12580  sinkMBB->splice(sinkMBB->begin(), BB,
12581                  llvm::next(MachineBasicBlock::iterator(MI)),
12582                  BB->end());
12583  sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
12584
12585  // Add the true and fallthrough blocks as its successors.
12586  BB->addSuccessor(copy0MBB);
12587  BB->addSuccessor(sinkMBB);
12588
12589  // Create the conditional branch instruction.
12590  unsigned Opc =
12591    X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
12592  BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
12593
12594  //  copy0MBB:
12595  //   %FalseValue = ...
12596  //   # fallthrough to sinkMBB
12597  copy0MBB->addSuccessor(sinkMBB);
12598
12599  //  sinkMBB:
12600  //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
12601  //  ...
12602  BuildMI(*sinkMBB, sinkMBB->begin(), DL,
12603          TII->get(X86::PHI), MI->getOperand(0).getReg())
12604    .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
12605    .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
12606
12607  MI->eraseFromParent();   // The pseudo instruction is gone now.
12608  return sinkMBB;
12609}
12610
12611MachineBasicBlock *
12612X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI, MachineBasicBlock *BB,
12613                                        bool Is64Bit) const {
12614  const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12615  DebugLoc DL = MI->getDebugLoc();
12616  MachineFunction *MF = BB->getParent();
12617  const BasicBlock *LLVM_BB = BB->getBasicBlock();
12618
12619  assert(getTargetMachine().Options.EnableSegmentedStacks);
12620
12621  unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
12622  unsigned TlsOffset = Is64Bit ? 0x70 : 0x30;
12623
12624  // BB:
12625  //  ... [Till the alloca]
12626  // If stacklet is not large enough, jump to mallocMBB
12627  //
12628  // bumpMBB:
12629  //  Allocate by subtracting from RSP
12630  //  Jump to continueMBB
12631  //
12632  // mallocMBB:
12633  //  Allocate by call to runtime
12634  //
12635  // continueMBB:
12636  //  ...
12637  //  [rest of original BB]
12638  //
12639
12640  MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
12641  MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
12642  MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
12643
12644  MachineRegisterInfo &MRI = MF->getRegInfo();
12645  const TargetRegisterClass *AddrRegClass =
12646    getRegClassFor(Is64Bit ? MVT::i64:MVT::i32);
12647
12648  unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
12649    bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
12650    tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
12651    SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
12652    sizeVReg = MI->getOperand(1).getReg(),
12653    physSPReg = Is64Bit ? X86::RSP : X86::ESP;
12654
12655  MachineFunction::iterator MBBIter = BB;
12656  ++MBBIter;
12657
12658  MF->insert(MBBIter, bumpMBB);
12659  MF->insert(MBBIter, mallocMBB);
12660  MF->insert(MBBIter, continueMBB);
12661
12662  continueMBB->splice(continueMBB->begin(), BB, llvm::next
12663                      (MachineBasicBlock::iterator(MI)), BB->end());
12664  continueMBB->transferSuccessorsAndUpdatePHIs(BB);
12665
12666  // Add code to the main basic block to check if the stack limit has been hit,
12667  // and if so, jump to mallocMBB otherwise to bumpMBB.
12668  BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
12669  BuildMI(BB, DL, TII->get(Is64Bit ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
12670    .addReg(tmpSPVReg).addReg(sizeVReg);
12671  BuildMI(BB, DL, TII->get(Is64Bit ? X86::CMP64mr:X86::CMP32mr))
12672    .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg)
12673    .addReg(SPLimitVReg);
12674  BuildMI(BB, DL, TII->get(X86::JG_4)).addMBB(mallocMBB);
12675
12676  // bumpMBB simply decreases the stack pointer, since we know the current
12677  // stacklet has enough space.
12678  BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
12679    .addReg(SPLimitVReg);
12680  BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
12681    .addReg(SPLimitVReg);
12682  BuildMI(bumpMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
12683
12684  // Calls into a routine in libgcc to allocate more space from the heap.
12685  const uint32_t *RegMask =
12686    getTargetMachine().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
12687  if (Is64Bit) {
12688    BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
12689      .addReg(sizeVReg);
12690    BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
12691      .addExternalSymbol("__morestack_allocate_stack_space")
12692      .addRegMask(RegMask)
12693      .addReg(X86::RDI, RegState::Implicit)
12694      .addReg(X86::RAX, RegState::ImplicitDefine);
12695  } else {
12696    BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
12697      .addImm(12);
12698    BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
12699    BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
12700      .addExternalSymbol("__morestack_allocate_stack_space")
12701      .addRegMask(RegMask)
12702      .addReg(X86::EAX, RegState::ImplicitDefine);
12703  }
12704
12705  if (!Is64Bit)
12706    BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
12707      .addImm(16);
12708
12709  BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
12710    .addReg(Is64Bit ? X86::RAX : X86::EAX);
12711  BuildMI(mallocMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
12712
12713  // Set up the CFG correctly.
12714  BB->addSuccessor(bumpMBB);
12715  BB->addSuccessor(mallocMBB);
12716  mallocMBB->addSuccessor(continueMBB);
12717  bumpMBB->addSuccessor(continueMBB);
12718
12719  // Take care of the PHI nodes.
12720  BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
12721          MI->getOperand(0).getReg())
12722    .addReg(mallocPtrVReg).addMBB(mallocMBB)
12723    .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
12724
12725  // Delete the original pseudo instruction.
12726  MI->eraseFromParent();
12727
12728  // And we're done.
12729  return continueMBB;
12730}
12731
12732MachineBasicBlock *
12733X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
12734                                          MachineBasicBlock *BB) const {
12735  const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12736  DebugLoc DL = MI->getDebugLoc();
12737
12738  assert(!Subtarget->isTargetEnvMacho());
12739
12740  // The lowering is pretty easy: we're just emitting the call to _alloca.  The
12741  // non-trivial part is impdef of ESP.
12742
12743  if (Subtarget->isTargetWin64()) {
12744    if (Subtarget->isTargetCygMing()) {
12745      // ___chkstk(Mingw64):
12746      // Clobbers R10, R11, RAX and EFLAGS.
12747      // Updates RSP.
12748      BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
12749        .addExternalSymbol("___chkstk")
12750        .addReg(X86::RAX, RegState::Implicit)
12751        .addReg(X86::RSP, RegState::Implicit)
12752        .addReg(X86::RAX, RegState::Define | RegState::Implicit)
12753        .addReg(X86::RSP, RegState::Define | RegState::Implicit)
12754        .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
12755    } else {
12756      // __chkstk(MSVCRT): does not update stack pointer.
12757      // Clobbers R10, R11 and EFLAGS.
12758      // FIXME: RAX(allocated size) might be reused and not killed.
12759      BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
12760        .addExternalSymbol("__chkstk")
12761        .addReg(X86::RAX, RegState::Implicit)
12762        .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
12763      // RAX has the offset to subtracted from RSP.
12764      BuildMI(*BB, MI, DL, TII->get(X86::SUB64rr), X86::RSP)
12765        .addReg(X86::RSP)
12766        .addReg(X86::RAX);
12767    }
12768  } else {
12769    const char *StackProbeSymbol =
12770      Subtarget->isTargetWindows() ? "_chkstk" : "_alloca";
12771
12772    BuildMI(*BB, MI, DL, TII->get(X86::CALLpcrel32))
12773      .addExternalSymbol(StackProbeSymbol)
12774      .addReg(X86::EAX, RegState::Implicit)
12775      .addReg(X86::ESP, RegState::Implicit)
12776      .addReg(X86::EAX, RegState::Define | RegState::Implicit)
12777      .addReg(X86::ESP, RegState::Define | RegState::Implicit)
12778      .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
12779  }
12780
12781  MI->eraseFromParent();   // The pseudo instruction is gone now.
12782  return BB;
12783}
12784
12785MachineBasicBlock *
12786X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
12787                                      MachineBasicBlock *BB) const {
12788  // This is pretty easy.  We're taking the value that we received from
12789  // our load from the relocation, sticking it in either RDI (x86-64)
12790  // or EAX and doing an indirect call.  The return value will then
12791  // be in the normal return register.
12792  const X86InstrInfo *TII
12793    = static_cast<const X86InstrInfo*>(getTargetMachine().getInstrInfo());
12794  DebugLoc DL = MI->getDebugLoc();
12795  MachineFunction *F = BB->getParent();
12796
12797  assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
12798  assert(MI->getOperand(3).isGlobal() && "This should be a global");
12799
12800  // Get a register mask for the lowered call.
12801  // FIXME: The 32-bit calls have non-standard calling conventions. Use a
12802  // proper register mask.
12803  const uint32_t *RegMask =
12804    getTargetMachine().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
12805  if (Subtarget->is64Bit()) {
12806    MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
12807                                      TII->get(X86::MOV64rm), X86::RDI)
12808    .addReg(X86::RIP)
12809    .addImm(0).addReg(0)
12810    .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
12811                      MI->getOperand(3).getTargetFlags())
12812    .addReg(0);
12813    MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
12814    addDirectMem(MIB, X86::RDI);
12815    MIB.addReg(X86::RAX, RegState::ImplicitDefine).addRegMask(RegMask);
12816  } else if (getTargetMachine().getRelocationModel() != Reloc::PIC_) {
12817    MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
12818                                      TII->get(X86::MOV32rm), X86::EAX)
12819    .addReg(0)
12820    .addImm(0).addReg(0)
12821    .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
12822                      MI->getOperand(3).getTargetFlags())
12823    .addReg(0);
12824    MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
12825    addDirectMem(MIB, X86::EAX);
12826    MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
12827  } else {
12828    MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
12829                                      TII->get(X86::MOV32rm), X86::EAX)
12830    .addReg(TII->getGlobalBaseReg(F))
12831    .addImm(0).addReg(0)
12832    .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
12833                      MI->getOperand(3).getTargetFlags())
12834    .addReg(0);
12835    MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
12836    addDirectMem(MIB, X86::EAX);
12837    MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
12838  }
12839
12840  MI->eraseFromParent(); // The pseudo instruction is gone now.
12841  return BB;
12842}
12843
12844MachineBasicBlock *
12845X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
12846                                               MachineBasicBlock *BB) const {
12847  switch (MI->getOpcode()) {
12848  default: llvm_unreachable("Unexpected instr type to insert");
12849  case X86::TAILJMPd64:
12850  case X86::TAILJMPr64:
12851  case X86::TAILJMPm64:
12852    llvm_unreachable("TAILJMP64 would not be touched here.");
12853  case X86::TCRETURNdi64:
12854  case X86::TCRETURNri64:
12855  case X86::TCRETURNmi64:
12856    return BB;
12857  case X86::WIN_ALLOCA:
12858    return EmitLoweredWinAlloca(MI, BB);
12859  case X86::SEG_ALLOCA_32:
12860    return EmitLoweredSegAlloca(MI, BB, false);
12861  case X86::SEG_ALLOCA_64:
12862    return EmitLoweredSegAlloca(MI, BB, true);
12863  case X86::TLSCall_32:
12864  case X86::TLSCall_64:
12865    return EmitLoweredTLSCall(MI, BB);
12866  case X86::CMOV_GR8:
12867  case X86::CMOV_FR32:
12868  case X86::CMOV_FR64:
12869  case X86::CMOV_V4F32:
12870  case X86::CMOV_V2F64:
12871  case X86::CMOV_V2I64:
12872  case X86::CMOV_V8F32:
12873  case X86::CMOV_V4F64:
12874  case X86::CMOV_V4I64:
12875  case X86::CMOV_GR16:
12876  case X86::CMOV_GR32:
12877  case X86::CMOV_RFP32:
12878  case X86::CMOV_RFP64:
12879  case X86::CMOV_RFP80:
12880    return EmitLoweredSelect(MI, BB);
12881
12882  case X86::FP32_TO_INT16_IN_MEM:
12883  case X86::FP32_TO_INT32_IN_MEM:
12884  case X86::FP32_TO_INT64_IN_MEM:
12885  case X86::FP64_TO_INT16_IN_MEM:
12886  case X86::FP64_TO_INT32_IN_MEM:
12887  case X86::FP64_TO_INT64_IN_MEM:
12888  case X86::FP80_TO_INT16_IN_MEM:
12889  case X86::FP80_TO_INT32_IN_MEM:
12890  case X86::FP80_TO_INT64_IN_MEM: {
12891    const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12892    DebugLoc DL = MI->getDebugLoc();
12893
12894    // Change the floating point control register to use "round towards zero"
12895    // mode when truncating to an integer value.
12896    MachineFunction *F = BB->getParent();
12897    int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
12898    addFrameReference(BuildMI(*BB, MI, DL,
12899                              TII->get(X86::FNSTCW16m)), CWFrameIdx);
12900
12901    // Load the old value of the high byte of the control word...
12902    unsigned OldCW =
12903      F->getRegInfo().createVirtualRegister(&X86::GR16RegClass);
12904    addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
12905                      CWFrameIdx);
12906
12907    // Set the high part to be round to zero...
12908    addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
12909      .addImm(0xC7F);
12910
12911    // Reload the modified control word now...
12912    addFrameReference(BuildMI(*BB, MI, DL,
12913                              TII->get(X86::FLDCW16m)), CWFrameIdx);
12914
12915    // Restore the memory image of control word to original value
12916    addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
12917      .addReg(OldCW);
12918
12919    // Get the X86 opcode to use.
12920    unsigned Opc;
12921    switch (MI->getOpcode()) {
12922    default: llvm_unreachable("illegal opcode!");
12923    case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
12924    case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
12925    case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
12926    case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
12927    case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
12928    case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
12929    case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
12930    case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
12931    case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
12932    }
12933
12934    X86AddressMode AM;
12935    MachineOperand &Op = MI->getOperand(0);
12936    if (Op.isReg()) {
12937      AM.BaseType = X86AddressMode::RegBase;
12938      AM.Base.Reg = Op.getReg();
12939    } else {
12940      AM.BaseType = X86AddressMode::FrameIndexBase;
12941      AM.Base.FrameIndex = Op.getIndex();
12942    }
12943    Op = MI->getOperand(1);
12944    if (Op.isImm())
12945      AM.Scale = Op.getImm();
12946    Op = MI->getOperand(2);
12947    if (Op.isImm())
12948      AM.IndexReg = Op.getImm();
12949    Op = MI->getOperand(3);
12950    if (Op.isGlobal()) {
12951      AM.GV = Op.getGlobal();
12952    } else {
12953      AM.Disp = Op.getImm();
12954    }
12955    addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
12956                      .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
12957
12958    // Reload the original control word now.
12959    addFrameReference(BuildMI(*BB, MI, DL,
12960                              TII->get(X86::FLDCW16m)), CWFrameIdx);
12961
12962    MI->eraseFromParent();   // The pseudo instruction is gone now.
12963    return BB;
12964  }
12965    // String/text processing lowering.
12966  case X86::PCMPISTRM128REG:
12967  case X86::VPCMPISTRM128REG:
12968  case X86::PCMPISTRM128MEM:
12969  case X86::VPCMPISTRM128MEM:
12970  case X86::PCMPESTRM128REG:
12971  case X86::VPCMPESTRM128REG:
12972  case X86::PCMPESTRM128MEM:
12973  case X86::VPCMPESTRM128MEM: {
12974    unsigned NumArgs;
12975    bool MemArg;
12976    switch (MI->getOpcode()) {
12977    default: llvm_unreachable("illegal opcode!");
12978    case X86::PCMPISTRM128REG:
12979    case X86::VPCMPISTRM128REG:
12980      NumArgs = 3; MemArg = false; break;
12981    case X86::PCMPISTRM128MEM:
12982    case X86::VPCMPISTRM128MEM:
12983      NumArgs = 3; MemArg = true; break;
12984    case X86::PCMPESTRM128REG:
12985    case X86::VPCMPESTRM128REG:
12986      NumArgs = 5; MemArg = false; break;
12987    case X86::PCMPESTRM128MEM:
12988    case X86::VPCMPESTRM128MEM:
12989      NumArgs = 5; MemArg = true; break;
12990    }
12991    return EmitPCMP(MI, BB, NumArgs, MemArg);
12992  }
12993
12994    // Thread synchronization.
12995  case X86::MONITOR:
12996    return EmitMonitor(MI, BB);
12997
12998    // Atomic Lowering.
12999  case X86::ATOMMIN32:
13000  case X86::ATOMMAX32:
13001  case X86::ATOMUMIN32:
13002  case X86::ATOMUMAX32:
13003  case X86::ATOMMIN16:
13004  case X86::ATOMMAX16:
13005  case X86::ATOMUMIN16:
13006  case X86::ATOMUMAX16:
13007  case X86::ATOMMIN64:
13008  case X86::ATOMMAX64:
13009  case X86::ATOMUMIN64:
13010  case X86::ATOMUMAX64: {
13011    unsigned Opc;
13012    switch (MI->getOpcode()) {
13013    default: llvm_unreachable("illegal opcode!");
13014    case X86::ATOMMIN32:  Opc = X86::CMOVL32rr; break;
13015    case X86::ATOMMAX32:  Opc = X86::CMOVG32rr; break;
13016    case X86::ATOMUMIN32: Opc = X86::CMOVB32rr; break;
13017    case X86::ATOMUMAX32: Opc = X86::CMOVA32rr; break;
13018    case X86::ATOMMIN16:  Opc = X86::CMOVL16rr; break;
13019    case X86::ATOMMAX16:  Opc = X86::CMOVG16rr; break;
13020    case X86::ATOMUMIN16: Opc = X86::CMOVB16rr; break;
13021    case X86::ATOMUMAX16: Opc = X86::CMOVA16rr; break;
13022    case X86::ATOMMIN64:  Opc = X86::CMOVL64rr; break;
13023    case X86::ATOMMAX64:  Opc = X86::CMOVG64rr; break;
13024    case X86::ATOMUMIN64: Opc = X86::CMOVB64rr; break;
13025    case X86::ATOMUMAX64: Opc = X86::CMOVA64rr; break;
13026    // FIXME: There are no CMOV8 instructions; MIN/MAX need some other way.
13027    }
13028    return EmitAtomicMinMaxWithCustomInserter(MI, BB, Opc);
13029  }
13030
13031  case X86::ATOMAND32:
13032  case X86::ATOMOR32:
13033  case X86::ATOMXOR32:
13034  case X86::ATOMNAND32: {
13035    bool Invert = false;
13036    unsigned RegOpc, ImmOpc;
13037    switch (MI->getOpcode()) {
13038    default: llvm_unreachable("illegal opcode!");
13039    case X86::ATOMAND32:
13040      RegOpc = X86::AND32rr; ImmOpc = X86::AND32ri; break;
13041    case X86::ATOMOR32:
13042      RegOpc = X86::OR32rr;  ImmOpc = X86::OR32ri; break;
13043    case X86::ATOMXOR32:
13044      RegOpc = X86::XOR32rr; ImmOpc = X86::XOR32ri; break;
13045    case X86::ATOMNAND32:
13046      RegOpc = X86::AND32rr; ImmOpc = X86::AND32ri; Invert = true; break;
13047    }
13048    return EmitAtomicBitwiseWithCustomInserter(MI, BB, RegOpc, ImmOpc,
13049                                               X86::MOV32rm, X86::LCMPXCHG32,
13050                                               X86::NOT32r, X86::EAX,
13051                                               &X86::GR32RegClass, Invert);
13052  }
13053
13054  case X86::ATOMAND16:
13055  case X86::ATOMOR16:
13056  case X86::ATOMXOR16:
13057  case X86::ATOMNAND16: {
13058    bool Invert = false;
13059    unsigned RegOpc, ImmOpc;
13060    switch (MI->getOpcode()) {
13061    default: llvm_unreachable("illegal opcode!");
13062    case X86::ATOMAND16:
13063      RegOpc = X86::AND16rr; ImmOpc = X86::AND16ri; break;
13064    case X86::ATOMOR16:
13065      RegOpc = X86::OR16rr;  ImmOpc = X86::OR16ri; break;
13066    case X86::ATOMXOR16:
13067      RegOpc = X86::XOR16rr; ImmOpc = X86::XOR16ri; break;
13068    case X86::ATOMNAND16:
13069      RegOpc = X86::AND16rr; ImmOpc = X86::AND16ri; Invert = true; break;
13070    }
13071    return EmitAtomicBitwiseWithCustomInserter(MI, BB, RegOpc, ImmOpc,
13072                                               X86::MOV16rm, X86::LCMPXCHG16,
13073                                               X86::NOT16r, X86::AX,
13074                                               &X86::GR16RegClass, Invert);
13075  }
13076
13077  case X86::ATOMAND8:
13078  case X86::ATOMOR8:
13079  case X86::ATOMXOR8:
13080  case X86::ATOMNAND8: {
13081    bool Invert = false;
13082    unsigned RegOpc, ImmOpc;
13083    switch (MI->getOpcode()) {
13084    default: llvm_unreachable("illegal opcode!");
13085    case X86::ATOMAND8:
13086      RegOpc = X86::AND8rr; ImmOpc = X86::AND8ri; break;
13087    case X86::ATOMOR8:
13088      RegOpc = X86::OR8rr;  ImmOpc = X86::OR8ri; break;
13089    case X86::ATOMXOR8:
13090      RegOpc = X86::XOR8rr; ImmOpc = X86::XOR8ri; break;
13091    case X86::ATOMNAND8:
13092      RegOpc = X86::AND8rr; ImmOpc = X86::AND8ri; Invert = true; break;
13093    }
13094    return EmitAtomicBitwiseWithCustomInserter(MI, BB, RegOpc, ImmOpc,
13095                                               X86::MOV8rm, X86::LCMPXCHG8,
13096                                               X86::NOT8r, X86::AL,
13097                                               &X86::GR8RegClass, Invert);
13098  }
13099
13100  // This group is for 64-bit host.
13101  case X86::ATOMAND64:
13102  case X86::ATOMOR64:
13103  case X86::ATOMXOR64:
13104  case X86::ATOMNAND64: {
13105    bool Invert = false;
13106    unsigned RegOpc, ImmOpc;
13107    switch (MI->getOpcode()) {
13108    default: llvm_unreachable("illegal opcode!");
13109    case X86::ATOMAND64:
13110      RegOpc = X86::AND64rr; ImmOpc = X86::AND64ri32; break;
13111    case X86::ATOMOR64:
13112      RegOpc = X86::OR64rr;  ImmOpc = X86::OR64ri32; break;
13113    case X86::ATOMXOR64:
13114      RegOpc = X86::XOR64rr; ImmOpc = X86::XOR64ri32; break;
13115    case X86::ATOMNAND64:
13116      RegOpc = X86::AND64rr; ImmOpc = X86::AND64ri32; Invert = true; break;
13117    }
13118    return EmitAtomicBitwiseWithCustomInserter(MI, BB, RegOpc, ImmOpc,
13119                                               X86::MOV64rm, X86::LCMPXCHG64,
13120                                               X86::NOT64r, X86::RAX,
13121                                               &X86::GR64RegClass, Invert);
13122  }
13123
13124  // This group does 64-bit operations on a 32-bit host.
13125  case X86::ATOMAND6432:
13126  case X86::ATOMOR6432:
13127  case X86::ATOMXOR6432:
13128  case X86::ATOMNAND6432:
13129  case X86::ATOMADD6432:
13130  case X86::ATOMSUB6432:
13131  case X86::ATOMSWAP6432: {
13132    bool Invert = false;
13133    unsigned RegOpcL, RegOpcH, ImmOpcL, ImmOpcH;
13134    switch (MI->getOpcode()) {
13135    default: llvm_unreachable("illegal opcode!");
13136    case X86::ATOMAND6432:
13137      RegOpcL = RegOpcH = X86::AND32rr;
13138      ImmOpcL = ImmOpcH = X86::AND32ri;
13139      break;
13140    case X86::ATOMOR6432:
13141      RegOpcL = RegOpcH = X86::OR32rr;
13142      ImmOpcL = ImmOpcH = X86::OR32ri;
13143      break;
13144    case X86::ATOMXOR6432:
13145      RegOpcL = RegOpcH = X86::XOR32rr;
13146      ImmOpcL = ImmOpcH = X86::XOR32ri;
13147      break;
13148    case X86::ATOMNAND6432:
13149      RegOpcL = RegOpcH = X86::AND32rr;
13150      ImmOpcL = ImmOpcH = X86::AND32ri;
13151      Invert = true;
13152      break;
13153    case X86::ATOMADD6432:
13154      RegOpcL = X86::ADD32rr; RegOpcH = X86::ADC32rr;
13155      ImmOpcL = X86::ADD32ri; ImmOpcH = X86::ADC32ri;
13156      break;
13157    case X86::ATOMSUB6432:
13158      RegOpcL = X86::SUB32rr; RegOpcH = X86::SBB32rr;
13159      ImmOpcL = X86::SUB32ri; ImmOpcH = X86::SBB32ri;
13160      break;
13161    case X86::ATOMSWAP6432:
13162      RegOpcL = RegOpcH = X86::MOV32rr;
13163      ImmOpcL = ImmOpcH = X86::MOV32ri;
13164      break;
13165    }
13166    return EmitAtomicBit6432WithCustomInserter(MI, BB, RegOpcL, RegOpcH,
13167                                               ImmOpcL, ImmOpcH, Invert);
13168  }
13169
13170  case X86::VASTART_SAVE_XMM_REGS:
13171    return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
13172
13173  case X86::VAARG_64:
13174    return EmitVAARG64WithCustomInserter(MI, BB);
13175  }
13176}
13177
13178//===----------------------------------------------------------------------===//
13179//                           X86 Optimization Hooks
13180//===----------------------------------------------------------------------===//
13181
13182void X86TargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
13183                                                       APInt &KnownZero,
13184                                                       APInt &KnownOne,
13185                                                       const SelectionDAG &DAG,
13186                                                       unsigned Depth) const {
13187  unsigned BitWidth = KnownZero.getBitWidth();
13188  unsigned Opc = Op.getOpcode();
13189  assert((Opc >= ISD::BUILTIN_OP_END ||
13190          Opc == ISD::INTRINSIC_WO_CHAIN ||
13191          Opc == ISD::INTRINSIC_W_CHAIN ||
13192          Opc == ISD::INTRINSIC_VOID) &&
13193         "Should use MaskedValueIsZero if you don't know whether Op"
13194         " is a target node!");
13195
13196  KnownZero = KnownOne = APInt(BitWidth, 0);   // Don't know anything.
13197  switch (Opc) {
13198  default: break;
13199  case X86ISD::ADD:
13200  case X86ISD::SUB:
13201  case X86ISD::ADC:
13202  case X86ISD::SBB:
13203  case X86ISD::SMUL:
13204  case X86ISD::UMUL:
13205  case X86ISD::INC:
13206  case X86ISD::DEC:
13207  case X86ISD::OR:
13208  case X86ISD::XOR:
13209  case X86ISD::AND:
13210    // These nodes' second result is a boolean.
13211    if (Op.getResNo() == 0)
13212      break;
13213    // Fallthrough
13214  case X86ISD::SETCC:
13215    KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
13216    break;
13217  case ISD::INTRINSIC_WO_CHAIN: {
13218    unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
13219    unsigned NumLoBits = 0;
13220    switch (IntId) {
13221    default: break;
13222    case Intrinsic::x86_sse_movmsk_ps:
13223    case Intrinsic::x86_avx_movmsk_ps_256:
13224    case Intrinsic::x86_sse2_movmsk_pd:
13225    case Intrinsic::x86_avx_movmsk_pd_256:
13226    case Intrinsic::x86_mmx_pmovmskb:
13227    case Intrinsic::x86_sse2_pmovmskb_128:
13228    case Intrinsic::x86_avx2_pmovmskb: {
13229      // High bits of movmskp{s|d}, pmovmskb are known zero.
13230      switch (IntId) {
13231        default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
13232        case Intrinsic::x86_sse_movmsk_ps:      NumLoBits = 4; break;
13233        case Intrinsic::x86_avx_movmsk_ps_256:  NumLoBits = 8; break;
13234        case Intrinsic::x86_sse2_movmsk_pd:     NumLoBits = 2; break;
13235        case Intrinsic::x86_avx_movmsk_pd_256:  NumLoBits = 4; break;
13236        case Intrinsic::x86_mmx_pmovmskb:       NumLoBits = 8; break;
13237        case Intrinsic::x86_sse2_pmovmskb_128:  NumLoBits = 16; break;
13238        case Intrinsic::x86_avx2_pmovmskb:      NumLoBits = 32; break;
13239      }
13240      KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - NumLoBits);
13241      break;
13242    }
13243    }
13244    break;
13245  }
13246  }
13247}
13248
13249unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(SDValue Op,
13250                                                         unsigned Depth) const {
13251  // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
13252  if (Op.getOpcode() == X86ISD::SETCC_CARRY)
13253    return Op.getValueType().getScalarType().getSizeInBits();
13254
13255  // Fallback case.
13256  return 1;
13257}
13258
13259/// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
13260/// node is a GlobalAddress + offset.
13261bool X86TargetLowering::isGAPlusOffset(SDNode *N,
13262                                       const GlobalValue* &GA,
13263                                       int64_t &Offset) const {
13264  if (N->getOpcode() == X86ISD::Wrapper) {
13265    if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
13266      GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
13267      Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
13268      return true;
13269    }
13270  }
13271  return TargetLowering::isGAPlusOffset(N, GA, Offset);
13272}
13273
13274/// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the
13275/// same as extracting the high 128-bit part of 256-bit vector and then
13276/// inserting the result into the low part of a new 256-bit vector
13277static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) {
13278  EVT VT = SVOp->getValueType(0);
13279  unsigned NumElems = VT.getVectorNumElements();
13280
13281  // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
13282  for (unsigned i = 0, j = NumElems/2; i != NumElems/2; ++i, ++j)
13283    if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
13284        SVOp->getMaskElt(j) >= 0)
13285      return false;
13286
13287  return true;
13288}
13289
13290/// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the
13291/// same as extracting the low 128-bit part of 256-bit vector and then
13292/// inserting the result into the high part of a new 256-bit vector
13293static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) {
13294  EVT VT = SVOp->getValueType(0);
13295  unsigned NumElems = VT.getVectorNumElements();
13296
13297  // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
13298  for (unsigned i = NumElems/2, j = 0; i != NumElems; ++i, ++j)
13299    if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
13300        SVOp->getMaskElt(j) >= 0)
13301      return false;
13302
13303  return true;
13304}
13305
13306/// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
13307static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
13308                                        TargetLowering::DAGCombinerInfo &DCI,
13309                                        const X86Subtarget* Subtarget) {
13310  DebugLoc dl = N->getDebugLoc();
13311  ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
13312  SDValue V1 = SVOp->getOperand(0);
13313  SDValue V2 = SVOp->getOperand(1);
13314  EVT VT = SVOp->getValueType(0);
13315  unsigned NumElems = VT.getVectorNumElements();
13316
13317  if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
13318      V2.getOpcode() == ISD::CONCAT_VECTORS) {
13319    //
13320    //                   0,0,0,...
13321    //                      |
13322    //    V      UNDEF    BUILD_VECTOR    UNDEF
13323    //     \      /           \           /
13324    //  CONCAT_VECTOR         CONCAT_VECTOR
13325    //         \                  /
13326    //          \                /
13327    //          RESULT: V + zero extended
13328    //
13329    if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
13330        V2.getOperand(1).getOpcode() != ISD::UNDEF ||
13331        V1.getOperand(1).getOpcode() != ISD::UNDEF)
13332      return SDValue();
13333
13334    if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
13335      return SDValue();
13336
13337    // To match the shuffle mask, the first half of the mask should
13338    // be exactly the first vector, and all the rest a splat with the
13339    // first element of the second one.
13340    for (unsigned i = 0; i != NumElems/2; ++i)
13341      if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
13342          !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
13343        return SDValue();
13344
13345    // If V1 is coming from a vector load then just fold to a VZEXT_LOAD.
13346    if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(V1.getOperand(0))) {
13347      if (Ld->hasNUsesOfValue(1, 0)) {
13348        SDVTList Tys = DAG.getVTList(MVT::v4i64, MVT::Other);
13349        SDValue Ops[] = { Ld->getChain(), Ld->getBasePtr() };
13350        SDValue ResNode =
13351          DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops, 2,
13352                                  Ld->getMemoryVT(),
13353                                  Ld->getPointerInfo(),
13354                                  Ld->getAlignment(),
13355                                  false/*isVolatile*/, true/*ReadMem*/,
13356                                  false/*WriteMem*/);
13357        return DAG.getNode(ISD::BITCAST, dl, VT, ResNode);
13358      }
13359    }
13360
13361    // Emit a zeroed vector and insert the desired subvector on its
13362    // first half.
13363    SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
13364    SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0), 0, DAG, dl);
13365    return DCI.CombineTo(N, InsV);
13366  }
13367
13368  //===--------------------------------------------------------------------===//
13369  // Combine some shuffles into subvector extracts and inserts:
13370  //
13371
13372  // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
13373  if (isShuffleHigh128VectorInsertLow(SVOp)) {
13374    SDValue V = Extract128BitVector(V1, NumElems/2, DAG, dl);
13375    SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, 0, DAG, dl);
13376    return DCI.CombineTo(N, InsV);
13377  }
13378
13379  // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
13380  if (isShuffleLow128VectorInsertHigh(SVOp)) {
13381    SDValue V = Extract128BitVector(V1, 0, DAG, dl);
13382    SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, NumElems/2, DAG, dl);
13383    return DCI.CombineTo(N, InsV);
13384  }
13385
13386  return SDValue();
13387}
13388
13389/// PerformShuffleCombine - Performs several different shuffle combines.
13390static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
13391                                     TargetLowering::DAGCombinerInfo &DCI,
13392                                     const X86Subtarget *Subtarget) {
13393  DebugLoc dl = N->getDebugLoc();
13394  EVT VT = N->getValueType(0);
13395
13396  // Don't create instructions with illegal types after legalize types has run.
13397  const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13398  if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
13399    return SDValue();
13400
13401  // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
13402  if (Subtarget->hasAVX() && VT.is256BitVector() &&
13403      N->getOpcode() == ISD::VECTOR_SHUFFLE)
13404    return PerformShuffleCombine256(N, DAG, DCI, Subtarget);
13405
13406  // Only handle 128 wide vector from here on.
13407  if (!VT.is128BitVector())
13408    return SDValue();
13409
13410  // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
13411  // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
13412  // consecutive, non-overlapping, and in the right order.
13413  SmallVector<SDValue, 16> Elts;
13414  for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
13415    Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
13416
13417  return EltsFromConsecutiveLoads(VT, Elts, dl, DAG);
13418}
13419
13420
13421/// DCI, PerformTruncateCombine - Converts truncate operation to
13422/// a sequence of vector shuffle operations.
13423/// It is possible when we truncate 256-bit vector to 128-bit vector
13424
13425SDValue X86TargetLowering::PerformTruncateCombine(SDNode *N, SelectionDAG &DAG,
13426                                                  DAGCombinerInfo &DCI) const {
13427  if (!DCI.isBeforeLegalizeOps())
13428    return SDValue();
13429
13430  if (!Subtarget->hasAVX())
13431    return SDValue();
13432
13433  EVT VT = N->getValueType(0);
13434  SDValue Op = N->getOperand(0);
13435  EVT OpVT = Op.getValueType();
13436  DebugLoc dl = N->getDebugLoc();
13437
13438  if ((VT == MVT::v4i32) && (OpVT == MVT::v4i64)) {
13439
13440    if (Subtarget->hasAVX2()) {
13441      // AVX2: v4i64 -> v4i32
13442
13443      // VPERMD
13444      static const int ShufMask[] = {0, 2, 4, 6, -1, -1, -1, -1};
13445
13446      Op = DAG.getNode(ISD::BITCAST, dl, MVT::v8i32, Op);
13447      Op = DAG.getVectorShuffle(MVT::v8i32, dl, Op, DAG.getUNDEF(MVT::v8i32),
13448                                ShufMask);
13449
13450      return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, Op,
13451                         DAG.getIntPtrConstant(0));
13452    }
13453
13454    // AVX: v4i64 -> v4i32
13455    SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v2i64, Op,
13456                               DAG.getIntPtrConstant(0));
13457
13458    SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v2i64, Op,
13459                               DAG.getIntPtrConstant(2));
13460
13461    OpLo = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, OpLo);
13462    OpHi = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, OpHi);
13463
13464    // PSHUFD
13465    static const int ShufMask1[] = {0, 2, 0, 0};
13466
13467    SDValue Undef = DAG.getUNDEF(VT);
13468    OpLo = DAG.getVectorShuffle(VT, dl, OpLo, Undef, ShufMask1);
13469    OpHi = DAG.getVectorShuffle(VT, dl, OpHi, Undef, ShufMask1);
13470
13471    // MOVLHPS
13472    static const int ShufMask2[] = {0, 1, 4, 5};
13473
13474    return DAG.getVectorShuffle(VT, dl, OpLo, OpHi, ShufMask2);
13475  }
13476
13477  if ((VT == MVT::v8i16) && (OpVT == MVT::v8i32)) {
13478
13479    if (Subtarget->hasAVX2()) {
13480      // AVX2: v8i32 -> v8i16
13481
13482      Op = DAG.getNode(ISD::BITCAST, dl, MVT::v32i8, Op);
13483
13484      // PSHUFB
13485      SmallVector<SDValue,32> pshufbMask;
13486      for (unsigned i = 0; i < 2; ++i) {
13487        pshufbMask.push_back(DAG.getConstant(0x0, MVT::i8));
13488        pshufbMask.push_back(DAG.getConstant(0x1, MVT::i8));
13489        pshufbMask.push_back(DAG.getConstant(0x4, MVT::i8));
13490        pshufbMask.push_back(DAG.getConstant(0x5, MVT::i8));
13491        pshufbMask.push_back(DAG.getConstant(0x8, MVT::i8));
13492        pshufbMask.push_back(DAG.getConstant(0x9, MVT::i8));
13493        pshufbMask.push_back(DAG.getConstant(0xc, MVT::i8));
13494        pshufbMask.push_back(DAG.getConstant(0xd, MVT::i8));
13495        for (unsigned j = 0; j < 8; ++j)
13496          pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
13497      }
13498      SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v32i8,
13499                               &pshufbMask[0], 32);
13500      Op = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v32i8, Op, BV);
13501
13502      Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4i64, Op);
13503
13504      static const int ShufMask[] = {0,  2,  -1,  -1};
13505      Op = DAG.getVectorShuffle(MVT::v4i64, dl,  Op, DAG.getUNDEF(MVT::v4i64),
13506                                &ShufMask[0]);
13507
13508      Op = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v2i64, Op,
13509                       DAG.getIntPtrConstant(0));
13510
13511      return DAG.getNode(ISD::BITCAST, dl, VT, Op);
13512    }
13513
13514    SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i32, Op,
13515                               DAG.getIntPtrConstant(0));
13516
13517    SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i32, Op,
13518                               DAG.getIntPtrConstant(4));
13519
13520    OpLo = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpLo);
13521    OpHi = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpHi);
13522
13523    // PSHUFB
13524    static const int ShufMask1[] = {0,  1,  4,  5,  8,  9, 12, 13,
13525                                   -1, -1, -1, -1, -1, -1, -1, -1};
13526
13527    SDValue Undef = DAG.getUNDEF(MVT::v16i8);
13528    OpLo = DAG.getVectorShuffle(MVT::v16i8, dl, OpLo, Undef, ShufMask1);
13529    OpHi = DAG.getVectorShuffle(MVT::v16i8, dl, OpHi, Undef, ShufMask1);
13530
13531    OpLo = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, OpLo);
13532    OpHi = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, OpHi);
13533
13534    // MOVLHPS
13535    static const int ShufMask2[] = {0, 1, 4, 5};
13536
13537    SDValue res = DAG.getVectorShuffle(MVT::v4i32, dl, OpLo, OpHi, ShufMask2);
13538    return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, res);
13539  }
13540
13541  return SDValue();
13542}
13543
13544/// XFormVExtractWithShuffleIntoLoad - Check if a vector extract from a target
13545/// specific shuffle of a load can be folded into a single element load.
13546/// Similar handling for VECTOR_SHUFFLE is performed by DAGCombiner, but
13547/// shuffles have been customed lowered so we need to handle those here.
13548static SDValue XFormVExtractWithShuffleIntoLoad(SDNode *N, SelectionDAG &DAG,
13549                                         TargetLowering::DAGCombinerInfo &DCI) {
13550  if (DCI.isBeforeLegalizeOps())
13551    return SDValue();
13552
13553  SDValue InVec = N->getOperand(0);
13554  SDValue EltNo = N->getOperand(1);
13555
13556  if (!isa<ConstantSDNode>(EltNo))
13557    return SDValue();
13558
13559  EVT VT = InVec.getValueType();
13560
13561  bool HasShuffleIntoBitcast = false;
13562  if (InVec.getOpcode() == ISD::BITCAST) {
13563    // Don't duplicate a load with other uses.
13564    if (!InVec.hasOneUse())
13565      return SDValue();
13566    EVT BCVT = InVec.getOperand(0).getValueType();
13567    if (BCVT.getVectorNumElements() != VT.getVectorNumElements())
13568      return SDValue();
13569    InVec = InVec.getOperand(0);
13570    HasShuffleIntoBitcast = true;
13571  }
13572
13573  if (!isTargetShuffle(InVec.getOpcode()))
13574    return SDValue();
13575
13576  // Don't duplicate a load with other uses.
13577  if (!InVec.hasOneUse())
13578    return SDValue();
13579
13580  SmallVector<int, 16> ShuffleMask;
13581  bool UnaryShuffle;
13582  if (!getTargetShuffleMask(InVec.getNode(), VT.getSimpleVT(), ShuffleMask,
13583                            UnaryShuffle))
13584    return SDValue();
13585
13586  // Select the input vector, guarding against out of range extract vector.
13587  unsigned NumElems = VT.getVectorNumElements();
13588  int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
13589  int Idx = (Elt > (int)NumElems) ? -1 : ShuffleMask[Elt];
13590  SDValue LdNode = (Idx < (int)NumElems) ? InVec.getOperand(0)
13591                                         : InVec.getOperand(1);
13592
13593  // If inputs to shuffle are the same for both ops, then allow 2 uses
13594  unsigned AllowedUses = InVec.getOperand(0) == InVec.getOperand(1) ? 2 : 1;
13595
13596  if (LdNode.getOpcode() == ISD::BITCAST) {
13597    // Don't duplicate a load with other uses.
13598    if (!LdNode.getNode()->hasNUsesOfValue(AllowedUses, 0))
13599      return SDValue();
13600
13601    AllowedUses = 1; // only allow 1 load use if we have a bitcast
13602    LdNode = LdNode.getOperand(0);
13603  }
13604
13605  if (!ISD::isNormalLoad(LdNode.getNode()))
13606    return SDValue();
13607
13608  LoadSDNode *LN0 = cast<LoadSDNode>(LdNode);
13609
13610  if (!LN0 ||!LN0->hasNUsesOfValue(AllowedUses, 0) || LN0->isVolatile())
13611    return SDValue();
13612
13613  if (HasShuffleIntoBitcast) {
13614    // If there's a bitcast before the shuffle, check if the load type and
13615    // alignment is valid.
13616    unsigned Align = LN0->getAlignment();
13617    const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13618    unsigned NewAlign = TLI.getTargetData()->
13619      getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
13620
13621    if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VT))
13622      return SDValue();
13623  }
13624
13625  // All checks match so transform back to vector_shuffle so that DAG combiner
13626  // can finish the job
13627  DebugLoc dl = N->getDebugLoc();
13628
13629  // Create shuffle node taking into account the case that its a unary shuffle
13630  SDValue Shuffle = (UnaryShuffle) ? DAG.getUNDEF(VT) : InVec.getOperand(1);
13631  Shuffle = DAG.getVectorShuffle(InVec.getValueType(), dl,
13632                                 InVec.getOperand(0), Shuffle,
13633                                 &ShuffleMask[0]);
13634  Shuffle = DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
13635  return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0), Shuffle,
13636                     EltNo);
13637}
13638
13639/// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
13640/// generation and convert it from being a bunch of shuffles and extracts
13641/// to a simple store and scalar loads to extract the elements.
13642static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
13643                                         TargetLowering::DAGCombinerInfo &DCI) {
13644  SDValue NewOp = XFormVExtractWithShuffleIntoLoad(N, DAG, DCI);
13645  if (NewOp.getNode())
13646    return NewOp;
13647
13648  SDValue InputVector = N->getOperand(0);
13649
13650  // Only operate on vectors of 4 elements, where the alternative shuffling
13651  // gets to be more expensive.
13652  if (InputVector.getValueType() != MVT::v4i32)
13653    return SDValue();
13654
13655  // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
13656  // single use which is a sign-extend or zero-extend, and all elements are
13657  // used.
13658  SmallVector<SDNode *, 4> Uses;
13659  unsigned ExtractedElements = 0;
13660  for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
13661       UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
13662    if (UI.getUse().getResNo() != InputVector.getResNo())
13663      return SDValue();
13664
13665    SDNode *Extract = *UI;
13666    if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
13667      return SDValue();
13668
13669    if (Extract->getValueType(0) != MVT::i32)
13670      return SDValue();
13671    if (!Extract->hasOneUse())
13672      return SDValue();
13673    if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
13674        Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
13675      return SDValue();
13676    if (!isa<ConstantSDNode>(Extract->getOperand(1)))
13677      return SDValue();
13678
13679    // Record which element was extracted.
13680    ExtractedElements |=
13681      1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
13682
13683    Uses.push_back(Extract);
13684  }
13685
13686  // If not all the elements were used, this may not be worthwhile.
13687  if (ExtractedElements != 15)
13688    return SDValue();
13689
13690  // Ok, we've now decided to do the transformation.
13691  DebugLoc dl = InputVector.getDebugLoc();
13692
13693  // Store the value to a temporary stack slot.
13694  SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
13695  SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
13696                            MachinePointerInfo(), false, false, 0);
13697
13698  // Replace each use (extract) with a load of the appropriate element.
13699  for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
13700       UE = Uses.end(); UI != UE; ++UI) {
13701    SDNode *Extract = *UI;
13702
13703    // cOMpute the element's address.
13704    SDValue Idx = Extract->getOperand(1);
13705    unsigned EltSize =
13706        InputVector.getValueType().getVectorElementType().getSizeInBits()/8;
13707    uint64_t Offset = EltSize * cast<ConstantSDNode>(Idx)->getZExtValue();
13708    const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13709    SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy());
13710
13711    SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(),
13712                                     StackPtr, OffsetVal);
13713
13714    // Load the scalar.
13715    SDValue LoadScalar = DAG.getLoad(Extract->getValueType(0), dl, Ch,
13716                                     ScalarAddr, MachinePointerInfo(),
13717                                     false, false, false, 0);
13718
13719    // Replace the exact with the load.
13720    DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), LoadScalar);
13721  }
13722
13723  // The replacement was made in place; don't return anything.
13724  return SDValue();
13725}
13726
13727/// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
13728/// nodes.
13729static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
13730                                    TargetLowering::DAGCombinerInfo &DCI,
13731                                    const X86Subtarget *Subtarget) {
13732  DebugLoc DL = N->getDebugLoc();
13733  SDValue Cond = N->getOperand(0);
13734  // Get the LHS/RHS of the select.
13735  SDValue LHS = N->getOperand(1);
13736  SDValue RHS = N->getOperand(2);
13737  EVT VT = LHS.getValueType();
13738
13739  // If we have SSE[12] support, try to form min/max nodes. SSE min/max
13740  // instructions match the semantics of the common C idiom x<y?x:y but not
13741  // x<=y?x:y, because of how they handle negative zero (which can be
13742  // ignored in unsafe-math mode).
13743  if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
13744      VT != MVT::f80 && DAG.getTargetLoweringInfo().isTypeLegal(VT) &&
13745      (Subtarget->hasSSE2() ||
13746       (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
13747    ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
13748
13749    unsigned Opcode = 0;
13750    // Check for x CC y ? x : y.
13751    if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
13752        DAG.isEqualTo(RHS, Cond.getOperand(1))) {
13753      switch (CC) {
13754      default: break;
13755      case ISD::SETULT:
13756        // Converting this to a min would handle NaNs incorrectly, and swapping
13757        // the operands would cause it to handle comparisons between positive
13758        // and negative zero incorrectly.
13759        if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
13760          if (!DAG.getTarget().Options.UnsafeFPMath &&
13761              !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
13762            break;
13763          std::swap(LHS, RHS);
13764        }
13765        Opcode = X86ISD::FMIN;
13766        break;
13767      case ISD::SETOLE:
13768        // Converting this to a min would handle comparisons between positive
13769        // and negative zero incorrectly.
13770        if (!DAG.getTarget().Options.UnsafeFPMath &&
13771            !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
13772          break;
13773        Opcode = X86ISD::FMIN;
13774        break;
13775      case ISD::SETULE:
13776        // Converting this to a min would handle both negative zeros and NaNs
13777        // incorrectly, but we can swap the operands to fix both.
13778        std::swap(LHS, RHS);
13779      case ISD::SETOLT:
13780      case ISD::SETLT:
13781      case ISD::SETLE:
13782        Opcode = X86ISD::FMIN;
13783        break;
13784
13785      case ISD::SETOGE:
13786        // Converting this to a max would handle comparisons between positive
13787        // and negative zero incorrectly.
13788        if (!DAG.getTarget().Options.UnsafeFPMath &&
13789            !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
13790          break;
13791        Opcode = X86ISD::FMAX;
13792        break;
13793      case ISD::SETUGT:
13794        // Converting this to a max would handle NaNs incorrectly, and swapping
13795        // the operands would cause it to handle comparisons between positive
13796        // and negative zero incorrectly.
13797        if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
13798          if (!DAG.getTarget().Options.UnsafeFPMath &&
13799              !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
13800            break;
13801          std::swap(LHS, RHS);
13802        }
13803        Opcode = X86ISD::FMAX;
13804        break;
13805      case ISD::SETUGE:
13806        // Converting this to a max would handle both negative zeros and NaNs
13807        // incorrectly, but we can swap the operands to fix both.
13808        std::swap(LHS, RHS);
13809      case ISD::SETOGT:
13810      case ISD::SETGT:
13811      case ISD::SETGE:
13812        Opcode = X86ISD::FMAX;
13813        break;
13814      }
13815    // Check for x CC y ? y : x -- a min/max with reversed arms.
13816    } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
13817               DAG.isEqualTo(RHS, Cond.getOperand(0))) {
13818      switch (CC) {
13819      default: break;
13820      case ISD::SETOGE:
13821        // Converting this to a min would handle comparisons between positive
13822        // and negative zero incorrectly, and swapping the operands would
13823        // cause it to handle NaNs incorrectly.
13824        if (!DAG.getTarget().Options.UnsafeFPMath &&
13825            !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
13826          if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
13827            break;
13828          std::swap(LHS, RHS);
13829        }
13830        Opcode = X86ISD::FMIN;
13831        break;
13832      case ISD::SETUGT:
13833        // Converting this to a min would handle NaNs incorrectly.
13834        if (!DAG.getTarget().Options.UnsafeFPMath &&
13835            (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
13836          break;
13837        Opcode = X86ISD::FMIN;
13838        break;
13839      case ISD::SETUGE:
13840        // Converting this to a min would handle both negative zeros and NaNs
13841        // incorrectly, but we can swap the operands to fix both.
13842        std::swap(LHS, RHS);
13843      case ISD::SETOGT:
13844      case ISD::SETGT:
13845      case ISD::SETGE:
13846        Opcode = X86ISD::FMIN;
13847        break;
13848
13849      case ISD::SETULT:
13850        // Converting this to a max would handle NaNs incorrectly.
13851        if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
13852          break;
13853        Opcode = X86ISD::FMAX;
13854        break;
13855      case ISD::SETOLE:
13856        // Converting this to a max would handle comparisons between positive
13857        // and negative zero incorrectly, and swapping the operands would
13858        // cause it to handle NaNs incorrectly.
13859        if (!DAG.getTarget().Options.UnsafeFPMath &&
13860            !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
13861          if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
13862            break;
13863          std::swap(LHS, RHS);
13864        }
13865        Opcode = X86ISD::FMAX;
13866        break;
13867      case ISD::SETULE:
13868        // Converting this to a max would handle both negative zeros and NaNs
13869        // incorrectly, but we can swap the operands to fix both.
13870        std::swap(LHS, RHS);
13871      case ISD::SETOLT:
13872      case ISD::SETLT:
13873      case ISD::SETLE:
13874        Opcode = X86ISD::FMAX;
13875        break;
13876      }
13877    }
13878
13879    if (Opcode)
13880      return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
13881  }
13882
13883  // If this is a select between two integer constants, try to do some
13884  // optimizations.
13885  if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
13886    if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
13887      // Don't do this for crazy integer types.
13888      if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
13889        // If this is efficiently invertible, canonicalize the LHSC/RHSC values
13890        // so that TrueC (the true value) is larger than FalseC.
13891        bool NeedsCondInvert = false;
13892
13893        if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
13894            // Efficiently invertible.
13895            (Cond.getOpcode() == ISD::SETCC ||  // setcc -> invertible.
13896             (Cond.getOpcode() == ISD::XOR &&   // xor(X, C) -> invertible.
13897              isa<ConstantSDNode>(Cond.getOperand(1))))) {
13898          NeedsCondInvert = true;
13899          std::swap(TrueC, FalseC);
13900        }
13901
13902        // Optimize C ? 8 : 0 -> zext(C) << 3.  Likewise for any pow2/0.
13903        if (FalseC->getAPIntValue() == 0 &&
13904            TrueC->getAPIntValue().isPowerOf2()) {
13905          if (NeedsCondInvert) // Invert the condition if needed.
13906            Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
13907                               DAG.getConstant(1, Cond.getValueType()));
13908
13909          // Zero extend the condition if needed.
13910          Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
13911
13912          unsigned ShAmt = TrueC->getAPIntValue().logBase2();
13913          return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
13914                             DAG.getConstant(ShAmt, MVT::i8));
13915        }
13916
13917        // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
13918        if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
13919          if (NeedsCondInvert) // Invert the condition if needed.
13920            Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
13921                               DAG.getConstant(1, Cond.getValueType()));
13922
13923          // Zero extend the condition if needed.
13924          Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
13925                             FalseC->getValueType(0), Cond);
13926          return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
13927                             SDValue(FalseC, 0));
13928        }
13929
13930        // Optimize cases that will turn into an LEA instruction.  This requires
13931        // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
13932        if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
13933          uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
13934          if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
13935
13936          bool isFastMultiplier = false;
13937          if (Diff < 10) {
13938            switch ((unsigned char)Diff) {
13939              default: break;
13940              case 1:  // result = add base, cond
13941              case 2:  // result = lea base(    , cond*2)
13942              case 3:  // result = lea base(cond, cond*2)
13943              case 4:  // result = lea base(    , cond*4)
13944              case 5:  // result = lea base(cond, cond*4)
13945              case 8:  // result = lea base(    , cond*8)
13946              case 9:  // result = lea base(cond, cond*8)
13947                isFastMultiplier = true;
13948                break;
13949            }
13950          }
13951
13952          if (isFastMultiplier) {
13953            APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
13954            if (NeedsCondInvert) // Invert the condition if needed.
13955              Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
13956                                 DAG.getConstant(1, Cond.getValueType()));
13957
13958            // Zero extend the condition if needed.
13959            Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
13960                               Cond);
13961            // Scale the condition by the difference.
13962            if (Diff != 1)
13963              Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
13964                                 DAG.getConstant(Diff, Cond.getValueType()));
13965
13966            // Add the base if non-zero.
13967            if (FalseC->getAPIntValue() != 0)
13968              Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
13969                                 SDValue(FalseC, 0));
13970            return Cond;
13971          }
13972        }
13973      }
13974  }
13975
13976  // Canonicalize max and min:
13977  // (x > y) ? x : y -> (x >= y) ? x : y
13978  // (x < y) ? x : y -> (x <= y) ? x : y
13979  // This allows use of COND_S / COND_NS (see TranslateX86CC) which eliminates
13980  // the need for an extra compare
13981  // against zero. e.g.
13982  // (x - y) > 0 : (x - y) ? 0 -> (x - y) >= 0 : (x - y) ? 0
13983  // subl   %esi, %edi
13984  // testl  %edi, %edi
13985  // movl   $0, %eax
13986  // cmovgl %edi, %eax
13987  // =>
13988  // xorl   %eax, %eax
13989  // subl   %esi, $edi
13990  // cmovsl %eax, %edi
13991  if (N->getOpcode() == ISD::SELECT && Cond.getOpcode() == ISD::SETCC &&
13992      DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
13993      DAG.isEqualTo(RHS, Cond.getOperand(1))) {
13994    ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
13995    switch (CC) {
13996    default: break;
13997    case ISD::SETLT:
13998    case ISD::SETGT: {
13999      ISD::CondCode NewCC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGE;
14000      Cond = DAG.getSetCC(Cond.getDebugLoc(), Cond.getValueType(),
14001                          Cond.getOperand(0), Cond.getOperand(1), NewCC);
14002      return DAG.getNode(ISD::SELECT, DL, VT, Cond, LHS, RHS);
14003    }
14004    }
14005  }
14006
14007  // If we know that this node is legal then we know that it is going to be
14008  // matched by one of the SSE/AVX BLEND instructions. These instructions only
14009  // depend on the highest bit in each word. Try to use SimplifyDemandedBits
14010  // to simplify previous instructions.
14011  const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14012  if (N->getOpcode() == ISD::VSELECT && DCI.isBeforeLegalizeOps() &&
14013      !DCI.isBeforeLegalize() && TLI.isOperationLegal(ISD::VSELECT, VT)) {
14014    unsigned BitWidth = Cond.getValueType().getScalarType().getSizeInBits();
14015
14016    // Don't optimize vector selects that map to mask-registers.
14017    if (BitWidth == 1)
14018      return SDValue();
14019
14020    assert(BitWidth >= 8 && BitWidth <= 64 && "Invalid mask size");
14021    APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 1);
14022
14023    APInt KnownZero, KnownOne;
14024    TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
14025                                          DCI.isBeforeLegalizeOps());
14026    if (TLO.ShrinkDemandedConstant(Cond, DemandedMask) ||
14027        TLI.SimplifyDemandedBits(Cond, DemandedMask, KnownZero, KnownOne, TLO))
14028      DCI.CommitTargetLoweringOpt(TLO);
14029  }
14030
14031  return SDValue();
14032}
14033
14034// Check whether a boolean test is testing a boolean value generated by
14035// X86ISD::SETCC. If so, return the operand of that SETCC and proper condition
14036// code.
14037//
14038// Simplify the following patterns:
14039// (Op (CMP (SETCC Cond EFLAGS) 1) EQ) or
14040// (Op (CMP (SETCC Cond EFLAGS) 0) NEQ)
14041// to (Op EFLAGS Cond)
14042//
14043// (Op (CMP (SETCC Cond EFLAGS) 0) EQ) or
14044// (Op (CMP (SETCC Cond EFLAGS) 1) NEQ)
14045// to (Op EFLAGS !Cond)
14046//
14047// where Op could be BRCOND or CMOV.
14048//
14049static SDValue checkBoolTestSetCCCombine(SDValue Cmp, X86::CondCode &CC) {
14050  // Quit if not CMP and SUB with its value result used.
14051  if (Cmp.getOpcode() != X86ISD::CMP &&
14052      (Cmp.getOpcode() != X86ISD::SUB || Cmp.getNode()->hasAnyUseOfValue(0)))
14053      return SDValue();
14054
14055  // Quit if not used as a boolean value.
14056  if (CC != X86::COND_E && CC != X86::COND_NE)
14057    return SDValue();
14058
14059  // Check CMP operands. One of them should be 0 or 1 and the other should be
14060  // an SetCC or extended from it.
14061  SDValue Op1 = Cmp.getOperand(0);
14062  SDValue Op2 = Cmp.getOperand(1);
14063
14064  SDValue SetCC;
14065  const ConstantSDNode* C = 0;
14066  bool needOppositeCond = (CC == X86::COND_E);
14067
14068  if ((C = dyn_cast<ConstantSDNode>(Op1)))
14069    SetCC = Op2;
14070  else if ((C = dyn_cast<ConstantSDNode>(Op2)))
14071    SetCC = Op1;
14072  else // Quit if all operands are not constants.
14073    return SDValue();
14074
14075  if (C->getZExtValue() == 1)
14076    needOppositeCond = !needOppositeCond;
14077  else if (C->getZExtValue() != 0)
14078    // Quit if the constant is neither 0 or 1.
14079    return SDValue();
14080
14081  // Skip 'zext' node.
14082  if (SetCC.getOpcode() == ISD::ZERO_EXTEND)
14083    SetCC = SetCC.getOperand(0);
14084
14085  // Quit if not SETCC.
14086  // FIXME: So far we only handle the boolean value generated from SETCC. If
14087  // there is other ways to generate boolean values, we need handle them here
14088  // as well.
14089  if (SetCC.getOpcode() != X86ISD::SETCC)
14090    return SDValue();
14091
14092  // Set the condition code or opposite one if necessary.
14093  CC = X86::CondCode(SetCC.getConstantOperandVal(0));
14094  if (needOppositeCond)
14095    CC = X86::GetOppositeBranchCondition(CC);
14096
14097  return SetCC.getOperand(1);
14098}
14099
14100/// checkFlaggedOrCombine - DAG combination on X86ISD::OR, i.e. with EFLAGS
14101/// updated. If only flag result is used and the result is evaluated from a
14102/// series of element extraction, try to combine it into a PTEST.
14103static SDValue checkFlaggedOrCombine(SDValue Or, X86::CondCode &CC,
14104                                     SelectionDAG &DAG,
14105                                     const X86Subtarget *Subtarget) {
14106  SDNode *N = Or.getNode();
14107  DebugLoc DL = N->getDebugLoc();
14108
14109  // Only SSE4.1 and beyond supports PTEST or like.
14110  if (!Subtarget->hasSSE41())
14111    return SDValue();
14112
14113  if (N->getOpcode() != X86ISD::OR)
14114    return SDValue();
14115
14116  // Quit if the value result of OR is used.
14117  if (N->hasAnyUseOfValue(0))
14118    return SDValue();
14119
14120  // Quit if not used as a boolean value.
14121  if (CC != X86::COND_E && CC != X86::COND_NE)
14122    return SDValue();
14123
14124  SmallVector<SDValue, 8> Opnds;
14125  SDValue VecIn;
14126  EVT VT = MVT::Other;
14127  unsigned Mask = 0;
14128
14129  // Recognize a special case where a vector is casted into wide integer to
14130  // test all 0s.
14131  Opnds.push_back(N->getOperand(0));
14132  Opnds.push_back(N->getOperand(1));
14133
14134  for (unsigned Slot = 0, e = Opnds.size(); Slot < e; ++Slot) {
14135    SmallVector<SDValue, 8>::const_iterator I = Opnds.begin() + Slot;
14136    // BFS traverse all OR'd operands.
14137    if (I->getOpcode() == ISD::OR) {
14138      Opnds.push_back(I->getOperand(0));
14139      Opnds.push_back(I->getOperand(1));
14140      // Re-evaluate the number of nodes to be traversed.
14141      e += 2; // 2 more nodes (LHS and RHS) are pushed.
14142      continue;
14143    }
14144
14145    // Quit if a non-EXTRACT_VECTOR_ELT
14146    if (I->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
14147      return SDValue();
14148
14149    // Quit if without a constant index.
14150    SDValue Idx = I->getOperand(1);
14151    if (!isa<ConstantSDNode>(Idx))
14152      return SDValue();
14153
14154    // Check if all elements are extracted from the same vector.
14155    SDValue ExtractedFromVec = I->getOperand(0);
14156    if (VecIn.getNode() == 0) {
14157      VT = ExtractedFromVec.getValueType();
14158      // FIXME: only 128-bit vector is supported so far.
14159      if (!VT.is128BitVector())
14160        return SDValue();
14161      VecIn = ExtractedFromVec;
14162    } else if (VecIn != ExtractedFromVec)
14163      return SDValue();
14164
14165    // Record the constant index.
14166    Mask |= 1U << cast<ConstantSDNode>(Idx)->getZExtValue();
14167  }
14168
14169  assert(VT.is128BitVector() && "Only 128-bit vector PTEST is supported so far.");
14170
14171  // Quit if not all elements are used.
14172  if (Mask != (1U << VT.getVectorNumElements()) - 1U)
14173    return SDValue();
14174
14175  return DAG.getNode(X86ISD::PTEST, DL, MVT::i32, VecIn, VecIn);
14176}
14177
14178static bool isValidFCMOVCondition(X86::CondCode CC) {
14179  switch (CC) {
14180  default:
14181    return false;
14182  case X86::COND_B:
14183  case X86::COND_BE:
14184  case X86::COND_E:
14185  case X86::COND_P:
14186  case X86::COND_AE:
14187  case X86::COND_A:
14188  case X86::COND_NE:
14189  case X86::COND_NP:
14190    return true;
14191  }
14192}
14193
14194/// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
14195static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
14196                                  TargetLowering::DAGCombinerInfo &DCI,
14197                                  const X86Subtarget *Subtarget) {
14198  DebugLoc DL = N->getDebugLoc();
14199
14200  // If the flag operand isn't dead, don't touch this CMOV.
14201  if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
14202    return SDValue();
14203
14204  SDValue FalseOp = N->getOperand(0);
14205  SDValue TrueOp = N->getOperand(1);
14206  X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
14207  SDValue Cond = N->getOperand(3);
14208
14209  if (CC == X86::COND_E || CC == X86::COND_NE) {
14210    switch (Cond.getOpcode()) {
14211    default: break;
14212    case X86ISD::BSR:
14213    case X86ISD::BSF:
14214      // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
14215      if (DAG.isKnownNeverZero(Cond.getOperand(0)))
14216        return (CC == X86::COND_E) ? FalseOp : TrueOp;
14217    }
14218  }
14219
14220  SDValue Flags;
14221
14222  Flags = checkBoolTestSetCCCombine(Cond, CC);
14223  if (Flags.getNode() &&
14224      // Extra check as FCMOV only supports a subset of X86 cond.
14225      (FalseOp.getValueType() != MVT::f80 || isValidFCMOVCondition(CC))) {
14226    SDValue Ops[] = { FalseOp, TrueOp,
14227                      DAG.getConstant(CC, MVT::i8), Flags };
14228    return DAG.getNode(X86ISD::CMOV, DL, N->getVTList(),
14229                       Ops, array_lengthof(Ops));
14230  }
14231
14232  Flags = checkFlaggedOrCombine(Cond, CC, DAG, Subtarget);
14233  if (Flags.getNode()) {
14234    SDValue Ops[] = { FalseOp, TrueOp,
14235                      DAG.getConstant(CC, MVT::i8), Flags };
14236    return DAG.getNode(X86ISD::CMOV, DL, N->getVTList(),
14237                       Ops, array_lengthof(Ops));
14238  }
14239
14240  // If this is a select between two integer constants, try to do some
14241  // optimizations.  Note that the operands are ordered the opposite of SELECT
14242  // operands.
14243  if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
14244    if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
14245      // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
14246      // larger than FalseC (the false value).
14247      if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
14248        CC = X86::GetOppositeBranchCondition(CC);
14249        std::swap(TrueC, FalseC);
14250      }
14251
14252      // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3.  Likewise for any pow2/0.
14253      // This is efficient for any integer data type (including i8/i16) and
14254      // shift amount.
14255      if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
14256        Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
14257                           DAG.getConstant(CC, MVT::i8), Cond);
14258
14259        // Zero extend the condition if needed.
14260        Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
14261
14262        unsigned ShAmt = TrueC->getAPIntValue().logBase2();
14263        Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
14264                           DAG.getConstant(ShAmt, MVT::i8));
14265        if (N->getNumValues() == 2)  // Dead flag value?
14266          return DCI.CombineTo(N, Cond, SDValue());
14267        return Cond;
14268      }
14269
14270      // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.  This is efficient
14271      // for any integer data type, including i8/i16.
14272      if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
14273        Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
14274                           DAG.getConstant(CC, MVT::i8), Cond);
14275
14276        // Zero extend the condition if needed.
14277        Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
14278                           FalseC->getValueType(0), Cond);
14279        Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
14280                           SDValue(FalseC, 0));
14281
14282        if (N->getNumValues() == 2)  // Dead flag value?
14283          return DCI.CombineTo(N, Cond, SDValue());
14284        return Cond;
14285      }
14286
14287      // Optimize cases that will turn into an LEA instruction.  This requires
14288      // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
14289      if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
14290        uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
14291        if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
14292
14293        bool isFastMultiplier = false;
14294        if (Diff < 10) {
14295          switch ((unsigned char)Diff) {
14296          default: break;
14297          case 1:  // result = add base, cond
14298          case 2:  // result = lea base(    , cond*2)
14299          case 3:  // result = lea base(cond, cond*2)
14300          case 4:  // result = lea base(    , cond*4)
14301          case 5:  // result = lea base(cond, cond*4)
14302          case 8:  // result = lea base(    , cond*8)
14303          case 9:  // result = lea base(cond, cond*8)
14304            isFastMultiplier = true;
14305            break;
14306          }
14307        }
14308
14309        if (isFastMultiplier) {
14310          APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
14311          Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
14312                             DAG.getConstant(CC, MVT::i8), Cond);
14313          // Zero extend the condition if needed.
14314          Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
14315                             Cond);
14316          // Scale the condition by the difference.
14317          if (Diff != 1)
14318            Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
14319                               DAG.getConstant(Diff, Cond.getValueType()));
14320
14321          // Add the base if non-zero.
14322          if (FalseC->getAPIntValue() != 0)
14323            Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
14324                               SDValue(FalseC, 0));
14325          if (N->getNumValues() == 2)  // Dead flag value?
14326            return DCI.CombineTo(N, Cond, SDValue());
14327          return Cond;
14328        }
14329      }
14330    }
14331  }
14332  return SDValue();
14333}
14334
14335
14336/// PerformMulCombine - Optimize a single multiply with constant into two
14337/// in order to implement it with two cheaper instructions, e.g.
14338/// LEA + SHL, LEA + LEA.
14339static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
14340                                 TargetLowering::DAGCombinerInfo &DCI) {
14341  if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
14342    return SDValue();
14343
14344  EVT VT = N->getValueType(0);
14345  if (VT != MVT::i64)
14346    return SDValue();
14347
14348  ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
14349  if (!C)
14350    return SDValue();
14351  uint64_t MulAmt = C->getZExtValue();
14352  if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
14353    return SDValue();
14354
14355  uint64_t MulAmt1 = 0;
14356  uint64_t MulAmt2 = 0;
14357  if ((MulAmt % 9) == 0) {
14358    MulAmt1 = 9;
14359    MulAmt2 = MulAmt / 9;
14360  } else if ((MulAmt % 5) == 0) {
14361    MulAmt1 = 5;
14362    MulAmt2 = MulAmt / 5;
14363  } else if ((MulAmt % 3) == 0) {
14364    MulAmt1 = 3;
14365    MulAmt2 = MulAmt / 3;
14366  }
14367  if (MulAmt2 &&
14368      (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
14369    DebugLoc DL = N->getDebugLoc();
14370
14371    if (isPowerOf2_64(MulAmt2) &&
14372        !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
14373      // If second multiplifer is pow2, issue it first. We want the multiply by
14374      // 3, 5, or 9 to be folded into the addressing mode unless the lone use
14375      // is an add.
14376      std::swap(MulAmt1, MulAmt2);
14377
14378    SDValue NewMul;
14379    if (isPowerOf2_64(MulAmt1))
14380      NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
14381                           DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
14382    else
14383      NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
14384                           DAG.getConstant(MulAmt1, VT));
14385
14386    if (isPowerOf2_64(MulAmt2))
14387      NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
14388                           DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
14389    else
14390      NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
14391                           DAG.getConstant(MulAmt2, VT));
14392
14393    // Do not add new nodes to DAG combiner worklist.
14394    DCI.CombineTo(N, NewMul, false);
14395  }
14396  return SDValue();
14397}
14398
14399static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
14400  SDValue N0 = N->getOperand(0);
14401  SDValue N1 = N->getOperand(1);
14402  ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
14403  EVT VT = N0.getValueType();
14404
14405  // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
14406  // since the result of setcc_c is all zero's or all ones.
14407  if (VT.isInteger() && !VT.isVector() &&
14408      N1C && N0.getOpcode() == ISD::AND &&
14409      N0.getOperand(1).getOpcode() == ISD::Constant) {
14410    SDValue N00 = N0.getOperand(0);
14411    if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
14412        ((N00.getOpcode() == ISD::ANY_EXTEND ||
14413          N00.getOpcode() == ISD::ZERO_EXTEND) &&
14414         N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
14415      APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
14416      APInt ShAmt = N1C->getAPIntValue();
14417      Mask = Mask.shl(ShAmt);
14418      if (Mask != 0)
14419        return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
14420                           N00, DAG.getConstant(Mask, VT));
14421    }
14422  }
14423
14424
14425  // Hardware support for vector shifts is sparse which makes us scalarize the
14426  // vector operations in many cases. Also, on sandybridge ADD is faster than
14427  // shl.
14428  // (shl V, 1) -> add V,V
14429  if (isSplatVector(N1.getNode())) {
14430    assert(N0.getValueType().isVector() && "Invalid vector shift type");
14431    ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1->getOperand(0));
14432    // We shift all of the values by one. In many cases we do not have
14433    // hardware support for this operation. This is better expressed as an ADD
14434    // of two values.
14435    if (N1C && (1 == N1C->getZExtValue())) {
14436      return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, N0, N0);
14437    }
14438  }
14439
14440  return SDValue();
14441}
14442
14443/// PerformShiftCombine - Transforms vector shift nodes to use vector shifts
14444///                       when possible.
14445static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
14446                                   TargetLowering::DAGCombinerInfo &DCI,
14447                                   const X86Subtarget *Subtarget) {
14448  EVT VT = N->getValueType(0);
14449  if (N->getOpcode() == ISD::SHL) {
14450    SDValue V = PerformSHLCombine(N, DAG);
14451    if (V.getNode()) return V;
14452  }
14453
14454  // On X86 with SSE2 support, we can transform this to a vector shift if
14455  // all elements are shifted by the same amount.  We can't do this in legalize
14456  // because the a constant vector is typically transformed to a constant pool
14457  // so we have no knowledge of the shift amount.
14458  if (!Subtarget->hasSSE2())
14459    return SDValue();
14460
14461  if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16 &&
14462      (!Subtarget->hasAVX2() ||
14463       (VT != MVT::v4i64 && VT != MVT::v8i32 && VT != MVT::v16i16)))
14464    return SDValue();
14465
14466  SDValue ShAmtOp = N->getOperand(1);
14467  EVT EltVT = VT.getVectorElementType();
14468  DebugLoc DL = N->getDebugLoc();
14469  SDValue BaseShAmt = SDValue();
14470  if (ShAmtOp.getOpcode() == ISD::BUILD_VECTOR) {
14471    unsigned NumElts = VT.getVectorNumElements();
14472    unsigned i = 0;
14473    for (; i != NumElts; ++i) {
14474      SDValue Arg = ShAmtOp.getOperand(i);
14475      if (Arg.getOpcode() == ISD::UNDEF) continue;
14476      BaseShAmt = Arg;
14477      break;
14478    }
14479    // Handle the case where the build_vector is all undef
14480    // FIXME: Should DAG allow this?
14481    if (i == NumElts)
14482      return SDValue();
14483
14484    for (; i != NumElts; ++i) {
14485      SDValue Arg = ShAmtOp.getOperand(i);
14486      if (Arg.getOpcode() == ISD::UNDEF) continue;
14487      if (Arg != BaseShAmt) {
14488        return SDValue();
14489      }
14490    }
14491  } else if (ShAmtOp.getOpcode() == ISD::VECTOR_SHUFFLE &&
14492             cast<ShuffleVectorSDNode>(ShAmtOp)->isSplat()) {
14493    SDValue InVec = ShAmtOp.getOperand(0);
14494    if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
14495      unsigned NumElts = InVec.getValueType().getVectorNumElements();
14496      unsigned i = 0;
14497      for (; i != NumElts; ++i) {
14498        SDValue Arg = InVec.getOperand(i);
14499        if (Arg.getOpcode() == ISD::UNDEF) continue;
14500        BaseShAmt = Arg;
14501        break;
14502      }
14503    } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
14504       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
14505         unsigned SplatIdx= cast<ShuffleVectorSDNode>(ShAmtOp)->getSplatIndex();
14506         if (C->getZExtValue() == SplatIdx)
14507           BaseShAmt = InVec.getOperand(1);
14508       }
14509    }
14510    if (BaseShAmt.getNode() == 0) {
14511      // Don't create instructions with illegal types after legalize
14512      // types has run.
14513      if (!DAG.getTargetLoweringInfo().isTypeLegal(EltVT) &&
14514          !DCI.isBeforeLegalize())
14515        return SDValue();
14516
14517      BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, ShAmtOp,
14518                              DAG.getIntPtrConstant(0));
14519    }
14520  } else
14521    return SDValue();
14522
14523  // The shift amount is an i32.
14524  if (EltVT.bitsGT(MVT::i32))
14525    BaseShAmt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, BaseShAmt);
14526  else if (EltVT.bitsLT(MVT::i32))
14527    BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, BaseShAmt);
14528
14529  // The shift amount is identical so we can do a vector shift.
14530  SDValue  ValOp = N->getOperand(0);
14531  switch (N->getOpcode()) {
14532  default:
14533    llvm_unreachable("Unknown shift opcode!");
14534  case ISD::SHL:
14535    switch (VT.getSimpleVT().SimpleTy) {
14536    default: return SDValue();
14537    case MVT::v2i64:
14538    case MVT::v4i32:
14539    case MVT::v8i16:
14540    case MVT::v4i64:
14541    case MVT::v8i32:
14542    case MVT::v16i16:
14543      return getTargetVShiftNode(X86ISD::VSHLI, DL, VT, ValOp, BaseShAmt, DAG);
14544    }
14545  case ISD::SRA:
14546    switch (VT.getSimpleVT().SimpleTy) {
14547    default: return SDValue();
14548    case MVT::v4i32:
14549    case MVT::v8i16:
14550    case MVT::v8i32:
14551    case MVT::v16i16:
14552      return getTargetVShiftNode(X86ISD::VSRAI, DL, VT, ValOp, BaseShAmt, DAG);
14553    }
14554  case ISD::SRL:
14555    switch (VT.getSimpleVT().SimpleTy) {
14556    default: return SDValue();
14557    case MVT::v2i64:
14558    case MVT::v4i32:
14559    case MVT::v8i16:
14560    case MVT::v4i64:
14561    case MVT::v8i32:
14562    case MVT::v16i16:
14563      return getTargetVShiftNode(X86ISD::VSRLI, DL, VT, ValOp, BaseShAmt, DAG);
14564    }
14565  }
14566}
14567
14568
14569// CMPEQCombine - Recognize the distinctive  (AND (setcc ...) (setcc ..))
14570// where both setccs reference the same FP CMP, and rewrite for CMPEQSS
14571// and friends.  Likewise for OR -> CMPNEQSS.
14572static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
14573                            TargetLowering::DAGCombinerInfo &DCI,
14574                            const X86Subtarget *Subtarget) {
14575  unsigned opcode;
14576
14577  // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
14578  // we're requiring SSE2 for both.
14579  if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
14580    SDValue N0 = N->getOperand(0);
14581    SDValue N1 = N->getOperand(1);
14582    SDValue CMP0 = N0->getOperand(1);
14583    SDValue CMP1 = N1->getOperand(1);
14584    DebugLoc DL = N->getDebugLoc();
14585
14586    // The SETCCs should both refer to the same CMP.
14587    if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
14588      return SDValue();
14589
14590    SDValue CMP00 = CMP0->getOperand(0);
14591    SDValue CMP01 = CMP0->getOperand(1);
14592    EVT     VT    = CMP00.getValueType();
14593
14594    if (VT == MVT::f32 || VT == MVT::f64) {
14595      bool ExpectingFlags = false;
14596      // Check for any users that want flags:
14597      for (SDNode::use_iterator UI = N->use_begin(),
14598             UE = N->use_end();
14599           !ExpectingFlags && UI != UE; ++UI)
14600        switch (UI->getOpcode()) {
14601        default:
14602        case ISD::BR_CC:
14603        case ISD::BRCOND:
14604        case ISD::SELECT:
14605          ExpectingFlags = true;
14606          break;
14607        case ISD::CopyToReg:
14608        case ISD::SIGN_EXTEND:
14609        case ISD::ZERO_EXTEND:
14610        case ISD::ANY_EXTEND:
14611          break;
14612        }
14613
14614      if (!ExpectingFlags) {
14615        enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
14616        enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
14617
14618        if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
14619          X86::CondCode tmp = cc0;
14620          cc0 = cc1;
14621          cc1 = tmp;
14622        }
14623
14624        if ((cc0 == X86::COND_E  && cc1 == X86::COND_NP) ||
14625            (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
14626          bool is64BitFP = (CMP00.getValueType() == MVT::f64);
14627          X86ISD::NodeType NTOperator = is64BitFP ?
14628            X86ISD::FSETCCsd : X86ISD::FSETCCss;
14629          // FIXME: need symbolic constants for these magic numbers.
14630          // See X86ATTInstPrinter.cpp:printSSECC().
14631          unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
14632          SDValue OnesOrZeroesF = DAG.getNode(NTOperator, DL, MVT::f32, CMP00, CMP01,
14633                                              DAG.getConstant(x86cc, MVT::i8));
14634          SDValue OnesOrZeroesI = DAG.getNode(ISD::BITCAST, DL, MVT::i32,
14635                                              OnesOrZeroesF);
14636          SDValue ANDed = DAG.getNode(ISD::AND, DL, MVT::i32, OnesOrZeroesI,
14637                                      DAG.getConstant(1, MVT::i32));
14638          SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8, ANDed);
14639          return OneBitOfTruth;
14640        }
14641      }
14642    }
14643  }
14644  return SDValue();
14645}
14646
14647/// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
14648/// so it can be folded inside ANDNP.
14649static bool CanFoldXORWithAllOnes(const SDNode *N) {
14650  EVT VT = N->getValueType(0);
14651
14652  // Match direct AllOnes for 128 and 256-bit vectors
14653  if (ISD::isBuildVectorAllOnes(N))
14654    return true;
14655
14656  // Look through a bit convert.
14657  if (N->getOpcode() == ISD::BITCAST)
14658    N = N->getOperand(0).getNode();
14659
14660  // Sometimes the operand may come from a insert_subvector building a 256-bit
14661  // allones vector
14662  if (VT.is256BitVector() &&
14663      N->getOpcode() == ISD::INSERT_SUBVECTOR) {
14664    SDValue V1 = N->getOperand(0);
14665    SDValue V2 = N->getOperand(1);
14666
14667    if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
14668        V1.getOperand(0).getOpcode() == ISD::UNDEF &&
14669        ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
14670        ISD::isBuildVectorAllOnes(V2.getNode()))
14671      return true;
14672  }
14673
14674  return false;
14675}
14676
14677static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
14678                                 TargetLowering::DAGCombinerInfo &DCI,
14679                                 const X86Subtarget *Subtarget) {
14680  if (DCI.isBeforeLegalizeOps())
14681    return SDValue();
14682
14683  SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
14684  if (R.getNode())
14685    return R;
14686
14687  EVT VT = N->getValueType(0);
14688
14689  // Create ANDN, BLSI, and BLSR instructions
14690  // BLSI is X & (-X)
14691  // BLSR is X & (X-1)
14692  if (Subtarget->hasBMI() && (VT == MVT::i32 || VT == MVT::i64)) {
14693    SDValue N0 = N->getOperand(0);
14694    SDValue N1 = N->getOperand(1);
14695    DebugLoc DL = N->getDebugLoc();
14696
14697    // Check LHS for not
14698    if (N0.getOpcode() == ISD::XOR && isAllOnes(N0.getOperand(1)))
14699      return DAG.getNode(X86ISD::ANDN, DL, VT, N0.getOperand(0), N1);
14700    // Check RHS for not
14701    if (N1.getOpcode() == ISD::XOR && isAllOnes(N1.getOperand(1)))
14702      return DAG.getNode(X86ISD::ANDN, DL, VT, N1.getOperand(0), N0);
14703
14704    // Check LHS for neg
14705    if (N0.getOpcode() == ISD::SUB && N0.getOperand(1) == N1 &&
14706        isZero(N0.getOperand(0)))
14707      return DAG.getNode(X86ISD::BLSI, DL, VT, N1);
14708
14709    // Check RHS for neg
14710    if (N1.getOpcode() == ISD::SUB && N1.getOperand(1) == N0 &&
14711        isZero(N1.getOperand(0)))
14712      return DAG.getNode(X86ISD::BLSI, DL, VT, N0);
14713
14714    // Check LHS for X-1
14715    if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1 &&
14716        isAllOnes(N0.getOperand(1)))
14717      return DAG.getNode(X86ISD::BLSR, DL, VT, N1);
14718
14719    // Check RHS for X-1
14720    if (N1.getOpcode() == ISD::ADD && N1.getOperand(0) == N0 &&
14721        isAllOnes(N1.getOperand(1)))
14722      return DAG.getNode(X86ISD::BLSR, DL, VT, N0);
14723
14724    return SDValue();
14725  }
14726
14727  // Want to form ANDNP nodes:
14728  // 1) In the hopes of then easily combining them with OR and AND nodes
14729  //    to form PBLEND/PSIGN.
14730  // 2) To match ANDN packed intrinsics
14731  if (VT != MVT::v2i64 && VT != MVT::v4i64)
14732    return SDValue();
14733
14734  SDValue N0 = N->getOperand(0);
14735  SDValue N1 = N->getOperand(1);
14736  DebugLoc DL = N->getDebugLoc();
14737
14738  // Check LHS for vnot
14739  if (N0.getOpcode() == ISD::XOR &&
14740      //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
14741      CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
14742    return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
14743
14744  // Check RHS for vnot
14745  if (N1.getOpcode() == ISD::XOR &&
14746      //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
14747      CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
14748    return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
14749
14750  return SDValue();
14751}
14752
14753static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
14754                                TargetLowering::DAGCombinerInfo &DCI,
14755                                const X86Subtarget *Subtarget) {
14756  if (DCI.isBeforeLegalizeOps())
14757    return SDValue();
14758
14759  SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
14760  if (R.getNode())
14761    return R;
14762
14763  EVT VT = N->getValueType(0);
14764
14765  SDValue N0 = N->getOperand(0);
14766  SDValue N1 = N->getOperand(1);
14767
14768  // look for psign/blend
14769  if (VT == MVT::v2i64 || VT == MVT::v4i64) {
14770    if (!Subtarget->hasSSSE3() ||
14771        (VT == MVT::v4i64 && !Subtarget->hasAVX2()))
14772      return SDValue();
14773
14774    // Canonicalize pandn to RHS
14775    if (N0.getOpcode() == X86ISD::ANDNP)
14776      std::swap(N0, N1);
14777    // or (and (m, y), (pandn m, x))
14778    if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
14779      SDValue Mask = N1.getOperand(0);
14780      SDValue X    = N1.getOperand(1);
14781      SDValue Y;
14782      if (N0.getOperand(0) == Mask)
14783        Y = N0.getOperand(1);
14784      if (N0.getOperand(1) == Mask)
14785        Y = N0.getOperand(0);
14786
14787      // Check to see if the mask appeared in both the AND and ANDNP and
14788      if (!Y.getNode())
14789        return SDValue();
14790
14791      // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
14792      // Look through mask bitcast.
14793      if (Mask.getOpcode() == ISD::BITCAST)
14794        Mask = Mask.getOperand(0);
14795      if (X.getOpcode() == ISD::BITCAST)
14796        X = X.getOperand(0);
14797      if (Y.getOpcode() == ISD::BITCAST)
14798        Y = Y.getOperand(0);
14799
14800      EVT MaskVT = Mask.getValueType();
14801
14802      // Validate that the Mask operand is a vector sra node.
14803      // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
14804      // there is no psrai.b
14805      if (Mask.getOpcode() != X86ISD::VSRAI)
14806        return SDValue();
14807
14808      // Check that the SRA is all signbits.
14809      SDValue SraC = Mask.getOperand(1);
14810      unsigned SraAmt  = cast<ConstantSDNode>(SraC)->getZExtValue();
14811      unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
14812      if ((SraAmt + 1) != EltBits)
14813        return SDValue();
14814
14815      DebugLoc DL = N->getDebugLoc();
14816
14817      // Now we know we at least have a plendvb with the mask val.  See if
14818      // we can form a psignb/w/d.
14819      // psign = x.type == y.type == mask.type && y = sub(0, x);
14820      if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
14821          ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
14822          X.getValueType() == MaskVT && Y.getValueType() == MaskVT) {
14823        assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
14824               "Unsupported VT for PSIGN");
14825        Mask = DAG.getNode(X86ISD::PSIGN, DL, MaskVT, X, Mask.getOperand(0));
14826        return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
14827      }
14828      // PBLENDVB only available on SSE 4.1
14829      if (!Subtarget->hasSSE41())
14830        return SDValue();
14831
14832      EVT BlendVT = (VT == MVT::v4i64) ? MVT::v32i8 : MVT::v16i8;
14833
14834      X = DAG.getNode(ISD::BITCAST, DL, BlendVT, X);
14835      Y = DAG.getNode(ISD::BITCAST, DL, BlendVT, Y);
14836      Mask = DAG.getNode(ISD::BITCAST, DL, BlendVT, Mask);
14837      Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, Y, X);
14838      return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
14839    }
14840  }
14841
14842  if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
14843    return SDValue();
14844
14845  // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
14846  if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
14847    std::swap(N0, N1);
14848  if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
14849    return SDValue();
14850  if (!N0.hasOneUse() || !N1.hasOneUse())
14851    return SDValue();
14852
14853  SDValue ShAmt0 = N0.getOperand(1);
14854  if (ShAmt0.getValueType() != MVT::i8)
14855    return SDValue();
14856  SDValue ShAmt1 = N1.getOperand(1);
14857  if (ShAmt1.getValueType() != MVT::i8)
14858    return SDValue();
14859  if (ShAmt0.getOpcode() == ISD::TRUNCATE)
14860    ShAmt0 = ShAmt0.getOperand(0);
14861  if (ShAmt1.getOpcode() == ISD::TRUNCATE)
14862    ShAmt1 = ShAmt1.getOperand(0);
14863
14864  DebugLoc DL = N->getDebugLoc();
14865  unsigned Opc = X86ISD::SHLD;
14866  SDValue Op0 = N0.getOperand(0);
14867  SDValue Op1 = N1.getOperand(0);
14868  if (ShAmt0.getOpcode() == ISD::SUB) {
14869    Opc = X86ISD::SHRD;
14870    std::swap(Op0, Op1);
14871    std::swap(ShAmt0, ShAmt1);
14872  }
14873
14874  unsigned Bits = VT.getSizeInBits();
14875  if (ShAmt1.getOpcode() == ISD::SUB) {
14876    SDValue Sum = ShAmt1.getOperand(0);
14877    if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
14878      SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
14879      if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
14880        ShAmt1Op1 = ShAmt1Op1.getOperand(0);
14881      if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
14882        return DAG.getNode(Opc, DL, VT,
14883                           Op0, Op1,
14884                           DAG.getNode(ISD::TRUNCATE, DL,
14885                                       MVT::i8, ShAmt0));
14886    }
14887  } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
14888    ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
14889    if (ShAmt0C &&
14890        ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
14891      return DAG.getNode(Opc, DL, VT,
14892                         N0.getOperand(0), N1.getOperand(0),
14893                         DAG.getNode(ISD::TRUNCATE, DL,
14894                                       MVT::i8, ShAmt0));
14895  }
14896
14897  return SDValue();
14898}
14899
14900// Generate NEG and CMOV for integer abs.
14901static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
14902  EVT VT = N->getValueType(0);
14903
14904  // Since X86 does not have CMOV for 8-bit integer, we don't convert
14905  // 8-bit integer abs to NEG and CMOV.
14906  if (VT.isInteger() && VT.getSizeInBits() == 8)
14907    return SDValue();
14908
14909  SDValue N0 = N->getOperand(0);
14910  SDValue N1 = N->getOperand(1);
14911  DebugLoc DL = N->getDebugLoc();
14912
14913  // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
14914  // and change it to SUB and CMOV.
14915  if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
14916      N0.getOpcode() == ISD::ADD &&
14917      N0.getOperand(1) == N1 &&
14918      N1.getOpcode() == ISD::SRA &&
14919      N1.getOperand(0) == N0.getOperand(0))
14920    if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
14921      if (Y1C->getAPIntValue() == VT.getSizeInBits()-1) {
14922        // Generate SUB & CMOV.
14923        SDValue Neg = DAG.getNode(X86ISD::SUB, DL, DAG.getVTList(VT, MVT::i32),
14924                                  DAG.getConstant(0, VT), N0.getOperand(0));
14925
14926        SDValue Ops[] = { N0.getOperand(0), Neg,
14927                          DAG.getConstant(X86::COND_GE, MVT::i8),
14928                          SDValue(Neg.getNode(), 1) };
14929        return DAG.getNode(X86ISD::CMOV, DL, DAG.getVTList(VT, MVT::Glue),
14930                           Ops, array_lengthof(Ops));
14931      }
14932  return SDValue();
14933}
14934
14935// PerformXorCombine - Attempts to turn XOR nodes into BLSMSK nodes
14936static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
14937                                 TargetLowering::DAGCombinerInfo &DCI,
14938                                 const X86Subtarget *Subtarget) {
14939  if (DCI.isBeforeLegalizeOps())
14940    return SDValue();
14941
14942  if (Subtarget->hasCMov()) {
14943    SDValue RV = performIntegerAbsCombine(N, DAG);
14944    if (RV.getNode())
14945      return RV;
14946  }
14947
14948  // Try forming BMI if it is available.
14949  if (!Subtarget->hasBMI())
14950    return SDValue();
14951
14952  EVT VT = N->getValueType(0);
14953
14954  if (VT != MVT::i32 && VT != MVT::i64)
14955    return SDValue();
14956
14957  assert(Subtarget->hasBMI() && "Creating BLSMSK requires BMI instructions");
14958
14959  // Create BLSMSK instructions by finding X ^ (X-1)
14960  SDValue N0 = N->getOperand(0);
14961  SDValue N1 = N->getOperand(1);
14962  DebugLoc DL = N->getDebugLoc();
14963
14964  if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1 &&
14965      isAllOnes(N0.getOperand(1)))
14966    return DAG.getNode(X86ISD::BLSMSK, DL, VT, N1);
14967
14968  if (N1.getOpcode() == ISD::ADD && N1.getOperand(0) == N0 &&
14969      isAllOnes(N1.getOperand(1)))
14970    return DAG.getNode(X86ISD::BLSMSK, DL, VT, N0);
14971
14972  return SDValue();
14973}
14974
14975/// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
14976static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
14977                                  TargetLowering::DAGCombinerInfo &DCI,
14978                                  const X86Subtarget *Subtarget) {
14979  LoadSDNode *Ld = cast<LoadSDNode>(N);
14980  EVT RegVT = Ld->getValueType(0);
14981  EVT MemVT = Ld->getMemoryVT();
14982  DebugLoc dl = Ld->getDebugLoc();
14983  const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14984
14985  ISD::LoadExtType Ext = Ld->getExtensionType();
14986
14987  // If this is a vector EXT Load then attempt to optimize it using a
14988  // shuffle. We need SSE4 for the shuffles.
14989  // TODO: It is possible to support ZExt by zeroing the undef values
14990  // during the shuffle phase or after the shuffle.
14991  if (RegVT.isVector() && RegVT.isInteger() &&
14992      Ext == ISD::EXTLOAD && Subtarget->hasSSE41()) {
14993    assert(MemVT != RegVT && "Cannot extend to the same type");
14994    assert(MemVT.isVector() && "Must load a vector from memory");
14995
14996    unsigned NumElems = RegVT.getVectorNumElements();
14997    unsigned RegSz = RegVT.getSizeInBits();
14998    unsigned MemSz = MemVT.getSizeInBits();
14999    assert(RegSz > MemSz && "Register size must be greater than the mem size");
15000
15001    // All sizes must be a power of two.
15002    if (!isPowerOf2_32(RegSz * MemSz * NumElems))
15003      return SDValue();
15004
15005    // Attempt to load the original value using scalar loads.
15006    // Find the largest scalar type that divides the total loaded size.
15007    MVT SclrLoadTy = MVT::i8;
15008    for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
15009         tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
15010      MVT Tp = (MVT::SimpleValueType)tp;
15011      if (TLI.isTypeLegal(Tp) && ((MemSz % Tp.getSizeInBits()) == 0)) {
15012        SclrLoadTy = Tp;
15013      }
15014    }
15015
15016    // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
15017    if (TLI.isTypeLegal(MVT::f64) && SclrLoadTy.getSizeInBits() < 64 &&
15018        (64 <= MemSz))
15019      SclrLoadTy = MVT::f64;
15020
15021    // Calculate the number of scalar loads that we need to perform
15022    // in order to load our vector from memory.
15023    unsigned NumLoads = MemSz / SclrLoadTy.getSizeInBits();
15024
15025    // Represent our vector as a sequence of elements which are the
15026    // largest scalar that we can load.
15027    EVT LoadUnitVecVT = EVT::getVectorVT(*DAG.getContext(), SclrLoadTy,
15028      RegSz/SclrLoadTy.getSizeInBits());
15029
15030    // Represent the data using the same element type that is stored in
15031    // memory. In practice, we ''widen'' MemVT.
15032    EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
15033                                  RegSz/MemVT.getScalarType().getSizeInBits());
15034
15035    assert(WideVecVT.getSizeInBits() == LoadUnitVecVT.getSizeInBits() &&
15036      "Invalid vector type");
15037
15038    // We can't shuffle using an illegal type.
15039    if (!TLI.isTypeLegal(WideVecVT))
15040      return SDValue();
15041
15042    SmallVector<SDValue, 8> Chains;
15043    SDValue Ptr = Ld->getBasePtr();
15044    SDValue Increment = DAG.getConstant(SclrLoadTy.getSizeInBits()/8,
15045                                        TLI.getPointerTy());
15046    SDValue Res = DAG.getUNDEF(LoadUnitVecVT);
15047
15048    for (unsigned i = 0; i < NumLoads; ++i) {
15049      // Perform a single load.
15050      SDValue ScalarLoad = DAG.getLoad(SclrLoadTy, dl, Ld->getChain(),
15051                                       Ptr, Ld->getPointerInfo(),
15052                                       Ld->isVolatile(), Ld->isNonTemporal(),
15053                                       Ld->isInvariant(), Ld->getAlignment());
15054      Chains.push_back(ScalarLoad.getValue(1));
15055      // Create the first element type using SCALAR_TO_VECTOR in order to avoid
15056      // another round of DAGCombining.
15057      if (i == 0)
15058        Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LoadUnitVecVT, ScalarLoad);
15059      else
15060        Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, LoadUnitVecVT, Res,
15061                          ScalarLoad, DAG.getIntPtrConstant(i));
15062
15063      Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
15064    }
15065
15066    SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Chains[0],
15067                               Chains.size());
15068
15069    // Bitcast the loaded value to a vector of the original element type, in
15070    // the size of the target vector type.
15071    SDValue SlicedVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Res);
15072    unsigned SizeRatio = RegSz/MemSz;
15073
15074    // Redistribute the loaded elements into the different locations.
15075    SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
15076    for (unsigned i = 0; i != NumElems; ++i)
15077      ShuffleVec[i*SizeRatio] = i;
15078
15079    SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
15080                                         DAG.getUNDEF(WideVecVT),
15081                                         &ShuffleVec[0]);
15082
15083    // Bitcast to the requested type.
15084    Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
15085    // Replace the original load with the new sequence
15086    // and return the new chain.
15087    return DCI.CombineTo(N, Shuff, TF, true);
15088  }
15089
15090  return SDValue();
15091}
15092
15093/// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
15094static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
15095                                   const X86Subtarget *Subtarget) {
15096  StoreSDNode *St = cast<StoreSDNode>(N);
15097  EVT VT = St->getValue().getValueType();
15098  EVT StVT = St->getMemoryVT();
15099  DebugLoc dl = St->getDebugLoc();
15100  SDValue StoredVal = St->getOperand(1);
15101  const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15102
15103  // If we are saving a concatenation of two XMM registers, perform two stores.
15104  // On Sandy Bridge, 256-bit memory operations are executed by two
15105  // 128-bit ports. However, on Haswell it is better to issue a single 256-bit
15106  // memory  operation.
15107  if (VT.is256BitVector() && !Subtarget->hasAVX2() &&
15108      StoredVal.getNode()->getOpcode() == ISD::CONCAT_VECTORS &&
15109      StoredVal.getNumOperands() == 2) {
15110    SDValue Value0 = StoredVal.getOperand(0);
15111    SDValue Value1 = StoredVal.getOperand(1);
15112
15113    SDValue Stride = DAG.getConstant(16, TLI.getPointerTy());
15114    SDValue Ptr0 = St->getBasePtr();
15115    SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
15116
15117    SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
15118                                St->getPointerInfo(), St->isVolatile(),
15119                                St->isNonTemporal(), St->getAlignment());
15120    SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
15121                                St->getPointerInfo(), St->isVolatile(),
15122                                St->isNonTemporal(), St->getAlignment());
15123    return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
15124  }
15125
15126  // Optimize trunc store (of multiple scalars) to shuffle and store.
15127  // First, pack all of the elements in one place. Next, store to memory
15128  // in fewer chunks.
15129  if (St->isTruncatingStore() && VT.isVector()) {
15130    const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15131    unsigned NumElems = VT.getVectorNumElements();
15132    assert(StVT != VT && "Cannot truncate to the same type");
15133    unsigned FromSz = VT.getVectorElementType().getSizeInBits();
15134    unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
15135
15136    // From, To sizes and ElemCount must be pow of two
15137    if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
15138    // We are going to use the original vector elt for storing.
15139    // Accumulated smaller vector elements must be a multiple of the store size.
15140    if (0 != (NumElems * FromSz) % ToSz) return SDValue();
15141
15142    unsigned SizeRatio  = FromSz / ToSz;
15143
15144    assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
15145
15146    // Create a type on which we perform the shuffle
15147    EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
15148            StVT.getScalarType(), NumElems*SizeRatio);
15149
15150    assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
15151
15152    SDValue WideVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, St->getValue());
15153    SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
15154    for (unsigned i = 0; i != NumElems; ++i)
15155      ShuffleVec[i] = i * SizeRatio;
15156
15157    // Can't shuffle using an illegal type.
15158    if (!TLI.isTypeLegal(WideVecVT))
15159      return SDValue();
15160
15161    SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
15162                                         DAG.getUNDEF(WideVecVT),
15163                                         &ShuffleVec[0]);
15164    // At this point all of the data is stored at the bottom of the
15165    // register. We now need to save it to mem.
15166
15167    // Find the largest store unit
15168    MVT StoreType = MVT::i8;
15169    for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
15170         tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
15171      MVT Tp = (MVT::SimpleValueType)tp;
15172      if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToSz)
15173        StoreType = Tp;
15174    }
15175
15176    // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
15177    if (TLI.isTypeLegal(MVT::f64) && StoreType.getSizeInBits() < 64 &&
15178        (64 <= NumElems * ToSz))
15179      StoreType = MVT::f64;
15180
15181    // Bitcast the original vector into a vector of store-size units
15182    EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
15183            StoreType, VT.getSizeInBits()/StoreType.getSizeInBits());
15184    assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
15185    SDValue ShuffWide = DAG.getNode(ISD::BITCAST, dl, StoreVecVT, Shuff);
15186    SmallVector<SDValue, 8> Chains;
15187    SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
15188                                        TLI.getPointerTy());
15189    SDValue Ptr = St->getBasePtr();
15190
15191    // Perform one or more big stores into memory.
15192    for (unsigned i=0, e=(ToSz*NumElems)/StoreType.getSizeInBits(); i!=e; ++i) {
15193      SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
15194                                   StoreType, ShuffWide,
15195                                   DAG.getIntPtrConstant(i));
15196      SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
15197                                St->getPointerInfo(), St->isVolatile(),
15198                                St->isNonTemporal(), St->getAlignment());
15199      Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
15200      Chains.push_back(Ch);
15201    }
15202
15203    return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Chains[0],
15204                               Chains.size());
15205  }
15206
15207
15208  // Turn load->store of MMX types into GPR load/stores.  This avoids clobbering
15209  // the FP state in cases where an emms may be missing.
15210  // A preferable solution to the general problem is to figure out the right
15211  // places to insert EMMS.  This qualifies as a quick hack.
15212
15213  // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
15214  if (VT.getSizeInBits() != 64)
15215    return SDValue();
15216
15217  const Function *F = DAG.getMachineFunction().getFunction();
15218  bool NoImplicitFloatOps = F->hasFnAttr(Attribute::NoImplicitFloat);
15219  bool F64IsLegal = !DAG.getTarget().Options.UseSoftFloat && !NoImplicitFloatOps
15220                     && Subtarget->hasSSE2();
15221  if ((VT.isVector() ||
15222       (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
15223      isa<LoadSDNode>(St->getValue()) &&
15224      !cast<LoadSDNode>(St->getValue())->isVolatile() &&
15225      St->getChain().hasOneUse() && !St->isVolatile()) {
15226    SDNode* LdVal = St->getValue().getNode();
15227    LoadSDNode *Ld = 0;
15228    int TokenFactorIndex = -1;
15229    SmallVector<SDValue, 8> Ops;
15230    SDNode* ChainVal = St->getChain().getNode();
15231    // Must be a store of a load.  We currently handle two cases:  the load
15232    // is a direct child, and it's under an intervening TokenFactor.  It is
15233    // possible to dig deeper under nested TokenFactors.
15234    if (ChainVal == LdVal)
15235      Ld = cast<LoadSDNode>(St->getChain());
15236    else if (St->getValue().hasOneUse() &&
15237             ChainVal->getOpcode() == ISD::TokenFactor) {
15238      for (unsigned i = 0, e = ChainVal->getNumOperands(); i != e; ++i) {
15239        if (ChainVal->getOperand(i).getNode() == LdVal) {
15240          TokenFactorIndex = i;
15241          Ld = cast<LoadSDNode>(St->getValue());
15242        } else
15243          Ops.push_back(ChainVal->getOperand(i));
15244      }
15245    }
15246
15247    if (!Ld || !ISD::isNormalLoad(Ld))
15248      return SDValue();
15249
15250    // If this is not the MMX case, i.e. we are just turning i64 load/store
15251    // into f64 load/store, avoid the transformation if there are multiple
15252    // uses of the loaded value.
15253    if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
15254      return SDValue();
15255
15256    DebugLoc LdDL = Ld->getDebugLoc();
15257    DebugLoc StDL = N->getDebugLoc();
15258    // If we are a 64-bit capable x86, lower to a single movq load/store pair.
15259    // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
15260    // pair instead.
15261    if (Subtarget->is64Bit() || F64IsLegal) {
15262      EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
15263      SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
15264                                  Ld->getPointerInfo(), Ld->isVolatile(),
15265                                  Ld->isNonTemporal(), Ld->isInvariant(),
15266                                  Ld->getAlignment());
15267      SDValue NewChain = NewLd.getValue(1);
15268      if (TokenFactorIndex != -1) {
15269        Ops.push_back(NewChain);
15270        NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
15271                               Ops.size());
15272      }
15273      return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
15274                          St->getPointerInfo(),
15275                          St->isVolatile(), St->isNonTemporal(),
15276                          St->getAlignment());
15277    }
15278
15279    // Otherwise, lower to two pairs of 32-bit loads / stores.
15280    SDValue LoAddr = Ld->getBasePtr();
15281    SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
15282                                 DAG.getConstant(4, MVT::i32));
15283
15284    SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
15285                               Ld->getPointerInfo(),
15286                               Ld->isVolatile(), Ld->isNonTemporal(),
15287                               Ld->isInvariant(), Ld->getAlignment());
15288    SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
15289                               Ld->getPointerInfo().getWithOffset(4),
15290                               Ld->isVolatile(), Ld->isNonTemporal(),
15291                               Ld->isInvariant(),
15292                               MinAlign(Ld->getAlignment(), 4));
15293
15294    SDValue NewChain = LoLd.getValue(1);
15295    if (TokenFactorIndex != -1) {
15296      Ops.push_back(LoLd);
15297      Ops.push_back(HiLd);
15298      NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
15299                             Ops.size());
15300    }
15301
15302    LoAddr = St->getBasePtr();
15303    HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
15304                         DAG.getConstant(4, MVT::i32));
15305
15306    SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
15307                                St->getPointerInfo(),
15308                                St->isVolatile(), St->isNonTemporal(),
15309                                St->getAlignment());
15310    SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
15311                                St->getPointerInfo().getWithOffset(4),
15312                                St->isVolatile(),
15313                                St->isNonTemporal(),
15314                                MinAlign(St->getAlignment(), 4));
15315    return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
15316  }
15317  return SDValue();
15318}
15319
15320/// isHorizontalBinOp - Return 'true' if this vector operation is "horizontal"
15321/// and return the operands for the horizontal operation in LHS and RHS.  A
15322/// horizontal operation performs the binary operation on successive elements
15323/// of its first operand, then on successive elements of its second operand,
15324/// returning the resulting values in a vector.  For example, if
15325///   A = < float a0, float a1, float a2, float a3 >
15326/// and
15327///   B = < float b0, float b1, float b2, float b3 >
15328/// then the result of doing a horizontal operation on A and B is
15329///   A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
15330/// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
15331/// A horizontal-op B, for some already available A and B, and if so then LHS is
15332/// set to A, RHS to B, and the routine returns 'true'.
15333/// Note that the binary operation should have the property that if one of the
15334/// operands is UNDEF then the result is UNDEF.
15335static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool IsCommutative) {
15336  // Look for the following pattern: if
15337  //   A = < float a0, float a1, float a2, float a3 >
15338  //   B = < float b0, float b1, float b2, float b3 >
15339  // and
15340  //   LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
15341  //   RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
15342  // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
15343  // which is A horizontal-op B.
15344
15345  // At least one of the operands should be a vector shuffle.
15346  if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
15347      RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
15348    return false;
15349
15350  EVT VT = LHS.getValueType();
15351
15352  assert((VT.is128BitVector() || VT.is256BitVector()) &&
15353         "Unsupported vector type for horizontal add/sub");
15354
15355  // Handle 128 and 256-bit vector lengths. AVX defines horizontal add/sub to
15356  // operate independently on 128-bit lanes.
15357  unsigned NumElts = VT.getVectorNumElements();
15358  unsigned NumLanes = VT.getSizeInBits()/128;
15359  unsigned NumLaneElts = NumElts / NumLanes;
15360  assert((NumLaneElts % 2 == 0) &&
15361         "Vector type should have an even number of elements in each lane");
15362  unsigned HalfLaneElts = NumLaneElts/2;
15363
15364  // View LHS in the form
15365  //   LHS = VECTOR_SHUFFLE A, B, LMask
15366  // If LHS is not a shuffle then pretend it is the shuffle
15367  //   LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
15368  // NOTE: in what follows a default initialized SDValue represents an UNDEF of
15369  // type VT.
15370  SDValue A, B;
15371  SmallVector<int, 16> LMask(NumElts);
15372  if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
15373    if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
15374      A = LHS.getOperand(0);
15375    if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
15376      B = LHS.getOperand(1);
15377    ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(LHS.getNode())->getMask();
15378    std::copy(Mask.begin(), Mask.end(), LMask.begin());
15379  } else {
15380    if (LHS.getOpcode() != ISD::UNDEF)
15381      A = LHS;
15382    for (unsigned i = 0; i != NumElts; ++i)
15383      LMask[i] = i;
15384  }
15385
15386  // Likewise, view RHS in the form
15387  //   RHS = VECTOR_SHUFFLE C, D, RMask
15388  SDValue C, D;
15389  SmallVector<int, 16> RMask(NumElts);
15390  if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
15391    if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
15392      C = RHS.getOperand(0);
15393    if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
15394      D = RHS.getOperand(1);
15395    ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(RHS.getNode())->getMask();
15396    std::copy(Mask.begin(), Mask.end(), RMask.begin());
15397  } else {
15398    if (RHS.getOpcode() != ISD::UNDEF)
15399      C = RHS;
15400    for (unsigned i = 0; i != NumElts; ++i)
15401      RMask[i] = i;
15402  }
15403
15404  // Check that the shuffles are both shuffling the same vectors.
15405  if (!(A == C && B == D) && !(A == D && B == C))
15406    return false;
15407
15408  // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
15409  if (!A.getNode() && !B.getNode())
15410    return false;
15411
15412  // If A and B occur in reverse order in RHS, then "swap" them (which means
15413  // rewriting the mask).
15414  if (A != C)
15415    CommuteVectorShuffleMask(RMask, NumElts);
15416
15417  // At this point LHS and RHS are equivalent to
15418  //   LHS = VECTOR_SHUFFLE A, B, LMask
15419  //   RHS = VECTOR_SHUFFLE A, B, RMask
15420  // Check that the masks correspond to performing a horizontal operation.
15421  for (unsigned i = 0; i != NumElts; ++i) {
15422    int LIdx = LMask[i], RIdx = RMask[i];
15423
15424    // Ignore any UNDEF components.
15425    if (LIdx < 0 || RIdx < 0 ||
15426        (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) ||
15427        (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts)))
15428      continue;
15429
15430    // Check that successive elements are being operated on.  If not, this is
15431    // not a horizontal operation.
15432    unsigned Src = (i/HalfLaneElts) % 2; // each lane is split between srcs
15433    unsigned LaneStart = (i/NumLaneElts) * NumLaneElts;
15434    int Index = 2*(i%HalfLaneElts) + NumElts*Src + LaneStart;
15435    if (!(LIdx == Index && RIdx == Index + 1) &&
15436        !(IsCommutative && LIdx == Index + 1 && RIdx == Index))
15437      return false;
15438  }
15439
15440  LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
15441  RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
15442  return true;
15443}
15444
15445/// PerformFADDCombine - Do target-specific dag combines on floating point adds.
15446static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
15447                                  const X86Subtarget *Subtarget) {
15448  EVT VT = N->getValueType(0);
15449  SDValue LHS = N->getOperand(0);
15450  SDValue RHS = N->getOperand(1);
15451
15452  // Try to synthesize horizontal adds from adds of shuffles.
15453  if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
15454       (Subtarget->hasAVX() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
15455      isHorizontalBinOp(LHS, RHS, true))
15456    return DAG.getNode(X86ISD::FHADD, N->getDebugLoc(), VT, LHS, RHS);
15457  return SDValue();
15458}
15459
15460/// PerformFSUBCombine - Do target-specific dag combines on floating point subs.
15461static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
15462                                  const X86Subtarget *Subtarget) {
15463  EVT VT = N->getValueType(0);
15464  SDValue LHS = N->getOperand(0);
15465  SDValue RHS = N->getOperand(1);
15466
15467  // Try to synthesize horizontal subs from subs of shuffles.
15468  if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
15469       (Subtarget->hasAVX() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
15470      isHorizontalBinOp(LHS, RHS, false))
15471    return DAG.getNode(X86ISD::FHSUB, N->getDebugLoc(), VT, LHS, RHS);
15472  return SDValue();
15473}
15474
15475/// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
15476/// X86ISD::FXOR nodes.
15477static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
15478  assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
15479  // F[X]OR(0.0, x) -> x
15480  // F[X]OR(x, 0.0) -> x
15481  if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
15482    if (C->getValueAPF().isPosZero())
15483      return N->getOperand(1);
15484  if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
15485    if (C->getValueAPF().isPosZero())
15486      return N->getOperand(0);
15487  return SDValue();
15488}
15489
15490/// PerformFMinFMaxCombine - Do target-specific dag combines on X86ISD::FMIN and
15491/// X86ISD::FMAX nodes.
15492static SDValue PerformFMinFMaxCombine(SDNode *N, SelectionDAG &DAG) {
15493  assert(N->getOpcode() == X86ISD::FMIN || N->getOpcode() == X86ISD::FMAX);
15494
15495  // Only perform optimizations if UnsafeMath is used.
15496  if (!DAG.getTarget().Options.UnsafeFPMath)
15497    return SDValue();
15498
15499  // If we run in unsafe-math mode, then convert the FMAX and FMIN nodes
15500  // into FMINC and MMAXC, which are Commutative operations.
15501  unsigned NewOp = 0;
15502  switch (N->getOpcode()) {
15503    default: llvm_unreachable("unknown opcode");
15504    case X86ISD::FMIN:  NewOp = X86ISD::FMINC; break;
15505    case X86ISD::FMAX:  NewOp = X86ISD::FMAXC; break;
15506  }
15507
15508  return DAG.getNode(NewOp, N->getDebugLoc(), N->getValueType(0),
15509                     N->getOperand(0), N->getOperand(1));
15510}
15511
15512
15513/// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
15514static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
15515  // FAND(0.0, x) -> 0.0
15516  // FAND(x, 0.0) -> 0.0
15517  if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
15518    if (C->getValueAPF().isPosZero())
15519      return N->getOperand(0);
15520  if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
15521    if (C->getValueAPF().isPosZero())
15522      return N->getOperand(1);
15523  return SDValue();
15524}
15525
15526static SDValue PerformBTCombine(SDNode *N,
15527                                SelectionDAG &DAG,
15528                                TargetLowering::DAGCombinerInfo &DCI) {
15529  // BT ignores high bits in the bit index operand.
15530  SDValue Op1 = N->getOperand(1);
15531  if (Op1.hasOneUse()) {
15532    unsigned BitWidth = Op1.getValueSizeInBits();
15533    APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
15534    APInt KnownZero, KnownOne;
15535    TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
15536                                          !DCI.isBeforeLegalizeOps());
15537    const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15538    if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
15539        TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
15540      DCI.CommitTargetLoweringOpt(TLO);
15541  }
15542  return SDValue();
15543}
15544
15545static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
15546  SDValue Op = N->getOperand(0);
15547  if (Op.getOpcode() == ISD::BITCAST)
15548    Op = Op.getOperand(0);
15549  EVT VT = N->getValueType(0), OpVT = Op.getValueType();
15550  if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
15551      VT.getVectorElementType().getSizeInBits() ==
15552      OpVT.getVectorElementType().getSizeInBits()) {
15553    return DAG.getNode(ISD::BITCAST, N->getDebugLoc(), VT, Op);
15554  }
15555  return SDValue();
15556}
15557
15558static SDValue PerformSExtCombine(SDNode *N, SelectionDAG &DAG,
15559                                  TargetLowering::DAGCombinerInfo &DCI,
15560                                  const X86Subtarget *Subtarget) {
15561  if (!DCI.isBeforeLegalizeOps())
15562    return SDValue();
15563
15564  if (!Subtarget->hasAVX())
15565    return SDValue();
15566
15567  EVT VT = N->getValueType(0);
15568  SDValue Op = N->getOperand(0);
15569  EVT OpVT = Op.getValueType();
15570  DebugLoc dl = N->getDebugLoc();
15571
15572  if ((VT == MVT::v4i64 && OpVT == MVT::v4i32) ||
15573      (VT == MVT::v8i32 && OpVT == MVT::v8i16)) {
15574
15575    if (Subtarget->hasAVX2())
15576      return DAG.getNode(X86ISD::VSEXT_MOVL, dl, VT, Op);
15577
15578    // Optimize vectors in AVX mode
15579    // Sign extend  v8i16 to v8i32 and
15580    //              v4i32 to v4i64
15581    //
15582    // Divide input vector into two parts
15583    // for v4i32 the shuffle mask will be { 0, 1, -1, -1} {2, 3, -1, -1}
15584    // use vpmovsx instruction to extend v4i32 -> v2i64; v8i16 -> v4i32
15585    // concat the vectors to original VT
15586
15587    unsigned NumElems = OpVT.getVectorNumElements();
15588    SDValue Undef = DAG.getUNDEF(OpVT);
15589
15590    SmallVector<int,8> ShufMask1(NumElems, -1);
15591    for (unsigned i = 0; i != NumElems/2; ++i)
15592      ShufMask1[i] = i;
15593
15594    SDValue OpLo = DAG.getVectorShuffle(OpVT, dl, Op, Undef, &ShufMask1[0]);
15595
15596    SmallVector<int,8> ShufMask2(NumElems, -1);
15597    for (unsigned i = 0; i != NumElems/2; ++i)
15598      ShufMask2[i] = i + NumElems/2;
15599
15600    SDValue OpHi = DAG.getVectorShuffle(OpVT, dl, Op, Undef, &ShufMask2[0]);
15601
15602    EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), VT.getScalarType(),
15603                                  VT.getVectorNumElements()/2);
15604
15605    OpLo = DAG.getNode(X86ISD::VSEXT_MOVL, dl, HalfVT, OpLo);
15606    OpHi = DAG.getNode(X86ISD::VSEXT_MOVL, dl, HalfVT, OpHi);
15607
15608    return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
15609  }
15610  return SDValue();
15611}
15612
15613static SDValue PerformFMACombine(SDNode *N, SelectionDAG &DAG,
15614                                 const X86Subtarget* Subtarget) {
15615  DebugLoc dl = N->getDebugLoc();
15616  EVT VT = N->getValueType(0);
15617
15618  // Let legalize expand this if it isn't a legal type yet.
15619  if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
15620    return SDValue();
15621
15622  EVT ScalarVT = VT.getScalarType();
15623  if ((ScalarVT != MVT::f32 && ScalarVT != MVT::f64) ||
15624      (!Subtarget->hasFMA() && !Subtarget->hasFMA4()))
15625    return SDValue();
15626
15627  SDValue A = N->getOperand(0);
15628  SDValue B = N->getOperand(1);
15629  SDValue C = N->getOperand(2);
15630
15631  bool NegA = (A.getOpcode() == ISD::FNEG);
15632  bool NegB = (B.getOpcode() == ISD::FNEG);
15633  bool NegC = (C.getOpcode() == ISD::FNEG);
15634
15635  // Negative multiplication when NegA xor NegB
15636  bool NegMul = (NegA != NegB);
15637  if (NegA)
15638    A = A.getOperand(0);
15639  if (NegB)
15640    B = B.getOperand(0);
15641  if (NegC)
15642    C = C.getOperand(0);
15643
15644  unsigned Opcode;
15645  if (!NegMul)
15646    Opcode = (!NegC) ? X86ISD::FMADD : X86ISD::FMSUB;
15647  else
15648    Opcode = (!NegC) ? X86ISD::FNMADD : X86ISD::FNMSUB;
15649
15650  return DAG.getNode(Opcode, dl, VT, A, B, C);
15651}
15652
15653static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG,
15654                                  TargetLowering::DAGCombinerInfo &DCI,
15655                                  const X86Subtarget *Subtarget) {
15656  // (i32 zext (and (i8  x86isd::setcc_carry), 1)) ->
15657  //           (and (i32 x86isd::setcc_carry), 1)
15658  // This eliminates the zext. This transformation is necessary because
15659  // ISD::SETCC is always legalized to i8.
15660  DebugLoc dl = N->getDebugLoc();
15661  SDValue N0 = N->getOperand(0);
15662  EVT VT = N->getValueType(0);
15663  EVT OpVT = N0.getValueType();
15664
15665  if (N0.getOpcode() == ISD::AND &&
15666      N0.hasOneUse() &&
15667      N0.getOperand(0).hasOneUse()) {
15668    SDValue N00 = N0.getOperand(0);
15669    if (N00.getOpcode() != X86ISD::SETCC_CARRY)
15670      return SDValue();
15671    ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
15672    if (!C || C->getZExtValue() != 1)
15673      return SDValue();
15674    return DAG.getNode(ISD::AND, dl, VT,
15675                       DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
15676                                   N00.getOperand(0), N00.getOperand(1)),
15677                       DAG.getConstant(1, VT));
15678  }
15679
15680  // Optimize vectors in AVX mode:
15681  //
15682  //   v8i16 -> v8i32
15683  //   Use vpunpcklwd for 4 lower elements  v8i16 -> v4i32.
15684  //   Use vpunpckhwd for 4 upper elements  v8i16 -> v4i32.
15685  //   Concat upper and lower parts.
15686  //
15687  //   v4i32 -> v4i64
15688  //   Use vpunpckldq for 4 lower elements  v4i32 -> v2i64.
15689  //   Use vpunpckhdq for 4 upper elements  v4i32 -> v2i64.
15690  //   Concat upper and lower parts.
15691  //
15692  if (!DCI.isBeforeLegalizeOps())
15693    return SDValue();
15694
15695  if (!Subtarget->hasAVX())
15696    return SDValue();
15697
15698  if (((VT == MVT::v8i32) && (OpVT == MVT::v8i16)) ||
15699      ((VT == MVT::v4i64) && (OpVT == MVT::v4i32)))  {
15700
15701    if (Subtarget->hasAVX2())
15702      return DAG.getNode(X86ISD::VZEXT_MOVL, dl, VT, N0);
15703
15704    SDValue ZeroVec = getZeroVector(OpVT, Subtarget, DAG, dl);
15705    SDValue OpLo = getUnpackl(DAG, dl, OpVT, N0, ZeroVec);
15706    SDValue OpHi = getUnpackh(DAG, dl, OpVT, N0, ZeroVec);
15707
15708    EVT HVT = EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(),
15709                               VT.getVectorNumElements()/2);
15710
15711    OpLo = DAG.getNode(ISD::BITCAST, dl, HVT, OpLo);
15712    OpHi = DAG.getNode(ISD::BITCAST, dl, HVT, OpHi);
15713
15714    return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
15715  }
15716
15717  return SDValue();
15718}
15719
15720// Optimize x == -y --> x+y == 0
15721//          x != -y --> x+y != 0
15722static SDValue PerformISDSETCCCombine(SDNode *N, SelectionDAG &DAG) {
15723  ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
15724  SDValue LHS = N->getOperand(0);
15725  SDValue RHS = N->getOperand(1);
15726
15727  if ((CC == ISD::SETNE || CC == ISD::SETEQ) && LHS.getOpcode() == ISD::SUB)
15728    if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(LHS.getOperand(0)))
15729      if (C->getAPIntValue() == 0 && LHS.hasOneUse()) {
15730        SDValue addV = DAG.getNode(ISD::ADD, N->getDebugLoc(),
15731                                   LHS.getValueType(), RHS, LHS.getOperand(1));
15732        return DAG.getSetCC(N->getDebugLoc(), N->getValueType(0),
15733                            addV, DAG.getConstant(0, addV.getValueType()), CC);
15734      }
15735  if ((CC == ISD::SETNE || CC == ISD::SETEQ) && RHS.getOpcode() == ISD::SUB)
15736    if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS.getOperand(0)))
15737      if (C->getAPIntValue() == 0 && RHS.hasOneUse()) {
15738        SDValue addV = DAG.getNode(ISD::ADD, N->getDebugLoc(),
15739                                   RHS.getValueType(), LHS, RHS.getOperand(1));
15740        return DAG.getSetCC(N->getDebugLoc(), N->getValueType(0),
15741                            addV, DAG.getConstant(0, addV.getValueType()), CC);
15742      }
15743  return SDValue();
15744}
15745
15746// Optimize  RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
15747static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG,
15748                                   TargetLowering::DAGCombinerInfo &DCI,
15749                                   const X86Subtarget *Subtarget) {
15750  DebugLoc DL = N->getDebugLoc();
15751  X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(0));
15752  SDValue EFLAGS = N->getOperand(1);
15753
15754  // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
15755  // a zext and produces an all-ones bit which is more useful than 0/1 in some
15756  // cases.
15757  if (CC == X86::COND_B)
15758    return DAG.getNode(ISD::AND, DL, MVT::i8,
15759                       DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
15760                                   DAG.getConstant(CC, MVT::i8), EFLAGS),
15761                       DAG.getConstant(1, MVT::i8));
15762
15763  SDValue Flags;
15764
15765  Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
15766  if (Flags.getNode()) {
15767    SDValue Cond = DAG.getConstant(CC, MVT::i8);
15768    return DAG.getNode(X86ISD::SETCC, DL, N->getVTList(), Cond, Flags);
15769  }
15770
15771  Flags = checkFlaggedOrCombine(EFLAGS, CC, DAG, Subtarget);
15772  if (Flags.getNode()) {
15773    SDValue Cond = DAG.getConstant(CC, MVT::i8);
15774    return DAG.getNode(X86ISD::SETCC, DL, N->getVTList(), Cond, Flags);
15775  }
15776
15777  return SDValue();
15778}
15779
15780// Optimize branch condition evaluation.
15781//
15782static SDValue PerformBrCondCombine(SDNode *N, SelectionDAG &DAG,
15783                                    TargetLowering::DAGCombinerInfo &DCI,
15784                                    const X86Subtarget *Subtarget) {
15785  DebugLoc DL = N->getDebugLoc();
15786  SDValue Chain = N->getOperand(0);
15787  SDValue Dest = N->getOperand(1);
15788  SDValue EFLAGS = N->getOperand(3);
15789  X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(2));
15790
15791  SDValue Flags;
15792
15793  Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
15794  if (Flags.getNode()) {
15795    SDValue Cond = DAG.getConstant(CC, MVT::i8);
15796    return DAG.getNode(X86ISD::BRCOND, DL, N->getVTList(), Chain, Dest, Cond,
15797                       Flags);
15798  }
15799
15800  Flags = checkFlaggedOrCombine(EFLAGS, CC, DAG, Subtarget);
15801  if (Flags.getNode()) {
15802    SDValue Cond = DAG.getConstant(CC, MVT::i8);
15803    return DAG.getNode(X86ISD::BRCOND, DL, N->getVTList(), Chain, Dest, Cond,
15804                       Flags);
15805  }
15806
15807  return SDValue();
15808}
15809
15810static SDValue PerformUINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG) {
15811  SDValue Op0 = N->getOperand(0);
15812  EVT InVT = Op0->getValueType(0);
15813
15814  // UINT_TO_FP(v4i8) -> SINT_TO_FP(ZEXT(v4i8 to v4i32))
15815  if (InVT == MVT::v8i8 || InVT == MVT::v4i8) {
15816    DebugLoc dl = N->getDebugLoc();
15817    MVT DstVT = InVT == MVT::v4i8 ? MVT::v4i32 : MVT::v8i32;
15818    SDValue P = DAG.getNode(ISD::ZERO_EXTEND, dl, DstVT, Op0);
15819    // Notice that we use SINT_TO_FP because we know that the high bits
15820    // are zero and SINT_TO_FP is better supported by the hardware.
15821    return DAG.getNode(ISD::SINT_TO_FP, dl, N->getValueType(0), P);
15822  }
15823
15824  return SDValue();
15825}
15826
15827static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
15828                                        const X86TargetLowering *XTLI) {
15829  SDValue Op0 = N->getOperand(0);
15830  EVT InVT = Op0->getValueType(0);
15831
15832  // SINT_TO_FP(v4i8) -> SINT_TO_FP(SEXT(v4i8 to v4i32))
15833  if (InVT == MVT::v8i8 || InVT == MVT::v4i8) {
15834    DebugLoc dl = N->getDebugLoc();
15835    MVT DstVT = InVT == MVT::v4i8 ? MVT::v4i32 : MVT::v8i32;
15836    SDValue P = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Op0);
15837    return DAG.getNode(ISD::SINT_TO_FP, dl, N->getValueType(0), P);
15838  }
15839
15840  // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
15841  // a 32-bit target where SSE doesn't support i64->FP operations.
15842  if (Op0.getOpcode() == ISD::LOAD) {
15843    LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
15844    EVT VT = Ld->getValueType(0);
15845    if (!Ld->isVolatile() && !N->getValueType(0).isVector() &&
15846        ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
15847        !XTLI->getSubtarget()->is64Bit() &&
15848        !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
15849      SDValue FILDChain = XTLI->BuildFILD(SDValue(N, 0), Ld->getValueType(0),
15850                                          Ld->getChain(), Op0, DAG);
15851      DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
15852      return FILDChain;
15853    }
15854  }
15855  return SDValue();
15856}
15857
15858static SDValue PerformFP_TO_SINTCombine(SDNode *N, SelectionDAG &DAG) {
15859  EVT VT = N->getValueType(0);
15860
15861  // v4i8 = FP_TO_SINT() -> v4i8 = TRUNCATE (V4i32 = FP_TO_SINT()
15862  if (VT == MVT::v8i8 || VT == MVT::v4i8) {
15863    DebugLoc dl = N->getDebugLoc();
15864    MVT DstVT = VT == MVT::v4i8 ? MVT::v4i32 : MVT::v8i32;
15865    SDValue I = DAG.getNode(ISD::FP_TO_SINT, dl, DstVT, N->getOperand(0));
15866    return DAG.getNode(ISD::TRUNCATE, dl, VT, I);
15867  }
15868
15869  return SDValue();
15870}
15871
15872// Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
15873static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
15874                                 X86TargetLowering::DAGCombinerInfo &DCI) {
15875  // If the LHS and RHS of the ADC node are zero, then it can't overflow and
15876  // the result is either zero or one (depending on the input carry bit).
15877  // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
15878  if (X86::isZeroNode(N->getOperand(0)) &&
15879      X86::isZeroNode(N->getOperand(1)) &&
15880      // We don't have a good way to replace an EFLAGS use, so only do this when
15881      // dead right now.
15882      SDValue(N, 1).use_empty()) {
15883    DebugLoc DL = N->getDebugLoc();
15884    EVT VT = N->getValueType(0);
15885    SDValue CarryOut = DAG.getConstant(0, N->getValueType(1));
15886    SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
15887                               DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
15888                                           DAG.getConstant(X86::COND_B,MVT::i8),
15889                                           N->getOperand(2)),
15890                               DAG.getConstant(1, VT));
15891    return DCI.CombineTo(N, Res1, CarryOut);
15892  }
15893
15894  return SDValue();
15895}
15896
15897// fold (add Y, (sete  X, 0)) -> adc  0, Y
15898//      (add Y, (setne X, 0)) -> sbb -1, Y
15899//      (sub (sete  X, 0), Y) -> sbb  0, Y
15900//      (sub (setne X, 0), Y) -> adc -1, Y
15901static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
15902  DebugLoc DL = N->getDebugLoc();
15903
15904  // Look through ZExts.
15905  SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
15906  if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
15907    return SDValue();
15908
15909  SDValue SetCC = Ext.getOperand(0);
15910  if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
15911    return SDValue();
15912
15913  X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
15914  if (CC != X86::COND_E && CC != X86::COND_NE)
15915    return SDValue();
15916
15917  SDValue Cmp = SetCC.getOperand(1);
15918  if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
15919      !X86::isZeroNode(Cmp.getOperand(1)) ||
15920      !Cmp.getOperand(0).getValueType().isInteger())
15921    return SDValue();
15922
15923  SDValue CmpOp0 = Cmp.getOperand(0);
15924  SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
15925                               DAG.getConstant(1, CmpOp0.getValueType()));
15926
15927  SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
15928  if (CC == X86::COND_NE)
15929    return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
15930                       DL, OtherVal.getValueType(), OtherVal,
15931                       DAG.getConstant(-1ULL, OtherVal.getValueType()), NewCmp);
15932  return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
15933                     DL, OtherVal.getValueType(), OtherVal,
15934                     DAG.getConstant(0, OtherVal.getValueType()), NewCmp);
15935}
15936
15937/// PerformADDCombine - Do target-specific dag combines on integer adds.
15938static SDValue PerformAddCombine(SDNode *N, SelectionDAG &DAG,
15939                                 const X86Subtarget *Subtarget) {
15940  EVT VT = N->getValueType(0);
15941  SDValue Op0 = N->getOperand(0);
15942  SDValue Op1 = N->getOperand(1);
15943
15944  // Try to synthesize horizontal adds from adds of shuffles.
15945  if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
15946       (Subtarget->hasAVX2() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
15947      isHorizontalBinOp(Op0, Op1, true))
15948    return DAG.getNode(X86ISD::HADD, N->getDebugLoc(), VT, Op0, Op1);
15949
15950  return OptimizeConditionalInDecrement(N, DAG);
15951}
15952
15953static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG,
15954                                 const X86Subtarget *Subtarget) {
15955  SDValue Op0 = N->getOperand(0);
15956  SDValue Op1 = N->getOperand(1);
15957
15958  // X86 can't encode an immediate LHS of a sub. See if we can push the
15959  // negation into a preceding instruction.
15960  if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
15961    // If the RHS of the sub is a XOR with one use and a constant, invert the
15962    // immediate. Then add one to the LHS of the sub so we can turn
15963    // X-Y -> X+~Y+1, saving one register.
15964    if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
15965        isa<ConstantSDNode>(Op1.getOperand(1))) {
15966      APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
15967      EVT VT = Op0.getValueType();
15968      SDValue NewXor = DAG.getNode(ISD::XOR, Op1.getDebugLoc(), VT,
15969                                   Op1.getOperand(0),
15970                                   DAG.getConstant(~XorC, VT));
15971      return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, NewXor,
15972                         DAG.getConstant(C->getAPIntValue()+1, VT));
15973    }
15974  }
15975
15976  // Try to synthesize horizontal adds from adds of shuffles.
15977  EVT VT = N->getValueType(0);
15978  if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
15979       (Subtarget->hasAVX2() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
15980      isHorizontalBinOp(Op0, Op1, true))
15981    return DAG.getNode(X86ISD::HSUB, N->getDebugLoc(), VT, Op0, Op1);
15982
15983  return OptimizeConditionalInDecrement(N, DAG);
15984}
15985
15986SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
15987                                             DAGCombinerInfo &DCI) const {
15988  SelectionDAG &DAG = DCI.DAG;
15989  switch (N->getOpcode()) {
15990  default: break;
15991  case ISD::EXTRACT_VECTOR_ELT:
15992    return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, DCI);
15993  case ISD::VSELECT:
15994  case ISD::SELECT:         return PerformSELECTCombine(N, DAG, DCI, Subtarget);
15995  case X86ISD::CMOV:        return PerformCMOVCombine(N, DAG, DCI, Subtarget);
15996  case ISD::ADD:            return PerformAddCombine(N, DAG, Subtarget);
15997  case ISD::SUB:            return PerformSubCombine(N, DAG, Subtarget);
15998  case X86ISD::ADC:         return PerformADCCombine(N, DAG, DCI);
15999  case ISD::MUL:            return PerformMulCombine(N, DAG, DCI);
16000  case ISD::SHL:
16001  case ISD::SRA:
16002  case ISD::SRL:            return PerformShiftCombine(N, DAG, DCI, Subtarget);
16003  case ISD::AND:            return PerformAndCombine(N, DAG, DCI, Subtarget);
16004  case ISD::OR:             return PerformOrCombine(N, DAG, DCI, Subtarget);
16005  case ISD::XOR:            return PerformXorCombine(N, DAG, DCI, Subtarget);
16006  case ISD::LOAD:           return PerformLOADCombine(N, DAG, DCI, Subtarget);
16007  case ISD::STORE:          return PerformSTORECombine(N, DAG, Subtarget);
16008  case ISD::UINT_TO_FP:     return PerformUINT_TO_FPCombine(N, DAG);
16009  case ISD::SINT_TO_FP:     return PerformSINT_TO_FPCombine(N, DAG, this);
16010  case ISD::FP_TO_SINT:     return PerformFP_TO_SINTCombine(N, DAG);
16011  case ISD::FADD:           return PerformFADDCombine(N, DAG, Subtarget);
16012  case ISD::FSUB:           return PerformFSUBCombine(N, DAG, Subtarget);
16013  case X86ISD::FXOR:
16014  case X86ISD::FOR:         return PerformFORCombine(N, DAG);
16015  case X86ISD::FMIN:
16016  case X86ISD::FMAX:        return PerformFMinFMaxCombine(N, DAG);
16017  case X86ISD::FAND:        return PerformFANDCombine(N, DAG);
16018  case X86ISD::BT:          return PerformBTCombine(N, DAG, DCI);
16019  case X86ISD::VZEXT_MOVL:  return PerformVZEXT_MOVLCombine(N, DAG);
16020  case ISD::ANY_EXTEND:
16021  case ISD::ZERO_EXTEND:    return PerformZExtCombine(N, DAG, DCI, Subtarget);
16022  case ISD::SIGN_EXTEND:    return PerformSExtCombine(N, DAG, DCI, Subtarget);
16023  case ISD::TRUNCATE:       return PerformTruncateCombine(N, DAG, DCI);
16024  case ISD::SETCC:          return PerformISDSETCCCombine(N, DAG);
16025  case X86ISD::SETCC:       return PerformSETCCCombine(N, DAG, DCI, Subtarget);
16026  case X86ISD::BRCOND:      return PerformBrCondCombine(N, DAG, DCI, Subtarget);
16027  case X86ISD::SHUFP:       // Handle all target specific shuffles
16028  case X86ISD::PALIGN:
16029  case X86ISD::UNPCKH:
16030  case X86ISD::UNPCKL:
16031  case X86ISD::MOVHLPS:
16032  case X86ISD::MOVLHPS:
16033  case X86ISD::PSHUFD:
16034  case X86ISD::PSHUFHW:
16035  case X86ISD::PSHUFLW:
16036  case X86ISD::MOVSS:
16037  case X86ISD::MOVSD:
16038  case X86ISD::VPERMILP:
16039  case X86ISD::VPERM2X128:
16040  case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
16041  case ISD::FMA:            return PerformFMACombine(N, DAG, Subtarget);
16042  }
16043
16044  return SDValue();
16045}
16046
16047/// isTypeDesirableForOp - Return true if the target has native support for
16048/// the specified value type and it is 'desirable' to use the type for the
16049/// given node type. e.g. On x86 i16 is legal, but undesirable since i16
16050/// instruction encodings are longer and some i16 instructions are slow.
16051bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
16052  if (!isTypeLegal(VT))
16053    return false;
16054  if (VT != MVT::i16)
16055    return true;
16056
16057  switch (Opc) {
16058  default:
16059    return true;
16060  case ISD::LOAD:
16061  case ISD::SIGN_EXTEND:
16062  case ISD::ZERO_EXTEND:
16063  case ISD::ANY_EXTEND:
16064  case ISD::SHL:
16065  case ISD::SRL:
16066  case ISD::SUB:
16067  case ISD::ADD:
16068  case ISD::MUL:
16069  case ISD::AND:
16070  case ISD::OR:
16071  case ISD::XOR:
16072    return false;
16073  }
16074}
16075
16076/// IsDesirableToPromoteOp - This method query the target whether it is
16077/// beneficial for dag combiner to promote the specified node. If true, it
16078/// should return the desired promotion type by reference.
16079bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
16080  EVT VT = Op.getValueType();
16081  if (VT != MVT::i16)
16082    return false;
16083
16084  bool Promote = false;
16085  bool Commute = false;
16086  switch (Op.getOpcode()) {
16087  default: break;
16088  case ISD::LOAD: {
16089    LoadSDNode *LD = cast<LoadSDNode>(Op);
16090    // If the non-extending load has a single use and it's not live out, then it
16091    // might be folded.
16092    if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
16093                                                     Op.hasOneUse()*/) {
16094      for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
16095             UE = Op.getNode()->use_end(); UI != UE; ++UI) {
16096        // The only case where we'd want to promote LOAD (rather then it being
16097        // promoted as an operand is when it's only use is liveout.
16098        if (UI->getOpcode() != ISD::CopyToReg)
16099          return false;
16100      }
16101    }
16102    Promote = true;
16103    break;
16104  }
16105  case ISD::SIGN_EXTEND:
16106  case ISD::ZERO_EXTEND:
16107  case ISD::ANY_EXTEND:
16108    Promote = true;
16109    break;
16110  case ISD::SHL:
16111  case ISD::SRL: {
16112    SDValue N0 = Op.getOperand(0);
16113    // Look out for (store (shl (load), x)).
16114    if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
16115      return false;
16116    Promote = true;
16117    break;
16118  }
16119  case ISD::ADD:
16120  case ISD::MUL:
16121  case ISD::AND:
16122  case ISD::OR:
16123  case ISD::XOR:
16124    Commute = true;
16125    // fallthrough
16126  case ISD::SUB: {
16127    SDValue N0 = Op.getOperand(0);
16128    SDValue N1 = Op.getOperand(1);
16129    if (!Commute && MayFoldLoad(N1))
16130      return false;
16131    // Avoid disabling potential load folding opportunities.
16132    if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
16133      return false;
16134    if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
16135      return false;
16136    Promote = true;
16137  }
16138  }
16139
16140  PVT = MVT::i32;
16141  return Promote;
16142}
16143
16144//===----------------------------------------------------------------------===//
16145//                           X86 Inline Assembly Support
16146//===----------------------------------------------------------------------===//
16147
16148namespace {
16149  // Helper to match a string separated by whitespace.
16150  bool matchAsmImpl(StringRef s, ArrayRef<const StringRef *> args) {
16151    s = s.substr(s.find_first_not_of(" \t")); // Skip leading whitespace.
16152
16153    for (unsigned i = 0, e = args.size(); i != e; ++i) {
16154      StringRef piece(*args[i]);
16155      if (!s.startswith(piece)) // Check if the piece matches.
16156        return false;
16157
16158      s = s.substr(piece.size());
16159      StringRef::size_type pos = s.find_first_not_of(" \t");
16160      if (pos == 0) // We matched a prefix.
16161        return false;
16162
16163      s = s.substr(pos);
16164    }
16165
16166    return s.empty();
16167  }
16168  const VariadicFunction1<bool, StringRef, StringRef, matchAsmImpl> matchAsm={};
16169}
16170
16171bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
16172  InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
16173
16174  std::string AsmStr = IA->getAsmString();
16175
16176  IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
16177  if (!Ty || Ty->getBitWidth() % 16 != 0)
16178    return false;
16179
16180  // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
16181  SmallVector<StringRef, 4> AsmPieces;
16182  SplitString(AsmStr, AsmPieces, ";\n");
16183
16184  switch (AsmPieces.size()) {
16185  default: return false;
16186  case 1:
16187    // FIXME: this should verify that we are targeting a 486 or better.  If not,
16188    // we will turn this bswap into something that will be lowered to logical
16189    // ops instead of emitting the bswap asm.  For now, we don't support 486 or
16190    // lower so don't worry about this.
16191    // bswap $0
16192    if (matchAsm(AsmPieces[0], "bswap", "$0") ||
16193        matchAsm(AsmPieces[0], "bswapl", "$0") ||
16194        matchAsm(AsmPieces[0], "bswapq", "$0") ||
16195        matchAsm(AsmPieces[0], "bswap", "${0:q}") ||
16196        matchAsm(AsmPieces[0], "bswapl", "${0:q}") ||
16197        matchAsm(AsmPieces[0], "bswapq", "${0:q}")) {
16198      // No need to check constraints, nothing other than the equivalent of
16199      // "=r,0" would be valid here.
16200      return IntrinsicLowering::LowerToByteSwap(CI);
16201    }
16202
16203    // rorw $$8, ${0:w}  -->  llvm.bswap.i16
16204    if (CI->getType()->isIntegerTy(16) &&
16205        IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
16206        (matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") ||
16207         matchAsm(AsmPieces[0], "rolw", "$$8,", "${0:w}"))) {
16208      AsmPieces.clear();
16209      const std::string &ConstraintsStr = IA->getConstraintString();
16210      SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
16211      std::sort(AsmPieces.begin(), AsmPieces.end());
16212      if (AsmPieces.size() == 4 &&
16213          AsmPieces[0] == "~{cc}" &&
16214          AsmPieces[1] == "~{dirflag}" &&
16215          AsmPieces[2] == "~{flags}" &&
16216          AsmPieces[3] == "~{fpsr}")
16217      return IntrinsicLowering::LowerToByteSwap(CI);
16218    }
16219    break;
16220  case 3:
16221    if (CI->getType()->isIntegerTy(32) &&
16222        IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
16223        matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") &&
16224        matchAsm(AsmPieces[1], "rorl", "$$16,", "$0") &&
16225        matchAsm(AsmPieces[2], "rorw", "$$8,", "${0:w}")) {
16226      AsmPieces.clear();
16227      const std::string &ConstraintsStr = IA->getConstraintString();
16228      SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
16229      std::sort(AsmPieces.begin(), AsmPieces.end());
16230      if (AsmPieces.size() == 4 &&
16231          AsmPieces[0] == "~{cc}" &&
16232          AsmPieces[1] == "~{dirflag}" &&
16233          AsmPieces[2] == "~{flags}" &&
16234          AsmPieces[3] == "~{fpsr}")
16235        return IntrinsicLowering::LowerToByteSwap(CI);
16236    }
16237
16238    if (CI->getType()->isIntegerTy(64)) {
16239      InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
16240      if (Constraints.size() >= 2 &&
16241          Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
16242          Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
16243        // bswap %eax / bswap %edx / xchgl %eax, %edx  -> llvm.bswap.i64
16244        if (matchAsm(AsmPieces[0], "bswap", "%eax") &&
16245            matchAsm(AsmPieces[1], "bswap", "%edx") &&
16246            matchAsm(AsmPieces[2], "xchgl", "%eax,", "%edx"))
16247          return IntrinsicLowering::LowerToByteSwap(CI);
16248      }
16249    }
16250    break;
16251  }
16252  return false;
16253}
16254
16255
16256
16257/// getConstraintType - Given a constraint letter, return the type of
16258/// constraint it is for this target.
16259X86TargetLowering::ConstraintType
16260X86TargetLowering::getConstraintType(const std::string &Constraint) const {
16261  if (Constraint.size() == 1) {
16262    switch (Constraint[0]) {
16263    case 'R':
16264    case 'q':
16265    case 'Q':
16266    case 'f':
16267    case 't':
16268    case 'u':
16269    case 'y':
16270    case 'x':
16271    case 'Y':
16272    case 'l':
16273      return C_RegisterClass;
16274    case 'a':
16275    case 'b':
16276    case 'c':
16277    case 'd':
16278    case 'S':
16279    case 'D':
16280    case 'A':
16281      return C_Register;
16282    case 'I':
16283    case 'J':
16284    case 'K':
16285    case 'L':
16286    case 'M':
16287    case 'N':
16288    case 'G':
16289    case 'C':
16290    case 'e':
16291    case 'Z':
16292      return C_Other;
16293    default:
16294      break;
16295    }
16296  }
16297  return TargetLowering::getConstraintType(Constraint);
16298}
16299
16300/// Examine constraint type and operand type and determine a weight value.
16301/// This object must already have been set up with the operand type
16302/// and the current alternative constraint selected.
16303TargetLowering::ConstraintWeight
16304  X86TargetLowering::getSingleConstraintMatchWeight(
16305    AsmOperandInfo &info, const char *constraint) const {
16306  ConstraintWeight weight = CW_Invalid;
16307  Value *CallOperandVal = info.CallOperandVal;
16308    // If we don't have a value, we can't do a match,
16309    // but allow it at the lowest weight.
16310  if (CallOperandVal == NULL)
16311    return CW_Default;
16312  Type *type = CallOperandVal->getType();
16313  // Look at the constraint type.
16314  switch (*constraint) {
16315  default:
16316    weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
16317  case 'R':
16318  case 'q':
16319  case 'Q':
16320  case 'a':
16321  case 'b':
16322  case 'c':
16323  case 'd':
16324  case 'S':
16325  case 'D':
16326  case 'A':
16327    if (CallOperandVal->getType()->isIntegerTy())
16328      weight = CW_SpecificReg;
16329    break;
16330  case 'f':
16331  case 't':
16332  case 'u':
16333      if (type->isFloatingPointTy())
16334        weight = CW_SpecificReg;
16335      break;
16336  case 'y':
16337      if (type->isX86_MMXTy() && Subtarget->hasMMX())
16338        weight = CW_SpecificReg;
16339      break;
16340  case 'x':
16341  case 'Y':
16342    if (((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasSSE1()) ||
16343        ((type->getPrimitiveSizeInBits() == 256) && Subtarget->hasAVX()))
16344      weight = CW_Register;
16345    break;
16346  case 'I':
16347    if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
16348      if (C->getZExtValue() <= 31)
16349        weight = CW_Constant;
16350    }
16351    break;
16352  case 'J':
16353    if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
16354      if (C->getZExtValue() <= 63)
16355        weight = CW_Constant;
16356    }
16357    break;
16358  case 'K':
16359    if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
16360      if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
16361        weight = CW_Constant;
16362    }
16363    break;
16364  case 'L':
16365    if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
16366      if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
16367        weight = CW_Constant;
16368    }
16369    break;
16370  case 'M':
16371    if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
16372      if (C->getZExtValue() <= 3)
16373        weight = CW_Constant;
16374    }
16375    break;
16376  case 'N':
16377    if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
16378      if (C->getZExtValue() <= 0xff)
16379        weight = CW_Constant;
16380    }
16381    break;
16382  case 'G':
16383  case 'C':
16384    if (dyn_cast<ConstantFP>(CallOperandVal)) {
16385      weight = CW_Constant;
16386    }
16387    break;
16388  case 'e':
16389    if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
16390      if ((C->getSExtValue() >= -0x80000000LL) &&
16391          (C->getSExtValue() <= 0x7fffffffLL))
16392        weight = CW_Constant;
16393    }
16394    break;
16395  case 'Z':
16396    if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
16397      if (C->getZExtValue() <= 0xffffffff)
16398        weight = CW_Constant;
16399    }
16400    break;
16401  }
16402  return weight;
16403}
16404
16405/// LowerXConstraint - try to replace an X constraint, which matches anything,
16406/// with another that has more specific requirements based on the type of the
16407/// corresponding operand.
16408const char *X86TargetLowering::
16409LowerXConstraint(EVT ConstraintVT) const {
16410  // FP X constraints get lowered to SSE1/2 registers if available, otherwise
16411  // 'f' like normal targets.
16412  if (ConstraintVT.isFloatingPoint()) {
16413    if (Subtarget->hasSSE2())
16414      return "Y";
16415    if (Subtarget->hasSSE1())
16416      return "x";
16417  }
16418
16419  return TargetLowering::LowerXConstraint(ConstraintVT);
16420}
16421
16422/// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
16423/// vector.  If it is invalid, don't add anything to Ops.
16424void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
16425                                                     std::string &Constraint,
16426                                                     std::vector<SDValue>&Ops,
16427                                                     SelectionDAG &DAG) const {
16428  SDValue Result(0, 0);
16429
16430  // Only support length 1 constraints for now.
16431  if (Constraint.length() > 1) return;
16432
16433  char ConstraintLetter = Constraint[0];
16434  switch (ConstraintLetter) {
16435  default: break;
16436  case 'I':
16437    if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
16438      if (C->getZExtValue() <= 31) {
16439        Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
16440        break;
16441      }
16442    }
16443    return;
16444  case 'J':
16445    if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
16446      if (C->getZExtValue() <= 63) {
16447        Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
16448        break;
16449      }
16450    }
16451    return;
16452  case 'K':
16453    if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
16454      if ((int8_t)C->getSExtValue() == C->getSExtValue()) {
16455        Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
16456        break;
16457      }
16458    }
16459    return;
16460  case 'N':
16461    if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
16462      if (C->getZExtValue() <= 255) {
16463        Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
16464        break;
16465      }
16466    }
16467    return;
16468  case 'e': {
16469    // 32-bit signed value
16470    if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
16471      if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
16472                                           C->getSExtValue())) {
16473        // Widen to 64 bits here to get it sign extended.
16474        Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
16475        break;
16476      }
16477    // FIXME gcc accepts some relocatable values here too, but only in certain
16478    // memory models; it's complicated.
16479    }
16480    return;
16481  }
16482  case 'Z': {
16483    // 32-bit unsigned value
16484    if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
16485      if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
16486                                           C->getZExtValue())) {
16487        Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
16488        break;
16489      }
16490    }
16491    // FIXME gcc accepts some relocatable values here too, but only in certain
16492    // memory models; it's complicated.
16493    return;
16494  }
16495  case 'i': {
16496    // Literal immediates are always ok.
16497    if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
16498      // Widen to 64 bits here to get it sign extended.
16499      Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
16500      break;
16501    }
16502
16503    // In any sort of PIC mode addresses need to be computed at runtime by
16504    // adding in a register or some sort of table lookup.  These can't
16505    // be used as immediates.
16506    if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
16507      return;
16508
16509    // If we are in non-pic codegen mode, we allow the address of a global (with
16510    // an optional displacement) to be used with 'i'.
16511    GlobalAddressSDNode *GA = 0;
16512    int64_t Offset = 0;
16513
16514    // Match either (GA), (GA+C), (GA+C1+C2), etc.
16515    while (1) {
16516      if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
16517        Offset += GA->getOffset();
16518        break;
16519      } else if (Op.getOpcode() == ISD::ADD) {
16520        if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
16521          Offset += C->getZExtValue();
16522          Op = Op.getOperand(0);
16523          continue;
16524        }
16525      } else if (Op.getOpcode() == ISD::SUB) {
16526        if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
16527          Offset += -C->getZExtValue();
16528          Op = Op.getOperand(0);
16529          continue;
16530        }
16531      }
16532
16533      // Otherwise, this isn't something we can handle, reject it.
16534      return;
16535    }
16536
16537    const GlobalValue *GV = GA->getGlobal();
16538    // If we require an extra load to get this address, as in PIC mode, we
16539    // can't accept it.
16540    if (isGlobalStubReference(Subtarget->ClassifyGlobalReference(GV,
16541                                                        getTargetMachine())))
16542      return;
16543
16544    Result = DAG.getTargetGlobalAddress(GV, Op.getDebugLoc(),
16545                                        GA->getValueType(0), Offset);
16546    break;
16547  }
16548  }
16549
16550  if (Result.getNode()) {
16551    Ops.push_back(Result);
16552    return;
16553  }
16554  return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
16555}
16556
16557std::pair<unsigned, const TargetRegisterClass*>
16558X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
16559                                                EVT VT) const {
16560  // First, see if this is a constraint that directly corresponds to an LLVM
16561  // register class.
16562  if (Constraint.size() == 1) {
16563    // GCC Constraint Letters
16564    switch (Constraint[0]) {
16565    default: break;
16566      // TODO: Slight differences here in allocation order and leaving
16567      // RIP in the class. Do they matter any more here than they do
16568      // in the normal allocation?
16569    case 'q':   // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
16570      if (Subtarget->is64Bit()) {
16571        if (VT == MVT::i32 || VT == MVT::f32)
16572          return std::make_pair(0U, &X86::GR32RegClass);
16573        if (VT == MVT::i16)
16574          return std::make_pair(0U, &X86::GR16RegClass);
16575        if (VT == MVT::i8 || VT == MVT::i1)
16576          return std::make_pair(0U, &X86::GR8RegClass);
16577        if (VT == MVT::i64 || VT == MVT::f64)
16578          return std::make_pair(0U, &X86::GR64RegClass);
16579        break;
16580      }
16581      // 32-bit fallthrough
16582    case 'Q':   // Q_REGS
16583      if (VT == MVT::i32 || VT == MVT::f32)
16584        return std::make_pair(0U, &X86::GR32_ABCDRegClass);
16585      if (VT == MVT::i16)
16586        return std::make_pair(0U, &X86::GR16_ABCDRegClass);
16587      if (VT == MVT::i8 || VT == MVT::i1)
16588        return std::make_pair(0U, &X86::GR8_ABCD_LRegClass);
16589      if (VT == MVT::i64)
16590        return std::make_pair(0U, &X86::GR64_ABCDRegClass);
16591      break;
16592    case 'r':   // GENERAL_REGS
16593    case 'l':   // INDEX_REGS
16594      if (VT == MVT::i8 || VT == MVT::i1)
16595        return std::make_pair(0U, &X86::GR8RegClass);
16596      if (VT == MVT::i16)
16597        return std::make_pair(0U, &X86::GR16RegClass);
16598      if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
16599        return std::make_pair(0U, &X86::GR32RegClass);
16600      return std::make_pair(0U, &X86::GR64RegClass);
16601    case 'R':   // LEGACY_REGS
16602      if (VT == MVT::i8 || VT == MVT::i1)
16603        return std::make_pair(0U, &X86::GR8_NOREXRegClass);
16604      if (VT == MVT::i16)
16605        return std::make_pair(0U, &X86::GR16_NOREXRegClass);
16606      if (VT == MVT::i32 || !Subtarget->is64Bit())
16607        return std::make_pair(0U, &X86::GR32_NOREXRegClass);
16608      return std::make_pair(0U, &X86::GR64_NOREXRegClass);
16609    case 'f':  // FP Stack registers.
16610      // If SSE is enabled for this VT, use f80 to ensure the isel moves the
16611      // value to the correct fpstack register class.
16612      if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
16613        return std::make_pair(0U, &X86::RFP32RegClass);
16614      if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
16615        return std::make_pair(0U, &X86::RFP64RegClass);
16616      return std::make_pair(0U, &X86::RFP80RegClass);
16617    case 'y':   // MMX_REGS if MMX allowed.
16618      if (!Subtarget->hasMMX()) break;
16619      return std::make_pair(0U, &X86::VR64RegClass);
16620    case 'Y':   // SSE_REGS if SSE2 allowed
16621      if (!Subtarget->hasSSE2()) break;
16622      // FALL THROUGH.
16623    case 'x':   // SSE_REGS if SSE1 allowed or AVX_REGS if AVX allowed
16624      if (!Subtarget->hasSSE1()) break;
16625
16626      switch (VT.getSimpleVT().SimpleTy) {
16627      default: break;
16628      // Scalar SSE types.
16629      case MVT::f32:
16630      case MVT::i32:
16631        return std::make_pair(0U, &X86::FR32RegClass);
16632      case MVT::f64:
16633      case MVT::i64:
16634        return std::make_pair(0U, &X86::FR64RegClass);
16635      // Vector types.
16636      case MVT::v16i8:
16637      case MVT::v8i16:
16638      case MVT::v4i32:
16639      case MVT::v2i64:
16640      case MVT::v4f32:
16641      case MVT::v2f64:
16642        return std::make_pair(0U, &X86::VR128RegClass);
16643      // AVX types.
16644      case MVT::v32i8:
16645      case MVT::v16i16:
16646      case MVT::v8i32:
16647      case MVT::v4i64:
16648      case MVT::v8f32:
16649      case MVT::v4f64:
16650        return std::make_pair(0U, &X86::VR256RegClass);
16651      }
16652      break;
16653    }
16654  }
16655
16656  // Use the default implementation in TargetLowering to convert the register
16657  // constraint into a member of a register class.
16658  std::pair<unsigned, const TargetRegisterClass*> Res;
16659  Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
16660
16661  // Not found as a standard register?
16662  if (Res.second == 0) {
16663    // Map st(0) -> st(7) -> ST0
16664    if (Constraint.size() == 7 && Constraint[0] == '{' &&
16665        tolower(Constraint[1]) == 's' &&
16666        tolower(Constraint[2]) == 't' &&
16667        Constraint[3] == '(' &&
16668        (Constraint[4] >= '0' && Constraint[4] <= '7') &&
16669        Constraint[5] == ')' &&
16670        Constraint[6] == '}') {
16671
16672      Res.first = X86::ST0+Constraint[4]-'0';
16673      Res.second = &X86::RFP80RegClass;
16674      return Res;
16675    }
16676
16677    // GCC allows "st(0)" to be called just plain "st".
16678    if (StringRef("{st}").equals_lower(Constraint)) {
16679      Res.first = X86::ST0;
16680      Res.second = &X86::RFP80RegClass;
16681      return Res;
16682    }
16683
16684    // flags -> EFLAGS
16685    if (StringRef("{flags}").equals_lower(Constraint)) {
16686      Res.first = X86::EFLAGS;
16687      Res.second = &X86::CCRRegClass;
16688      return Res;
16689    }
16690
16691    // 'A' means EAX + EDX.
16692    if (Constraint == "A") {
16693      Res.first = X86::EAX;
16694      Res.second = &X86::GR32_ADRegClass;
16695      return Res;
16696    }
16697    return Res;
16698  }
16699
16700  // Otherwise, check to see if this is a register class of the wrong value
16701  // type.  For example, we want to map "{ax},i32" -> {eax}, we don't want it to
16702  // turn into {ax},{dx}.
16703  if (Res.second->hasType(VT))
16704    return Res;   // Correct type already, nothing to do.
16705
16706  // All of the single-register GCC register classes map their values onto
16707  // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp".  If we
16708  // really want an 8-bit or 32-bit register, map to the appropriate register
16709  // class and return the appropriate register.
16710  if (Res.second == &X86::GR16RegClass) {
16711    if (VT == MVT::i8) {
16712      unsigned DestReg = 0;
16713      switch (Res.first) {
16714      default: break;
16715      case X86::AX: DestReg = X86::AL; break;
16716      case X86::DX: DestReg = X86::DL; break;
16717      case X86::CX: DestReg = X86::CL; break;
16718      case X86::BX: DestReg = X86::BL; break;
16719      }
16720      if (DestReg) {
16721        Res.first = DestReg;
16722        Res.second = &X86::GR8RegClass;
16723      }
16724    } else if (VT == MVT::i32) {
16725      unsigned DestReg = 0;
16726      switch (Res.first) {
16727      default: break;
16728      case X86::AX: DestReg = X86::EAX; break;
16729      case X86::DX: DestReg = X86::EDX; break;
16730      case X86::CX: DestReg = X86::ECX; break;
16731      case X86::BX: DestReg = X86::EBX; break;
16732      case X86::SI: DestReg = X86::ESI; break;
16733      case X86::DI: DestReg = X86::EDI; break;
16734      case X86::BP: DestReg = X86::EBP; break;
16735      case X86::SP: DestReg = X86::ESP; break;
16736      }
16737      if (DestReg) {
16738        Res.first = DestReg;
16739        Res.second = &X86::GR32RegClass;
16740      }
16741    } else if (VT == MVT::i64) {
16742      unsigned DestReg = 0;
16743      switch (Res.first) {
16744      default: break;
16745      case X86::AX: DestReg = X86::RAX; break;
16746      case X86::DX: DestReg = X86::RDX; break;
16747      case X86::CX: DestReg = X86::RCX; break;
16748      case X86::BX: DestReg = X86::RBX; break;
16749      case X86::SI: DestReg = X86::RSI; break;
16750      case X86::DI: DestReg = X86::RDI; break;
16751      case X86::BP: DestReg = X86::RBP; break;
16752      case X86::SP: DestReg = X86::RSP; break;
16753      }
16754      if (DestReg) {
16755        Res.first = DestReg;
16756        Res.second = &X86::GR64RegClass;
16757      }
16758    }
16759  } else if (Res.second == &X86::FR32RegClass ||
16760             Res.second == &X86::FR64RegClass ||
16761             Res.second == &X86::VR128RegClass) {
16762    // Handle references to XMM physical registers that got mapped into the
16763    // wrong class.  This can happen with constraints like {xmm0} where the
16764    // target independent register mapper will just pick the first match it can
16765    // find, ignoring the required type.
16766
16767    if (VT == MVT::f32 || VT == MVT::i32)
16768      Res.second = &X86::FR32RegClass;
16769    else if (VT == MVT::f64 || VT == MVT::i64)
16770      Res.second = &X86::FR64RegClass;
16771    else if (X86::VR128RegClass.hasType(VT))
16772      Res.second = &X86::VR128RegClass;
16773    else if (X86::VR256RegClass.hasType(VT))
16774      Res.second = &X86::VR256RegClass;
16775  }
16776
16777  return Res;
16778}
16779