1//===-- X86ISelLowering.cpp - X86 DAG Lowering Implementation -------------===//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file defines the interfaces that X86 uses to lower LLVM code into a
11// selection DAG.
12//
13//===----------------------------------------------------------------------===//
14
15#define DEBUG_TYPE "x86-isel"
16#include "X86ISelLowering.h"
17#include "X86.h"
18#include "X86InstrBuilder.h"
19#include "X86TargetMachine.h"
20#include "X86TargetObjectFile.h"
21#include "Utils/X86ShuffleDecode.h"
22#include "llvm/CallingConv.h"
23#include "llvm/Constants.h"
24#include "llvm/DerivedTypes.h"
25#include "llvm/GlobalAlias.h"
26#include "llvm/GlobalVariable.h"
27#include "llvm/Function.h"
28#include "llvm/Instructions.h"
29#include "llvm/Intrinsics.h"
30#include "llvm/LLVMContext.h"
31#include "llvm/CodeGen/IntrinsicLowering.h"
32#include "llvm/CodeGen/MachineFrameInfo.h"
33#include "llvm/CodeGen/MachineFunction.h"
34#include "llvm/CodeGen/MachineInstrBuilder.h"
35#include "llvm/CodeGen/MachineJumpTableInfo.h"
36#include "llvm/CodeGen/MachineModuleInfo.h"
37#include "llvm/CodeGen/MachineRegisterInfo.h"
38#include "llvm/MC/MCAsmInfo.h"
39#include "llvm/MC/MCContext.h"
40#include "llvm/MC/MCExpr.h"
41#include "llvm/MC/MCSymbol.h"
42#include "llvm/ADT/SmallSet.h"
43#include "llvm/ADT/Statistic.h"
44#include "llvm/ADT/StringExtras.h"
45#include "llvm/ADT/VariadicFunction.h"
46#include "llvm/Support/CallSite.h"
47#include "llvm/Support/Debug.h"
48#include "llvm/Support/ErrorHandling.h"
49#include "llvm/Support/MathExtras.h"
50#include "llvm/Target/TargetOptions.h"
51#include <bitset>
52#include <cctype>
53using namespace llvm;
54
55STATISTIC(NumTailCalls, "Number of tail calls");
56
57// Forward declarations.
58static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
59                       SDValue V2);
60
61/// Generate a DAG to grab 128-bits from a vector > 128 bits.  This
62/// sets things up to match to an AVX VEXTRACTF128 instruction or a
63/// simple subregister reference.  Idx is an index in the 128 bits we
64/// want.  It need not be aligned to a 128-bit bounday.  That makes
65/// lowering EXTRACT_VECTOR_ELT operations easier.
66static SDValue Extract128BitVector(SDValue Vec, unsigned IdxVal,
67                                   SelectionDAG &DAG, DebugLoc dl) {
68  EVT VT = Vec.getValueType();
69  assert(VT.is256BitVector() && "Unexpected vector size!");
70  EVT ElVT = VT.getVectorElementType();
71  unsigned Factor = VT.getSizeInBits()/128;
72  EVT ResultVT = EVT::getVectorVT(*DAG.getContext(), ElVT,
73                                  VT.getVectorNumElements()/Factor);
74
75  // Extract from UNDEF is UNDEF.
76  if (Vec.getOpcode() == ISD::UNDEF)
77    return DAG.getUNDEF(ResultVT);
78
79  // Extract the relevant 128 bits.  Generate an EXTRACT_SUBVECTOR
80  // we can match to VEXTRACTF128.
81  unsigned ElemsPerChunk = 128 / ElVT.getSizeInBits();
82
83  // This is the index of the first element of the 128-bit chunk
84  // we want.
85  unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits()) / 128)
86                               * ElemsPerChunk);
87
88  SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal);
89  SDValue Result = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, ResultVT, Vec,
90                               VecIdx);
91
92  return Result;
93}
94
95/// Generate a DAG to put 128-bits into a vector > 128 bits.  This
96/// sets things up to match to an AVX VINSERTF128 instruction or a
97/// simple superregister reference.  Idx is an index in the 128 bits
98/// we want.  It need not be aligned to a 128-bit bounday.  That makes
99/// lowering INSERT_VECTOR_ELT operations easier.
100static SDValue Insert128BitVector(SDValue Result, SDValue Vec,
101                                  unsigned IdxVal, SelectionDAG &DAG,
102                                  DebugLoc dl) {
103  // Inserting UNDEF is Result
104  if (Vec.getOpcode() == ISD::UNDEF)
105    return Result;
106
107  EVT VT = Vec.getValueType();
108  assert(VT.is128BitVector() && "Unexpected vector size!");
109
110  EVT ElVT = VT.getVectorElementType();
111  EVT ResultVT = Result.getValueType();
112
113  // Insert the relevant 128 bits.
114  unsigned ElemsPerChunk = 128/ElVT.getSizeInBits();
115
116  // This is the index of the first element of the 128-bit chunk
117  // we want.
118  unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits())/128)
119                               * ElemsPerChunk);
120
121  SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal);
122  return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Result, Vec,
123                     VecIdx);
124}
125
126/// Concat two 128-bit vectors into a 256 bit vector using VINSERTF128
127/// instructions. This is used because creating CONCAT_VECTOR nodes of
128/// BUILD_VECTORS returns a larger BUILD_VECTOR while we're trying to lower
129/// large BUILD_VECTORS.
130static SDValue Concat128BitVectors(SDValue V1, SDValue V2, EVT VT,
131                                   unsigned NumElems, SelectionDAG &DAG,
132                                   DebugLoc dl) {
133  SDValue V = Insert128BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
134  return Insert128BitVector(V, V2, NumElems/2, DAG, dl);
135}
136
137static TargetLoweringObjectFile *createTLOF(X86TargetMachine &TM) {
138  const X86Subtarget *Subtarget = &TM.getSubtarget<X86Subtarget>();
139  bool is64Bit = Subtarget->is64Bit();
140
141  if (Subtarget->isTargetEnvMacho()) {
142    if (is64Bit)
143      return new X86_64MachoTargetObjectFile();
144    return new TargetLoweringObjectFileMachO();
145  }
146
147  if (Subtarget->isTargetLinux())
148    return new X86LinuxTargetObjectFile();
149  if (Subtarget->isTargetELF())
150    return new TargetLoweringObjectFileELF();
151  if (Subtarget->isTargetCOFF() && !Subtarget->isTargetEnvMacho())
152    return new TargetLoweringObjectFileCOFF();
153  llvm_unreachable("unknown subtarget type");
154}
155
156X86TargetLowering::X86TargetLowering(X86TargetMachine &TM)
157  : TargetLowering(TM, createTLOF(TM)) {
158  Subtarget = &TM.getSubtarget<X86Subtarget>();
159  X86ScalarSSEf64 = Subtarget->hasSSE2();
160  X86ScalarSSEf32 = Subtarget->hasSSE1();
161  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  // Bypass i32 with i8 on Atom when compiling with O2
186  if (Subtarget->hasSlowDivide() && TM.getOptLevel() >= CodeGenOpt::Default)
187    addBypassSlowDivType(Type::getInt32Ty(getGlobalContext()), Type::getInt8Ty(getGlobalContext()));
188
189  if (Subtarget->isTargetWindows() && !Subtarget->isTargetCygMing()) {
190    // Setup Windows compiler runtime calls.
191    setLibcallName(RTLIB::SDIV_I64, "_alldiv");
192    setLibcallName(RTLIB::UDIV_I64, "_aulldiv");
193    setLibcallName(RTLIB::SREM_I64, "_allrem");
194    setLibcallName(RTLIB::UREM_I64, "_aullrem");
195    setLibcallName(RTLIB::MUL_I64, "_allmul");
196    setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::X86_StdCall);
197    setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::X86_StdCall);
198    setLibcallCallingConv(RTLIB::SREM_I64, CallingConv::X86_StdCall);
199    setLibcallCallingConv(RTLIB::UREM_I64, CallingConv::X86_StdCall);
200    setLibcallCallingConv(RTLIB::MUL_I64, CallingConv::X86_StdCall);
201
202    // The _ftol2 runtime function has an unusual calling conv, which
203    // is modeled by a special pseudo-instruction.
204    setLibcallName(RTLIB::FPTOUINT_F64_I64, 0);
205    setLibcallName(RTLIB::FPTOUINT_F32_I64, 0);
206    setLibcallName(RTLIB::FPTOUINT_F64_I32, 0);
207    setLibcallName(RTLIB::FPTOUINT_F32_I32, 0);
208  }
209
210  if (Subtarget->isTargetDarwin()) {
211    // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
212    setUseUnderscoreSetJmp(false);
213    setUseUnderscoreLongJmp(false);
214  } else if (Subtarget->isTargetMingw()) {
215    // MS runtime is weird: it exports _setjmp, but longjmp!
216    setUseUnderscoreSetJmp(true);
217    setUseUnderscoreLongJmp(false);
218  } else {
219    setUseUnderscoreSetJmp(true);
220    setUseUnderscoreLongJmp(true);
221  }
222
223  // Set up the register classes.
224  addRegisterClass(MVT::i8, &X86::GR8RegClass);
225  addRegisterClass(MVT::i16, &X86::GR16RegClass);
226  addRegisterClass(MVT::i32, &X86::GR32RegClass);
227  if (Subtarget->is64Bit())
228    addRegisterClass(MVT::i64, &X86::GR64RegClass);
229
230  setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
231
232  // We don't accept any truncstore of integer registers.
233  setTruncStoreAction(MVT::i64, MVT::i32, Expand);
234  setTruncStoreAction(MVT::i64, MVT::i16, Expand);
235  setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
236  setTruncStoreAction(MVT::i32, MVT::i16, Expand);
237  setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
238  setTruncStoreAction(MVT::i16, MVT::i8,  Expand);
239
240  // SETOEQ and SETUNE require checking two conditions.
241  setCondCodeAction(ISD::SETOEQ, MVT::f32, Expand);
242  setCondCodeAction(ISD::SETOEQ, MVT::f64, Expand);
243  setCondCodeAction(ISD::SETOEQ, MVT::f80, Expand);
244  setCondCodeAction(ISD::SETUNE, MVT::f32, Expand);
245  setCondCodeAction(ISD::SETUNE, MVT::f64, Expand);
246  setCondCodeAction(ISD::SETUNE, MVT::f80, Expand);
247
248  // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
249  // operation.
250  setOperationAction(ISD::UINT_TO_FP       , MVT::i1   , Promote);
251  setOperationAction(ISD::UINT_TO_FP       , MVT::i8   , Promote);
252  setOperationAction(ISD::UINT_TO_FP       , MVT::i16  , Promote);
253
254  if (Subtarget->is64Bit()) {
255    setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Promote);
256    setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Custom);
257  } else if (!TM.Options.UseSoftFloat) {
258    // We have an algorithm for SSE2->double, and we turn this into a
259    // 64-bit FILD followed by conditional FADD for other targets.
260    setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Custom);
261    // We have an algorithm for SSE2, and we turn this into a 64-bit
262    // FILD for other targets.
263    setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Custom);
264  }
265
266  // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
267  // this operation.
268  setOperationAction(ISD::SINT_TO_FP       , MVT::i1   , Promote);
269  setOperationAction(ISD::SINT_TO_FP       , MVT::i8   , Promote);
270
271  if (!TM.Options.UseSoftFloat) {
272    // SSE has no i16 to fp conversion, only i32
273    if (X86ScalarSSEf32) {
274      setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
275      // f32 and f64 cases are Legal, f80 case is not
276      setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
277    } else {
278      setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Custom);
279      setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
280    }
281  } else {
282    setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
283    setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Promote);
284  }
285
286  // In 32-bit mode these are custom lowered.  In 64-bit mode F32 and F64
287  // are Legal, f80 is custom lowered.
288  setOperationAction(ISD::FP_TO_SINT     , MVT::i64  , Custom);
289  setOperationAction(ISD::SINT_TO_FP     , MVT::i64  , Custom);
290
291  // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
292  // this operation.
293  setOperationAction(ISD::FP_TO_SINT       , MVT::i1   , Promote);
294  setOperationAction(ISD::FP_TO_SINT       , MVT::i8   , Promote);
295
296  if (X86ScalarSSEf32) {
297    setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Promote);
298    // f32 and f64 cases are Legal, f80 case is not
299    setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
300  } else {
301    setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Custom);
302    setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
303  }
304
305  // Handle FP_TO_UINT by promoting the destination to a larger signed
306  // conversion.
307  setOperationAction(ISD::FP_TO_UINT       , MVT::i1   , Promote);
308  setOperationAction(ISD::FP_TO_UINT       , MVT::i8   , Promote);
309  setOperationAction(ISD::FP_TO_UINT       , MVT::i16  , Promote);
310
311  if (Subtarget->is64Bit()) {
312    setOperationAction(ISD::FP_TO_UINT     , MVT::i64  , Expand);
313    setOperationAction(ISD::FP_TO_UINT     , MVT::i32  , Promote);
314  } else if (!TM.Options.UseSoftFloat) {
315    // Since AVX is a superset of SSE3, only check for SSE here.
316    if (Subtarget->hasSSE1() && !Subtarget->hasSSE3())
317      // Expand FP_TO_UINT into a select.
318      // FIXME: We would like to use a Custom expander here eventually to do
319      // the optimal thing for SSE vs. the default expansion in the legalizer.
320      setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Expand);
321    else
322      // With SSE3 we can use fisttpll to convert to a signed i64; without
323      // SSE, we're stuck with a fistpll.
324      setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Custom);
325  }
326
327  if (isTargetFTOL()) {
328    // Use the _ftol2 runtime function, which has a pseudo-instruction
329    // to handle its weird calling convention.
330    setOperationAction(ISD::FP_TO_UINT     , MVT::i64  , Custom);
331  }
332
333  // TODO: when we have SSE, these could be more efficient, by using movd/movq.
334  if (!X86ScalarSSEf64) {
335    setOperationAction(ISD::BITCAST        , MVT::f32  , Expand);
336    setOperationAction(ISD::BITCAST        , MVT::i32  , Expand);
337    if (Subtarget->is64Bit()) {
338      setOperationAction(ISD::BITCAST      , MVT::f64  , Expand);
339      // Without SSE, i64->f64 goes through memory.
340      setOperationAction(ISD::BITCAST      , MVT::i64  , Expand);
341    }
342  }
343
344  // Scalar integer divide and remainder are lowered to use operations that
345  // produce two results, to match the available instructions. This exposes
346  // the two-result form to trivial CSE, which is able to combine x/y and x%y
347  // into a single instruction.
348  //
349  // Scalar integer multiply-high is also lowered to use two-result
350  // operations, to match the available instructions. However, plain multiply
351  // (low) operations are left as Legal, as there are single-result
352  // instructions for this in x86. Using the two-result multiply instructions
353  // when both high and low results are needed must be arranged by dagcombine.
354  for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
355    MVT VT = IntVTs[i];
356    setOperationAction(ISD::MULHS, VT, Expand);
357    setOperationAction(ISD::MULHU, VT, Expand);
358    setOperationAction(ISD::SDIV, VT, Expand);
359    setOperationAction(ISD::UDIV, VT, Expand);
360    setOperationAction(ISD::SREM, VT, Expand);
361    setOperationAction(ISD::UREM, VT, Expand);
362
363    // Add/Sub overflow ops with MVT::Glues are lowered to EFLAGS dependences.
364    setOperationAction(ISD::ADDC, VT, Custom);
365    setOperationAction(ISD::ADDE, VT, Custom);
366    setOperationAction(ISD::SUBC, VT, Custom);
367    setOperationAction(ISD::SUBE, VT, Custom);
368  }
369
370  setOperationAction(ISD::BR_JT            , MVT::Other, Expand);
371  setOperationAction(ISD::BRCOND           , MVT::Other, Custom);
372  setOperationAction(ISD::BR_CC            , MVT::Other, Expand);
373  setOperationAction(ISD::SELECT_CC        , MVT::Other, Expand);
374  if (Subtarget->is64Bit())
375    setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
376  setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16  , Legal);
377  setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8   , Legal);
378  setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1   , Expand);
379  setOperationAction(ISD::FP_ROUND_INREG   , MVT::f32  , Expand);
380  setOperationAction(ISD::FREM             , MVT::f32  , Expand);
381  setOperationAction(ISD::FREM             , MVT::f64  , Expand);
382  setOperationAction(ISD::FREM             , MVT::f80  , Expand);
383  setOperationAction(ISD::FLT_ROUNDS_      , MVT::i32  , Custom);
384
385  // Promote the i8 variants and force them on up to i32 which has a shorter
386  // encoding.
387  setOperationAction(ISD::CTTZ             , MVT::i8   , Promote);
388  AddPromotedToType (ISD::CTTZ             , MVT::i8   , MVT::i32);
389  setOperationAction(ISD::CTTZ_ZERO_UNDEF  , MVT::i8   , Promote);
390  AddPromotedToType (ISD::CTTZ_ZERO_UNDEF  , MVT::i8   , MVT::i32);
391  if (Subtarget->hasBMI()) {
392    setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16  , Expand);
393    setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32  , Expand);
394    if (Subtarget->is64Bit())
395      setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
396  } else {
397    setOperationAction(ISD::CTTZ           , MVT::i16  , Custom);
398    setOperationAction(ISD::CTTZ           , MVT::i32  , Custom);
399    if (Subtarget->is64Bit())
400      setOperationAction(ISD::CTTZ         , MVT::i64  , Custom);
401  }
402
403  if (Subtarget->hasLZCNT()) {
404    // When promoting the i8 variants, force them to i32 for a shorter
405    // encoding.
406    setOperationAction(ISD::CTLZ           , MVT::i8   , Promote);
407    AddPromotedToType (ISD::CTLZ           , MVT::i8   , MVT::i32);
408    setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8   , Promote);
409    AddPromotedToType (ISD::CTLZ_ZERO_UNDEF, MVT::i8   , MVT::i32);
410    setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16  , Expand);
411    setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32  , Expand);
412    if (Subtarget->is64Bit())
413      setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
414  } else {
415    setOperationAction(ISD::CTLZ           , MVT::i8   , Custom);
416    setOperationAction(ISD::CTLZ           , MVT::i16  , Custom);
417    setOperationAction(ISD::CTLZ           , MVT::i32  , Custom);
418    setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8   , Custom);
419    setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16  , Custom);
420    setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32  , Custom);
421    if (Subtarget->is64Bit()) {
422      setOperationAction(ISD::CTLZ         , MVT::i64  , Custom);
423      setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Custom);
424    }
425  }
426
427  if (Subtarget->hasPOPCNT()) {
428    setOperationAction(ISD::CTPOP          , MVT::i8   , Promote);
429  } else {
430    setOperationAction(ISD::CTPOP          , MVT::i8   , Expand);
431    setOperationAction(ISD::CTPOP          , MVT::i16  , Expand);
432    setOperationAction(ISD::CTPOP          , MVT::i32  , Expand);
433    if (Subtarget->is64Bit())
434      setOperationAction(ISD::CTPOP        , MVT::i64  , Expand);
435  }
436
437  setOperationAction(ISD::READCYCLECOUNTER , MVT::i64  , Custom);
438  setOperationAction(ISD::BSWAP            , MVT::i16  , Expand);
439
440  // These should be promoted to a larger select which is supported.
441  setOperationAction(ISD::SELECT          , MVT::i1   , Promote);
442  // X86 wants to expand cmov itself.
443  setOperationAction(ISD::SELECT          , MVT::i8   , Custom);
444  setOperationAction(ISD::SELECT          , MVT::i16  , Custom);
445  setOperationAction(ISD::SELECT          , MVT::i32  , Custom);
446  setOperationAction(ISD::SELECT          , MVT::f32  , Custom);
447  setOperationAction(ISD::SELECT          , MVT::f64  , Custom);
448  setOperationAction(ISD::SELECT          , MVT::f80  , Custom);
449  setOperationAction(ISD::SETCC           , MVT::i8   , Custom);
450  setOperationAction(ISD::SETCC           , MVT::i16  , Custom);
451  setOperationAction(ISD::SETCC           , MVT::i32  , Custom);
452  setOperationAction(ISD::SETCC           , MVT::f32  , Custom);
453  setOperationAction(ISD::SETCC           , MVT::f64  , Custom);
454  setOperationAction(ISD::SETCC           , MVT::f80  , Custom);
455  if (Subtarget->is64Bit()) {
456    setOperationAction(ISD::SELECT        , MVT::i64  , Custom);
457    setOperationAction(ISD::SETCC         , MVT::i64  , Custom);
458  }
459  setOperationAction(ISD::EH_RETURN       , MVT::Other, Custom);
460
461  // Darwin ABI issue.
462  setOperationAction(ISD::ConstantPool    , MVT::i32  , Custom);
463  setOperationAction(ISD::JumpTable       , MVT::i32  , Custom);
464  setOperationAction(ISD::GlobalAddress   , MVT::i32  , Custom);
465  setOperationAction(ISD::GlobalTLSAddress, MVT::i32  , Custom);
466  if (Subtarget->is64Bit())
467    setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
468  setOperationAction(ISD::ExternalSymbol  , MVT::i32  , Custom);
469  setOperationAction(ISD::BlockAddress    , MVT::i32  , Custom);
470  if (Subtarget->is64Bit()) {
471    setOperationAction(ISD::ConstantPool  , MVT::i64  , Custom);
472    setOperationAction(ISD::JumpTable     , MVT::i64  , Custom);
473    setOperationAction(ISD::GlobalAddress , MVT::i64  , Custom);
474    setOperationAction(ISD::ExternalSymbol, MVT::i64  , Custom);
475    setOperationAction(ISD::BlockAddress  , MVT::i64  , Custom);
476  }
477  // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
478  setOperationAction(ISD::SHL_PARTS       , MVT::i32  , Custom);
479  setOperationAction(ISD::SRA_PARTS       , MVT::i32  , Custom);
480  setOperationAction(ISD::SRL_PARTS       , MVT::i32  , Custom);
481  if (Subtarget->is64Bit()) {
482    setOperationAction(ISD::SHL_PARTS     , MVT::i64  , Custom);
483    setOperationAction(ISD::SRA_PARTS     , MVT::i64  , Custom);
484    setOperationAction(ISD::SRL_PARTS     , MVT::i64  , Custom);
485  }
486
487  if (Subtarget->hasSSE1())
488    setOperationAction(ISD::PREFETCH      , MVT::Other, Legal);
489
490  setOperationAction(ISD::MEMBARRIER    , MVT::Other, Custom);
491  setOperationAction(ISD::ATOMIC_FENCE  , MVT::Other, Custom);
492
493  // On X86 and X86-64, atomic operations are lowered to locked instructions.
494  // Locked instructions, in turn, have implicit fence semantics (all memory
495  // operations are flushed before issuing the locked instruction, and they
496  // are not buffered), so we can fold away the common pattern of
497  // fence-atomic-fence.
498  setShouldFoldAtomicFences(true);
499
500  // Expand certain atomics
501  for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
502    MVT VT = IntVTs[i];
503    setOperationAction(ISD::ATOMIC_CMP_SWAP, VT, Custom);
504    setOperationAction(ISD::ATOMIC_LOAD_SUB, VT, Custom);
505    setOperationAction(ISD::ATOMIC_STORE, VT, Custom);
506  }
507
508  if (!Subtarget->is64Bit()) {
509    setOperationAction(ISD::ATOMIC_LOAD, MVT::i64, Custom);
510    setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i64, Custom);
511    setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
512    setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i64, Custom);
513    setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i64, Custom);
514    setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i64, Custom);
515    setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i64, Custom);
516    setOperationAction(ISD::ATOMIC_SWAP, MVT::i64, Custom);
517  }
518
519  if (Subtarget->hasCmpxchg16b()) {
520    setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i128, Custom);
521  }
522
523  // FIXME - use subtarget debug flags
524  if (!Subtarget->isTargetDarwin() &&
525      !Subtarget->isTargetELF() &&
526      !Subtarget->isTargetCygMing()) {
527    setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
528  }
529
530  setOperationAction(ISD::EXCEPTIONADDR, MVT::i64, Expand);
531  setOperationAction(ISD::EHSELECTION,   MVT::i64, Expand);
532  setOperationAction(ISD::EXCEPTIONADDR, MVT::i32, Expand);
533  setOperationAction(ISD::EHSELECTION,   MVT::i32, Expand);
534  if (Subtarget->is64Bit()) {
535    setExceptionPointerRegister(X86::RAX);
536    setExceptionSelectorRegister(X86::RDX);
537  } else {
538    setExceptionPointerRegister(X86::EAX);
539    setExceptionSelectorRegister(X86::EDX);
540  }
541  setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
542  setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
543
544  setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
545  setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
546
547  setOperationAction(ISD::TRAP, MVT::Other, Legal);
548
549  // VASTART needs to be custom lowered to use the VarArgsFrameIndex
550  setOperationAction(ISD::VASTART           , MVT::Other, Custom);
551  setOperationAction(ISD::VAEND             , MVT::Other, Expand);
552  if (Subtarget->is64Bit()) {
553    setOperationAction(ISD::VAARG           , MVT::Other, Custom);
554    setOperationAction(ISD::VACOPY          , MVT::Other, Custom);
555  } else {
556    setOperationAction(ISD::VAARG           , MVT::Other, Expand);
557    setOperationAction(ISD::VACOPY          , MVT::Other, Expand);
558  }
559
560  setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
561  setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
562
563  if (Subtarget->isTargetCOFF() && !Subtarget->isTargetEnvMacho())
564    setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
565                       MVT::i64 : MVT::i32, Custom);
566  else if (TM.Options.EnableSegmentedStacks)
567    setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
568                       MVT::i64 : MVT::i32, Custom);
569  else
570    setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
571                       MVT::i64 : MVT::i32, Expand);
572
573  if (!TM.Options.UseSoftFloat && X86ScalarSSEf64) {
574    // f32 and f64 use SSE.
575    // Set up the FP register classes.
576    addRegisterClass(MVT::f32, &X86::FR32RegClass);
577    addRegisterClass(MVT::f64, &X86::FR64RegClass);
578
579    // Use ANDPD to simulate FABS.
580    setOperationAction(ISD::FABS , MVT::f64, Custom);
581    setOperationAction(ISD::FABS , MVT::f32, Custom);
582
583    // Use XORP to simulate FNEG.
584    setOperationAction(ISD::FNEG , MVT::f64, Custom);
585    setOperationAction(ISD::FNEG , MVT::f32, Custom);
586
587    // Use ANDPD and ORPD to simulate FCOPYSIGN.
588    setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
589    setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
590
591    // Lower this to FGETSIGNx86 plus an AND.
592    setOperationAction(ISD::FGETSIGN, MVT::i64, Custom);
593    setOperationAction(ISD::FGETSIGN, MVT::i32, Custom);
594
595    // We don't support sin/cos/fmod
596    setOperationAction(ISD::FSIN , MVT::f64, Expand);
597    setOperationAction(ISD::FCOS , MVT::f64, Expand);
598    setOperationAction(ISD::FSIN , MVT::f32, Expand);
599    setOperationAction(ISD::FCOS , MVT::f32, Expand);
600
601    // Expand FP immediates into loads from the stack, except for the special
602    // cases we handle.
603    addLegalFPImmediate(APFloat(+0.0)); // xorpd
604    addLegalFPImmediate(APFloat(+0.0f)); // xorps
605  } else if (!TM.Options.UseSoftFloat && X86ScalarSSEf32) {
606    // Use SSE for f32, x87 for f64.
607    // Set up the FP register classes.
608    addRegisterClass(MVT::f32, &X86::FR32RegClass);
609    addRegisterClass(MVT::f64, &X86::RFP64RegClass);
610
611    // Use ANDPS to simulate FABS.
612    setOperationAction(ISD::FABS , MVT::f32, Custom);
613
614    // Use XORP to simulate FNEG.
615    setOperationAction(ISD::FNEG , MVT::f32, Custom);
616
617    setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
618
619    // Use ANDPS and ORPS to simulate FCOPYSIGN.
620    setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
621    setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
622
623    // We don't support sin/cos/fmod
624    setOperationAction(ISD::FSIN , MVT::f32, Expand);
625    setOperationAction(ISD::FCOS , MVT::f32, Expand);
626
627    // Special cases we handle for FP constants.
628    addLegalFPImmediate(APFloat(+0.0f)); // xorps
629    addLegalFPImmediate(APFloat(+0.0)); // FLD0
630    addLegalFPImmediate(APFloat(+1.0)); // FLD1
631    addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
632    addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
633
634    if (!TM.Options.UnsafeFPMath) {
635      setOperationAction(ISD::FSIN           , MVT::f64  , Expand);
636      setOperationAction(ISD::FCOS           , MVT::f64  , Expand);
637    }
638  } else if (!TM.Options.UseSoftFloat) {
639    // f32 and f64 in x87.
640    // Set up the FP register classes.
641    addRegisterClass(MVT::f64, &X86::RFP64RegClass);
642    addRegisterClass(MVT::f32, &X86::RFP32RegClass);
643
644    setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
645    setOperationAction(ISD::UNDEF,     MVT::f32, Expand);
646    setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
647    setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
648
649    if (!TM.Options.UnsafeFPMath) {
650      setOperationAction(ISD::FSIN           , MVT::f64  , Expand);
651      setOperationAction(ISD::FCOS           , MVT::f64  , Expand);
652    }
653    addLegalFPImmediate(APFloat(+0.0)); // FLD0
654    addLegalFPImmediate(APFloat(+1.0)); // FLD1
655    addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
656    addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
657    addLegalFPImmediate(APFloat(+0.0f)); // FLD0
658    addLegalFPImmediate(APFloat(+1.0f)); // FLD1
659    addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
660    addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
661  }
662
663  // We don't support FMA.
664  setOperationAction(ISD::FMA, MVT::f64, Expand);
665  setOperationAction(ISD::FMA, MVT::f32, Expand);
666
667  // Long double always uses X87.
668  if (!TM.Options.UseSoftFloat) {
669    addRegisterClass(MVT::f80, &X86::RFP80RegClass);
670    setOperationAction(ISD::UNDEF,     MVT::f80, Expand);
671    setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
672    {
673      APFloat TmpFlt = APFloat::getZero(APFloat::x87DoubleExtended);
674      addLegalFPImmediate(TmpFlt);  // FLD0
675      TmpFlt.changeSign();
676      addLegalFPImmediate(TmpFlt);  // FLD0/FCHS
677
678      bool ignored;
679      APFloat TmpFlt2(+1.0);
680      TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
681                      &ignored);
682      addLegalFPImmediate(TmpFlt2);  // FLD1
683      TmpFlt2.changeSign();
684      addLegalFPImmediate(TmpFlt2);  // FLD1/FCHS
685    }
686
687    if (!TM.Options.UnsafeFPMath) {
688      setOperationAction(ISD::FSIN           , MVT::f80  , Expand);
689      setOperationAction(ISD::FCOS           , MVT::f80  , Expand);
690    }
691
692    setOperationAction(ISD::FFLOOR, MVT::f80, Expand);
693    setOperationAction(ISD::FCEIL,  MVT::f80, Expand);
694    setOperationAction(ISD::FTRUNC, MVT::f80, Expand);
695    setOperationAction(ISD::FRINT,  MVT::f80, Expand);
696    setOperationAction(ISD::FNEARBYINT, MVT::f80, Expand);
697    setOperationAction(ISD::FMA, MVT::f80, Expand);
698  }
699
700  // Always use a library call for pow.
701  setOperationAction(ISD::FPOW             , MVT::f32  , Expand);
702  setOperationAction(ISD::FPOW             , MVT::f64  , Expand);
703  setOperationAction(ISD::FPOW             , MVT::f80  , Expand);
704
705  setOperationAction(ISD::FLOG, MVT::f80, Expand);
706  setOperationAction(ISD::FLOG2, MVT::f80, Expand);
707  setOperationAction(ISD::FLOG10, MVT::f80, Expand);
708  setOperationAction(ISD::FEXP, MVT::f80, Expand);
709  setOperationAction(ISD::FEXP2, MVT::f80, Expand);
710
711  // First set operation action for all vector types to either promote
712  // (for widening) or expand (for scalarization). Then we will selectively
713  // turn on ones that can be effectively codegen'd.
714  for (int VT = MVT::FIRST_VECTOR_VALUETYPE;
715           VT <= MVT::LAST_VECTOR_VALUETYPE; ++VT) {
716    setOperationAction(ISD::ADD , (MVT::SimpleValueType)VT, Expand);
717    setOperationAction(ISD::SUB , (MVT::SimpleValueType)VT, Expand);
718    setOperationAction(ISD::FADD, (MVT::SimpleValueType)VT, Expand);
719    setOperationAction(ISD::FNEG, (MVT::SimpleValueType)VT, Expand);
720    setOperationAction(ISD::FSUB, (MVT::SimpleValueType)VT, Expand);
721    setOperationAction(ISD::MUL , (MVT::SimpleValueType)VT, Expand);
722    setOperationAction(ISD::FMUL, (MVT::SimpleValueType)VT, Expand);
723    setOperationAction(ISD::SDIV, (MVT::SimpleValueType)VT, Expand);
724    setOperationAction(ISD::UDIV, (MVT::SimpleValueType)VT, Expand);
725    setOperationAction(ISD::FDIV, (MVT::SimpleValueType)VT, Expand);
726    setOperationAction(ISD::SREM, (MVT::SimpleValueType)VT, Expand);
727    setOperationAction(ISD::UREM, (MVT::SimpleValueType)VT, Expand);
728    setOperationAction(ISD::LOAD, (MVT::SimpleValueType)VT, Expand);
729    setOperationAction(ISD::VECTOR_SHUFFLE, (MVT::SimpleValueType)VT, Expand);
730    setOperationAction(ISD::EXTRACT_VECTOR_ELT,(MVT::SimpleValueType)VT,Expand);
731    setOperationAction(ISD::INSERT_VECTOR_ELT,(MVT::SimpleValueType)VT, Expand);
732    setOperationAction(ISD::EXTRACT_SUBVECTOR,(MVT::SimpleValueType)VT,Expand);
733    setOperationAction(ISD::INSERT_SUBVECTOR,(MVT::SimpleValueType)VT,Expand);
734    setOperationAction(ISD::FABS, (MVT::SimpleValueType)VT, Expand);
735    setOperationAction(ISD::FSIN, (MVT::SimpleValueType)VT, Expand);
736    setOperationAction(ISD::FCOS, (MVT::SimpleValueType)VT, Expand);
737    setOperationAction(ISD::FREM, (MVT::SimpleValueType)VT, Expand);
738    setOperationAction(ISD::FMA,  (MVT::SimpleValueType)VT, Expand);
739    setOperationAction(ISD::FPOWI, (MVT::SimpleValueType)VT, Expand);
740    setOperationAction(ISD::FSQRT, (MVT::SimpleValueType)VT, Expand);
741    setOperationAction(ISD::FCOPYSIGN, (MVT::SimpleValueType)VT, Expand);
742    setOperationAction(ISD::FFLOOR, (MVT::SimpleValueType)VT, Expand);
743    setOperationAction(ISD::SMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
744    setOperationAction(ISD::UMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
745    setOperationAction(ISD::SDIVREM, (MVT::SimpleValueType)VT, Expand);
746    setOperationAction(ISD::UDIVREM, (MVT::SimpleValueType)VT, Expand);
747    setOperationAction(ISD::FPOW, (MVT::SimpleValueType)VT, Expand);
748    setOperationAction(ISD::CTPOP, (MVT::SimpleValueType)VT, Expand);
749    setOperationAction(ISD::CTTZ, (MVT::SimpleValueType)VT, Expand);
750    setOperationAction(ISD::CTTZ_ZERO_UNDEF, (MVT::SimpleValueType)VT, Expand);
751    setOperationAction(ISD::CTLZ, (MVT::SimpleValueType)VT, Expand);
752    setOperationAction(ISD::CTLZ_ZERO_UNDEF, (MVT::SimpleValueType)VT, Expand);
753    setOperationAction(ISD::SHL, (MVT::SimpleValueType)VT, Expand);
754    setOperationAction(ISD::SRA, (MVT::SimpleValueType)VT, Expand);
755    setOperationAction(ISD::SRL, (MVT::SimpleValueType)VT, Expand);
756    setOperationAction(ISD::ROTL, (MVT::SimpleValueType)VT, Expand);
757    setOperationAction(ISD::ROTR, (MVT::SimpleValueType)VT, Expand);
758    setOperationAction(ISD::BSWAP, (MVT::SimpleValueType)VT, Expand);
759    setOperationAction(ISD::SETCC, (MVT::SimpleValueType)VT, Expand);
760    setOperationAction(ISD::FLOG, (MVT::SimpleValueType)VT, Expand);
761    setOperationAction(ISD::FLOG2, (MVT::SimpleValueType)VT, Expand);
762    setOperationAction(ISD::FLOG10, (MVT::SimpleValueType)VT, Expand);
763    setOperationAction(ISD::FEXP, (MVT::SimpleValueType)VT, Expand);
764    setOperationAction(ISD::FEXP2, (MVT::SimpleValueType)VT, Expand);
765    setOperationAction(ISD::FP_TO_UINT, (MVT::SimpleValueType)VT, Expand);
766    setOperationAction(ISD::FP_TO_SINT, (MVT::SimpleValueType)VT, Expand);
767    setOperationAction(ISD::UINT_TO_FP, (MVT::SimpleValueType)VT, Expand);
768    setOperationAction(ISD::SINT_TO_FP, (MVT::SimpleValueType)VT, Expand);
769    setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,Expand);
770    setOperationAction(ISD::TRUNCATE,  (MVT::SimpleValueType)VT, Expand);
771    setOperationAction(ISD::SIGN_EXTEND,  (MVT::SimpleValueType)VT, Expand);
772    setOperationAction(ISD::ZERO_EXTEND,  (MVT::SimpleValueType)VT, Expand);
773    setOperationAction(ISD::ANY_EXTEND,  (MVT::SimpleValueType)VT, Expand);
774    setOperationAction(ISD::VSELECT,  (MVT::SimpleValueType)VT, Expand);
775    for (int InnerVT = MVT::FIRST_VECTOR_VALUETYPE;
776             InnerVT <= MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
777      setTruncStoreAction((MVT::SimpleValueType)VT,
778                          (MVT::SimpleValueType)InnerVT, Expand);
779    setLoadExtAction(ISD::SEXTLOAD, (MVT::SimpleValueType)VT, Expand);
780    setLoadExtAction(ISD::ZEXTLOAD, (MVT::SimpleValueType)VT, Expand);
781    setLoadExtAction(ISD::EXTLOAD, (MVT::SimpleValueType)VT, Expand);
782  }
783
784  // FIXME: In order to prevent SSE instructions being expanded to MMX ones
785  // with -msoft-float, disable use of MMX as well.
786  if (!TM.Options.UseSoftFloat && Subtarget->hasMMX()) {
787    addRegisterClass(MVT::x86mmx, &X86::VR64RegClass);
788    // No operations on x86mmx supported, everything uses intrinsics.
789  }
790
791  // MMX-sized vectors (other than x86mmx) are expected to be expanded
792  // into smaller operations.
793  setOperationAction(ISD::MULHS,              MVT::v8i8,  Expand);
794  setOperationAction(ISD::MULHS,              MVT::v4i16, Expand);
795  setOperationAction(ISD::MULHS,              MVT::v2i32, Expand);
796  setOperationAction(ISD::MULHS,              MVT::v1i64, Expand);
797  setOperationAction(ISD::AND,                MVT::v8i8,  Expand);
798  setOperationAction(ISD::AND,                MVT::v4i16, Expand);
799  setOperationAction(ISD::AND,                MVT::v2i32, Expand);
800  setOperationAction(ISD::AND,                MVT::v1i64, Expand);
801  setOperationAction(ISD::OR,                 MVT::v8i8,  Expand);
802  setOperationAction(ISD::OR,                 MVT::v4i16, Expand);
803  setOperationAction(ISD::OR,                 MVT::v2i32, Expand);
804  setOperationAction(ISD::OR,                 MVT::v1i64, Expand);
805  setOperationAction(ISD::XOR,                MVT::v8i8,  Expand);
806  setOperationAction(ISD::XOR,                MVT::v4i16, Expand);
807  setOperationAction(ISD::XOR,                MVT::v2i32, Expand);
808  setOperationAction(ISD::XOR,                MVT::v1i64, Expand);
809  setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i8,  Expand);
810  setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v4i16, Expand);
811  setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v2i32, Expand);
812  setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v1i64, Expand);
813  setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v1i64, Expand);
814  setOperationAction(ISD::SELECT,             MVT::v8i8,  Expand);
815  setOperationAction(ISD::SELECT,             MVT::v4i16, Expand);
816  setOperationAction(ISD::SELECT,             MVT::v2i32, Expand);
817  setOperationAction(ISD::SELECT,             MVT::v1i64, Expand);
818  setOperationAction(ISD::BITCAST,            MVT::v8i8,  Expand);
819  setOperationAction(ISD::BITCAST,            MVT::v4i16, Expand);
820  setOperationAction(ISD::BITCAST,            MVT::v2i32, Expand);
821  setOperationAction(ISD::BITCAST,            MVT::v1i64, Expand);
822
823  if (!TM.Options.UseSoftFloat && Subtarget->hasSSE1()) {
824    addRegisterClass(MVT::v4f32, &X86::VR128RegClass);
825
826    setOperationAction(ISD::FADD,               MVT::v4f32, Legal);
827    setOperationAction(ISD::FSUB,               MVT::v4f32, Legal);
828    setOperationAction(ISD::FMUL,               MVT::v4f32, Legal);
829    setOperationAction(ISD::FDIV,               MVT::v4f32, Legal);
830    setOperationAction(ISD::FSQRT,              MVT::v4f32, Legal);
831    setOperationAction(ISD::FNEG,               MVT::v4f32, Custom);
832    setOperationAction(ISD::FABS,               MVT::v4f32, Custom);
833    setOperationAction(ISD::LOAD,               MVT::v4f32, Legal);
834    setOperationAction(ISD::BUILD_VECTOR,       MVT::v4f32, Custom);
835    setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4f32, Custom);
836    setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
837    setOperationAction(ISD::SELECT,             MVT::v4f32, Custom);
838  }
839
840  if (!TM.Options.UseSoftFloat && Subtarget->hasSSE2()) {
841    addRegisterClass(MVT::v2f64, &X86::VR128RegClass);
842
843    // FIXME: Unfortunately -soft-float and -no-implicit-float means XMM
844    // registers cannot be used even for integer operations.
845    addRegisterClass(MVT::v16i8, &X86::VR128RegClass);
846    addRegisterClass(MVT::v8i16, &X86::VR128RegClass);
847    addRegisterClass(MVT::v4i32, &X86::VR128RegClass);
848    addRegisterClass(MVT::v2i64, &X86::VR128RegClass);
849
850    setOperationAction(ISD::ADD,                MVT::v16i8, Legal);
851    setOperationAction(ISD::ADD,                MVT::v8i16, Legal);
852    setOperationAction(ISD::ADD,                MVT::v4i32, Legal);
853    setOperationAction(ISD::ADD,                MVT::v2i64, Legal);
854    setOperationAction(ISD::MUL,                MVT::v2i64, Custom);
855    setOperationAction(ISD::SUB,                MVT::v16i8, Legal);
856    setOperationAction(ISD::SUB,                MVT::v8i16, Legal);
857    setOperationAction(ISD::SUB,                MVT::v4i32, Legal);
858    setOperationAction(ISD::SUB,                MVT::v2i64, Legal);
859    setOperationAction(ISD::MUL,                MVT::v8i16, Legal);
860    setOperationAction(ISD::FADD,               MVT::v2f64, Legal);
861    setOperationAction(ISD::FSUB,               MVT::v2f64, Legal);
862    setOperationAction(ISD::FMUL,               MVT::v2f64, Legal);
863    setOperationAction(ISD::FDIV,               MVT::v2f64, Legal);
864    setOperationAction(ISD::FSQRT,              MVT::v2f64, Legal);
865    setOperationAction(ISD::FNEG,               MVT::v2f64, Custom);
866    setOperationAction(ISD::FABS,               MVT::v2f64, Custom);
867
868    setOperationAction(ISD::SETCC,              MVT::v2i64, Custom);
869    setOperationAction(ISD::SETCC,              MVT::v16i8, Custom);
870    setOperationAction(ISD::SETCC,              MVT::v8i16, Custom);
871    setOperationAction(ISD::SETCC,              MVT::v4i32, Custom);
872
873    setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v16i8, Custom);
874    setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i16, Custom);
875    setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
876    setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
877    setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
878
879    // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
880    for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
881      MVT VT = (MVT::SimpleValueType)i;
882      // Do not attempt to custom lower non-power-of-2 vectors
883      if (!isPowerOf2_32(VT.getVectorNumElements()))
884        continue;
885      // Do not attempt to custom lower non-128-bit vectors
886      if (!VT.is128BitVector())
887        continue;
888      setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
889      setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
890      setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
891    }
892
893    setOperationAction(ISD::BUILD_VECTOR,       MVT::v2f64, Custom);
894    setOperationAction(ISD::BUILD_VECTOR,       MVT::v2i64, Custom);
895    setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2f64, Custom);
896    setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2i64, Custom);
897    setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2f64, Custom);
898    setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
899
900    if (Subtarget->is64Bit()) {
901      setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
902      setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
903    }
904
905    // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
906    for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
907      MVT VT = (MVT::SimpleValueType)i;
908
909      // Do not attempt to promote non-128-bit vectors
910      if (!VT.is128BitVector())
911        continue;
912
913      setOperationAction(ISD::AND,    VT, Promote);
914      AddPromotedToType (ISD::AND,    VT, MVT::v2i64);
915      setOperationAction(ISD::OR,     VT, Promote);
916      AddPromotedToType (ISD::OR,     VT, MVT::v2i64);
917      setOperationAction(ISD::XOR,    VT, Promote);
918      AddPromotedToType (ISD::XOR,    VT, MVT::v2i64);
919      setOperationAction(ISD::LOAD,   VT, Promote);
920      AddPromotedToType (ISD::LOAD,   VT, MVT::v2i64);
921      setOperationAction(ISD::SELECT, VT, Promote);
922      AddPromotedToType (ISD::SELECT, VT, MVT::v2i64);
923    }
924
925    setTruncStoreAction(MVT::f64, MVT::f32, Expand);
926
927    // Custom lower v2i64 and v2f64 selects.
928    setOperationAction(ISD::LOAD,               MVT::v2f64, Legal);
929    setOperationAction(ISD::LOAD,               MVT::v2i64, Legal);
930    setOperationAction(ISD::SELECT,             MVT::v2f64, Custom);
931    setOperationAction(ISD::SELECT,             MVT::v2i64, Custom);
932
933    setOperationAction(ISD::FP_TO_SINT,         MVT::v4i32, Legal);
934    setOperationAction(ISD::SINT_TO_FP,         MVT::v4i32, Legal);
935
936    setLoadExtAction(ISD::EXTLOAD,              MVT::v2f32, Legal);
937  }
938
939  if (Subtarget->hasSSE41()) {
940    setOperationAction(ISD::FFLOOR,             MVT::f32,   Legal);
941    setOperationAction(ISD::FCEIL,              MVT::f32,   Legal);
942    setOperationAction(ISD::FTRUNC,             MVT::f32,   Legal);
943    setOperationAction(ISD::FRINT,              MVT::f32,   Legal);
944    setOperationAction(ISD::FNEARBYINT,         MVT::f32,   Legal);
945    setOperationAction(ISD::FFLOOR,             MVT::f64,   Legal);
946    setOperationAction(ISD::FCEIL,              MVT::f64,   Legal);
947    setOperationAction(ISD::FTRUNC,             MVT::f64,   Legal);
948    setOperationAction(ISD::FRINT,              MVT::f64,   Legal);
949    setOperationAction(ISD::FNEARBYINT,         MVT::f64,   Legal);
950
951    setOperationAction(ISD::FFLOOR,             MVT::v4f32, Legal);
952    setOperationAction(ISD::FFLOOR,             MVT::v2f64, Legal);
953
954    // FIXME: Do we need to handle scalar-to-vector here?
955    setOperationAction(ISD::MUL,                MVT::v4i32, Legal);
956
957    setOperationAction(ISD::VSELECT,            MVT::v2f64, Legal);
958    setOperationAction(ISD::VSELECT,            MVT::v2i64, Legal);
959    setOperationAction(ISD::VSELECT,            MVT::v16i8, Legal);
960    setOperationAction(ISD::VSELECT,            MVT::v4i32, Legal);
961    setOperationAction(ISD::VSELECT,            MVT::v4f32, Legal);
962
963    // i8 and i16 vectors are custom , because the source register and source
964    // source memory operand types are not the same width.  f32 vectors are
965    // custom since the immediate controlling the insert encodes additional
966    // information.
967    setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i8, Custom);
968    setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
969    setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
970    setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
971
972    setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
973    setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
974    setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
975    setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
976
977    // FIXME: these should be Legal but thats only for the case where
978    // the index is constant.  For now custom expand to deal with that.
979    if (Subtarget->is64Bit()) {
980      setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
981      setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
982    }
983  }
984
985  if (Subtarget->hasSSE2()) {
986    setOperationAction(ISD::SRL,               MVT::v8i16, Custom);
987    setOperationAction(ISD::SRL,               MVT::v16i8, Custom);
988
989    setOperationAction(ISD::SHL,               MVT::v8i16, Custom);
990    setOperationAction(ISD::SHL,               MVT::v16i8, Custom);
991
992    setOperationAction(ISD::SRA,               MVT::v8i16, Custom);
993    setOperationAction(ISD::SRA,               MVT::v16i8, Custom);
994
995    if (Subtarget->hasAVX2()) {
996      setOperationAction(ISD::SRL,             MVT::v2i64, Legal);
997      setOperationAction(ISD::SRL,             MVT::v4i32, Legal);
998
999      setOperationAction(ISD::SHL,             MVT::v2i64, Legal);
1000      setOperationAction(ISD::SHL,             MVT::v4i32, Legal);
1001
1002      setOperationAction(ISD::SRA,             MVT::v4i32, Legal);
1003    } else {
1004      setOperationAction(ISD::SRL,             MVT::v2i64, Custom);
1005      setOperationAction(ISD::SRL,             MVT::v4i32, Custom);
1006
1007      setOperationAction(ISD::SHL,             MVT::v2i64, Custom);
1008      setOperationAction(ISD::SHL,             MVT::v4i32, Custom);
1009
1010      setOperationAction(ISD::SRA,             MVT::v4i32, Custom);
1011    }
1012  }
1013
1014  if (!TM.Options.UseSoftFloat && Subtarget->hasAVX()) {
1015    addRegisterClass(MVT::v32i8,  &X86::VR256RegClass);
1016    addRegisterClass(MVT::v16i16, &X86::VR256RegClass);
1017    addRegisterClass(MVT::v8i32,  &X86::VR256RegClass);
1018    addRegisterClass(MVT::v8f32,  &X86::VR256RegClass);
1019    addRegisterClass(MVT::v4i64,  &X86::VR256RegClass);
1020    addRegisterClass(MVT::v4f64,  &X86::VR256RegClass);
1021
1022    setOperationAction(ISD::LOAD,               MVT::v8f32, Legal);
1023    setOperationAction(ISD::LOAD,               MVT::v4f64, Legal);
1024    setOperationAction(ISD::LOAD,               MVT::v4i64, Legal);
1025
1026    setOperationAction(ISD::FADD,               MVT::v8f32, Legal);
1027    setOperationAction(ISD::FSUB,               MVT::v8f32, Legal);
1028    setOperationAction(ISD::FMUL,               MVT::v8f32, Legal);
1029    setOperationAction(ISD::FDIV,               MVT::v8f32, Legal);
1030    setOperationAction(ISD::FSQRT,              MVT::v8f32, Legal);
1031    setOperationAction(ISD::FFLOOR,             MVT::v8f32, Legal);
1032    setOperationAction(ISD::FNEG,               MVT::v8f32, Custom);
1033    setOperationAction(ISD::FABS,               MVT::v8f32, Custom);
1034
1035    setOperationAction(ISD::FADD,               MVT::v4f64, Legal);
1036    setOperationAction(ISD::FSUB,               MVT::v4f64, Legal);
1037    setOperationAction(ISD::FMUL,               MVT::v4f64, Legal);
1038    setOperationAction(ISD::FDIV,               MVT::v4f64, Legal);
1039    setOperationAction(ISD::FSQRT,              MVT::v4f64, Legal);
1040    setOperationAction(ISD::FFLOOR,             MVT::v4f64, Legal);
1041    setOperationAction(ISD::FNEG,               MVT::v4f64, Custom);
1042    setOperationAction(ISD::FABS,               MVT::v4f64, Custom);
1043
1044    setOperationAction(ISD::FP_TO_SINT,         MVT::v8i32, Legal);
1045    setOperationAction(ISD::SINT_TO_FP,         MVT::v8i32, Legal);
1046    setOperationAction(ISD::FP_ROUND,           MVT::v4f32, Legal);
1047
1048    setLoadExtAction(ISD::EXTLOAD,              MVT::v4f32, Legal);
1049
1050    setOperationAction(ISD::SRL,               MVT::v16i16, Custom);
1051    setOperationAction(ISD::SRL,               MVT::v32i8, Custom);
1052
1053    setOperationAction(ISD::SHL,               MVT::v16i16, Custom);
1054    setOperationAction(ISD::SHL,               MVT::v32i8, Custom);
1055
1056    setOperationAction(ISD::SRA,               MVT::v16i16, Custom);
1057    setOperationAction(ISD::SRA,               MVT::v32i8, Custom);
1058
1059    setOperationAction(ISD::SETCC,             MVT::v32i8, Custom);
1060    setOperationAction(ISD::SETCC,             MVT::v16i16, Custom);
1061    setOperationAction(ISD::SETCC,             MVT::v8i32, Custom);
1062    setOperationAction(ISD::SETCC,             MVT::v4i64, Custom);
1063
1064    setOperationAction(ISD::SELECT,            MVT::v4f64, Custom);
1065    setOperationAction(ISD::SELECT,            MVT::v4i64, Custom);
1066    setOperationAction(ISD::SELECT,            MVT::v8f32, Custom);
1067
1068    setOperationAction(ISD::VSELECT,           MVT::v4f64, Legal);
1069    setOperationAction(ISD::VSELECT,           MVT::v4i64, Legal);
1070    setOperationAction(ISD::VSELECT,           MVT::v8i32, Legal);
1071    setOperationAction(ISD::VSELECT,           MVT::v8f32, Legal);
1072
1073    if (Subtarget->hasFMA() || Subtarget->hasFMA4()) {
1074      setOperationAction(ISD::FMA,             MVT::v8f32, Custom);
1075      setOperationAction(ISD::FMA,             MVT::v4f64, Custom);
1076      setOperationAction(ISD::FMA,             MVT::v4f32, Custom);
1077      setOperationAction(ISD::FMA,             MVT::v2f64, Custom);
1078      setOperationAction(ISD::FMA,             MVT::f32, Custom);
1079      setOperationAction(ISD::FMA,             MVT::f64, Custom);
1080    }
1081
1082    if (Subtarget->hasAVX2()) {
1083      setOperationAction(ISD::ADD,             MVT::v4i64, Legal);
1084      setOperationAction(ISD::ADD,             MVT::v8i32, Legal);
1085      setOperationAction(ISD::ADD,             MVT::v16i16, Legal);
1086      setOperationAction(ISD::ADD,             MVT::v32i8, Legal);
1087
1088      setOperationAction(ISD::SUB,             MVT::v4i64, Legal);
1089      setOperationAction(ISD::SUB,             MVT::v8i32, Legal);
1090      setOperationAction(ISD::SUB,             MVT::v16i16, Legal);
1091      setOperationAction(ISD::SUB,             MVT::v32i8, Legal);
1092
1093      setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1094      setOperationAction(ISD::MUL,             MVT::v8i32, Legal);
1095      setOperationAction(ISD::MUL,             MVT::v16i16, Legal);
1096      // Don't lower v32i8 because there is no 128-bit byte mul
1097
1098      setOperationAction(ISD::VSELECT,         MVT::v32i8, Legal);
1099
1100      setOperationAction(ISD::SRL,             MVT::v4i64, Legal);
1101      setOperationAction(ISD::SRL,             MVT::v8i32, Legal);
1102
1103      setOperationAction(ISD::SHL,             MVT::v4i64, Legal);
1104      setOperationAction(ISD::SHL,             MVT::v8i32, Legal);
1105
1106      setOperationAction(ISD::SRA,             MVT::v8i32, Legal);
1107    } else {
1108      setOperationAction(ISD::ADD,             MVT::v4i64, Custom);
1109      setOperationAction(ISD::ADD,             MVT::v8i32, Custom);
1110      setOperationAction(ISD::ADD,             MVT::v16i16, Custom);
1111      setOperationAction(ISD::ADD,             MVT::v32i8, Custom);
1112
1113      setOperationAction(ISD::SUB,             MVT::v4i64, Custom);
1114      setOperationAction(ISD::SUB,             MVT::v8i32, Custom);
1115      setOperationAction(ISD::SUB,             MVT::v16i16, Custom);
1116      setOperationAction(ISD::SUB,             MVT::v32i8, Custom);
1117
1118      setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1119      setOperationAction(ISD::MUL,             MVT::v8i32, Custom);
1120      setOperationAction(ISD::MUL,             MVT::v16i16, Custom);
1121      // Don't lower v32i8 because there is no 128-bit byte mul
1122
1123      setOperationAction(ISD::SRL,             MVT::v4i64, Custom);
1124      setOperationAction(ISD::SRL,             MVT::v8i32, Custom);
1125
1126      setOperationAction(ISD::SHL,             MVT::v4i64, Custom);
1127      setOperationAction(ISD::SHL,             MVT::v8i32, Custom);
1128
1129      setOperationAction(ISD::SRA,             MVT::v8i32, Custom);
1130    }
1131
1132    // Custom lower several nodes for 256-bit types.
1133    for (int i = MVT::FIRST_VECTOR_VALUETYPE;
1134             i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
1135      MVT VT = (MVT::SimpleValueType)i;
1136
1137      // Extract subvector is special because the value type
1138      // (result) is 128-bit but the source is 256-bit wide.
1139      if (VT.is128BitVector())
1140        setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1141
1142      // Do not attempt to custom lower other non-256-bit vectors
1143      if (!VT.is256BitVector())
1144        continue;
1145
1146      setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
1147      setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
1148      setOperationAction(ISD::INSERT_VECTOR_ELT,  VT, Custom);
1149      setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1150      setOperationAction(ISD::SCALAR_TO_VECTOR,   VT, Custom);
1151      setOperationAction(ISD::INSERT_SUBVECTOR,   VT, Custom);
1152      setOperationAction(ISD::CONCAT_VECTORS,     VT, Custom);
1153    }
1154
1155    // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
1156    for (int i = MVT::v32i8; i != MVT::v4i64; ++i) {
1157      MVT VT = (MVT::SimpleValueType)i;
1158
1159      // Do not attempt to promote non-256-bit vectors
1160      if (!VT.is256BitVector())
1161        continue;
1162
1163      setOperationAction(ISD::AND,    VT, Promote);
1164      AddPromotedToType (ISD::AND,    VT, MVT::v4i64);
1165      setOperationAction(ISD::OR,     VT, Promote);
1166      AddPromotedToType (ISD::OR,     VT, MVT::v4i64);
1167      setOperationAction(ISD::XOR,    VT, Promote);
1168      AddPromotedToType (ISD::XOR,    VT, MVT::v4i64);
1169      setOperationAction(ISD::LOAD,   VT, Promote);
1170      AddPromotedToType (ISD::LOAD,   VT, MVT::v4i64);
1171      setOperationAction(ISD::SELECT, VT, Promote);
1172      AddPromotedToType (ISD::SELECT, VT, MVT::v4i64);
1173    }
1174  }
1175
1176  // SIGN_EXTEND_INREGs are evaluated by the extend type. Handle the expansion
1177  // of this type with custom code.
1178  for (int VT = MVT::FIRST_VECTOR_VALUETYPE;
1179           VT != MVT::LAST_VECTOR_VALUETYPE; VT++) {
1180    setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,
1181                       Custom);
1182  }
1183
1184  // We want to custom lower some of our intrinsics.
1185  setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1186  setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
1187
1188
1189  // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1190  // handle type legalization for these operations here.
1191  //
1192  // FIXME: We really should do custom legalization for addition and
1193  // subtraction on x86-32 once PR3203 is fixed.  We really can't do much better
1194  // than generic legalization for 64-bit multiplication-with-overflow, though.
1195  for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) {
1196    // Add/Sub/Mul with overflow operations are custom lowered.
1197    MVT VT = IntVTs[i];
1198    setOperationAction(ISD::SADDO, VT, Custom);
1199    setOperationAction(ISD::UADDO, VT, Custom);
1200    setOperationAction(ISD::SSUBO, VT, Custom);
1201    setOperationAction(ISD::USUBO, VT, Custom);
1202    setOperationAction(ISD::SMULO, VT, Custom);
1203    setOperationAction(ISD::UMULO, VT, Custom);
1204  }
1205
1206  // There are no 8-bit 3-address imul/mul instructions
1207  setOperationAction(ISD::SMULO, MVT::i8, Expand);
1208  setOperationAction(ISD::UMULO, MVT::i8, Expand);
1209
1210  if (!Subtarget->is64Bit()) {
1211    // These libcalls are not available in 32-bit.
1212    setLibcallName(RTLIB::SHL_I128, 0);
1213    setLibcallName(RTLIB::SRL_I128, 0);
1214    setLibcallName(RTLIB::SRA_I128, 0);
1215  }
1216
1217  // We have target-specific dag combine patterns for the following nodes:
1218  setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1219  setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1220  setTargetDAGCombine(ISD::VSELECT);
1221  setTargetDAGCombine(ISD::SELECT);
1222  setTargetDAGCombine(ISD::SHL);
1223  setTargetDAGCombine(ISD::SRA);
1224  setTargetDAGCombine(ISD::SRL);
1225  setTargetDAGCombine(ISD::OR);
1226  setTargetDAGCombine(ISD::AND);
1227  setTargetDAGCombine(ISD::ADD);
1228  setTargetDAGCombine(ISD::FADD);
1229  setTargetDAGCombine(ISD::FSUB);
1230  setTargetDAGCombine(ISD::FMA);
1231  setTargetDAGCombine(ISD::SUB);
1232  setTargetDAGCombine(ISD::LOAD);
1233  setTargetDAGCombine(ISD::STORE);
1234  setTargetDAGCombine(ISD::ZERO_EXTEND);
1235  setTargetDAGCombine(ISD::ANY_EXTEND);
1236  setTargetDAGCombine(ISD::SIGN_EXTEND);
1237  setTargetDAGCombine(ISD::TRUNCATE);
1238  setTargetDAGCombine(ISD::UINT_TO_FP);
1239  setTargetDAGCombine(ISD::SINT_TO_FP);
1240  setTargetDAGCombine(ISD::SETCC);
1241  setTargetDAGCombine(ISD::FP_TO_SINT);
1242  if (Subtarget->is64Bit())
1243    setTargetDAGCombine(ISD::MUL);
1244  setTargetDAGCombine(ISD::XOR);
1245
1246  computeRegisterProperties();
1247
1248  // On Darwin, -Os means optimize for size without hurting performance,
1249  // do not reduce the limit.
1250  maxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1251  maxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 16 : 8;
1252  maxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1253  maxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1254  maxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1255  maxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1256  setPrefLoopAlignment(4); // 2^4 bytes.
1257  benefitFromCodePlacementOpt = true;
1258
1259  // Predictable cmov don't hurt on atom because it's in-order.
1260  predictableSelectIsExpensive = !Subtarget->isAtom();
1261
1262  setPrefFunctionAlignment(4); // 2^4 bytes.
1263}
1264
1265
1266EVT X86TargetLowering::getSetCCResultType(EVT VT) const {
1267  if (!VT.isVector()) return MVT::i8;
1268  return VT.changeVectorElementTypeToInteger();
1269}
1270
1271
1272/// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1273/// the desired ByVal argument alignment.
1274static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
1275  if (MaxAlign == 16)
1276    return;
1277  if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1278    if (VTy->getBitWidth() == 128)
1279      MaxAlign = 16;
1280  } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1281    unsigned EltAlign = 0;
1282    getMaxByValAlign(ATy->getElementType(), EltAlign);
1283    if (EltAlign > MaxAlign)
1284      MaxAlign = EltAlign;
1285  } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1286    for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1287      unsigned EltAlign = 0;
1288      getMaxByValAlign(STy->getElementType(i), EltAlign);
1289      if (EltAlign > MaxAlign)
1290        MaxAlign = EltAlign;
1291      if (MaxAlign == 16)
1292        break;
1293    }
1294  }
1295}
1296
1297/// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1298/// function arguments in the caller parameter area. For X86, aggregates
1299/// that contain SSE vectors are placed at 16-byte boundaries while the rest
1300/// are at 4-byte boundaries.
1301unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty) const {
1302  if (Subtarget->is64Bit()) {
1303    // Max of 8 and alignment of type.
1304    unsigned TyAlign = TD->getABITypeAlignment(Ty);
1305    if (TyAlign > 8)
1306      return TyAlign;
1307    return 8;
1308  }
1309
1310  unsigned Align = 4;
1311  if (Subtarget->hasSSE1())
1312    getMaxByValAlign(Ty, Align);
1313  return Align;
1314}
1315
1316/// getOptimalMemOpType - Returns the target specific optimal type for load
1317/// and store operations as a result of memset, memcpy, and memmove
1318/// lowering. If DstAlign is zero that means it's safe to destination
1319/// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1320/// means there isn't a need to check it against alignment requirement,
1321/// probably because the source does not need to be loaded. If
1322/// 'IsZeroVal' is true, that means it's safe to return a
1323/// non-scalar-integer type, e.g. empty string source, constant, or loaded
1324/// from memory. 'MemcpyStrSrc' indicates whether the memcpy source is
1325/// constant so it does not need to be loaded.
1326/// It returns EVT::Other if the type should be determined using generic
1327/// target-independent logic.
1328EVT
1329X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1330                                       unsigned DstAlign, unsigned SrcAlign,
1331                                       bool IsZeroVal,
1332                                       bool MemcpyStrSrc,
1333                                       MachineFunction &MF) const {
1334  // FIXME: This turns off use of xmm stores for memset/memcpy on targets like
1335  // linux.  This is because the stack realignment code can't handle certain
1336  // cases like PR2962.  This should be removed when PR2962 is fixed.
1337  const Function *F = MF.getFunction();
1338  if (IsZeroVal &&
1339      !F->hasFnAttr(Attribute::NoImplicitFloat)) {
1340    if (Size >= 16 &&
1341        (Subtarget->isUnalignedMemAccessFast() ||
1342         ((DstAlign == 0 || DstAlign >= 16) &&
1343          (SrcAlign == 0 || SrcAlign >= 16))) &&
1344        Subtarget->getStackAlignment() >= 16) {
1345      if (Subtarget->getStackAlignment() >= 32) {
1346        if (Subtarget->hasAVX2())
1347          return MVT::v8i32;
1348        if (Subtarget->hasAVX())
1349          return MVT::v8f32;
1350      }
1351      if (Subtarget->hasSSE2())
1352        return MVT::v4i32;
1353      if (Subtarget->hasSSE1())
1354        return MVT::v4f32;
1355    } else if (!MemcpyStrSrc && Size >= 8 &&
1356               !Subtarget->is64Bit() &&
1357               Subtarget->getStackAlignment() >= 8 &&
1358               Subtarget->hasSSE2()) {
1359      // Do not use f64 to lower memcpy if source is string constant. It's
1360      // better to use i32 to avoid the loads.
1361      return MVT::f64;
1362    }
1363  }
1364  if (Subtarget->is64Bit() && Size >= 8)
1365    return MVT::i64;
1366  return MVT::i32;
1367}
1368
1369/// getJumpTableEncoding - Return the entry encoding for a jump table in the
1370/// current function.  The returned value is a member of the
1371/// MachineJumpTableInfo::JTEntryKind enum.
1372unsigned X86TargetLowering::getJumpTableEncoding() const {
1373  // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1374  // symbol.
1375  if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1376      Subtarget->isPICStyleGOT())
1377    return MachineJumpTableInfo::EK_Custom32;
1378
1379  // Otherwise, use the normal jump table encoding heuristics.
1380  return TargetLowering::getJumpTableEncoding();
1381}
1382
1383const MCExpr *
1384X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1385                                             const MachineBasicBlock *MBB,
1386                                             unsigned uid,MCContext &Ctx) const{
1387  assert(getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1388         Subtarget->isPICStyleGOT());
1389  // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1390  // entries.
1391  return MCSymbolRefExpr::Create(MBB->getSymbol(),
1392                                 MCSymbolRefExpr::VK_GOTOFF, Ctx);
1393}
1394
1395/// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
1396/// jumptable.
1397SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1398                                                    SelectionDAG &DAG) const {
1399  if (!Subtarget->is64Bit())
1400    // This doesn't have DebugLoc associated with it, but is not really the
1401    // same as a Register.
1402    return DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), getPointerTy());
1403  return Table;
1404}
1405
1406/// getPICJumpTableRelocBaseExpr - This returns the relocation base for the
1407/// given PIC jumptable, the same as getPICJumpTableRelocBase, but as an
1408/// MCExpr.
1409const MCExpr *X86TargetLowering::
1410getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1411                             MCContext &Ctx) const {
1412  // X86-64 uses RIP relative addressing based on the jump table label.
1413  if (Subtarget->isPICStyleRIPRel())
1414    return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1415
1416  // Otherwise, the reference is relative to the PIC base.
1417  return MCSymbolRefExpr::Create(MF->getPICBaseSymbol(), Ctx);
1418}
1419
1420// FIXME: Why this routine is here? Move to RegInfo!
1421std::pair<const TargetRegisterClass*, uint8_t>
1422X86TargetLowering::findRepresentativeClass(EVT VT) const{
1423  const TargetRegisterClass *RRC = 0;
1424  uint8_t Cost = 1;
1425  switch (VT.getSimpleVT().SimpleTy) {
1426  default:
1427    return TargetLowering::findRepresentativeClass(VT);
1428  case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1429    RRC = Subtarget->is64Bit() ?
1430      (const TargetRegisterClass*)&X86::GR64RegClass :
1431      (const TargetRegisterClass*)&X86::GR32RegClass;
1432    break;
1433  case MVT::x86mmx:
1434    RRC = &X86::VR64RegClass;
1435    break;
1436  case MVT::f32: case MVT::f64:
1437  case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1438  case MVT::v4f32: case MVT::v2f64:
1439  case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
1440  case MVT::v4f64:
1441    RRC = &X86::VR128RegClass;
1442    break;
1443  }
1444  return std::make_pair(RRC, Cost);
1445}
1446
1447bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
1448                                               unsigned &Offset) const {
1449  if (!Subtarget->isTargetLinux())
1450    return false;
1451
1452  if (Subtarget->is64Bit()) {
1453    // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
1454    Offset = 0x28;
1455    if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
1456      AddressSpace = 256;
1457    else
1458      AddressSpace = 257;
1459  } else {
1460    // %gs:0x14 on i386
1461    Offset = 0x14;
1462    AddressSpace = 256;
1463  }
1464  return true;
1465}
1466
1467
1468//===----------------------------------------------------------------------===//
1469//               Return Value Calling Convention Implementation
1470//===----------------------------------------------------------------------===//
1471
1472#include "X86GenCallingConv.inc"
1473
1474bool
1475X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv,
1476                                  MachineFunction &MF, bool isVarArg,
1477                        const SmallVectorImpl<ISD::OutputArg> &Outs,
1478                        LLVMContext &Context) const {
1479  SmallVector<CCValAssign, 16> RVLocs;
1480  CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1481                 RVLocs, Context);
1482  return CCInfo.CheckReturn(Outs, RetCC_X86);
1483}
1484
1485SDValue
1486X86TargetLowering::LowerReturn(SDValue Chain,
1487                               CallingConv::ID CallConv, bool isVarArg,
1488                               const SmallVectorImpl<ISD::OutputArg> &Outs,
1489                               const SmallVectorImpl<SDValue> &OutVals,
1490                               DebugLoc dl, SelectionDAG &DAG) const {
1491  MachineFunction &MF = DAG.getMachineFunction();
1492  X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1493
1494  SmallVector<CCValAssign, 16> RVLocs;
1495  CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1496                 RVLocs, *DAG.getContext());
1497  CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1498
1499  // Add the regs to the liveout set for the function.
1500  MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
1501  for (unsigned i = 0; i != RVLocs.size(); ++i)
1502    if (RVLocs[i].isRegLoc() && !MRI.isLiveOut(RVLocs[i].getLocReg()))
1503      MRI.addLiveOut(RVLocs[i].getLocReg());
1504
1505  SDValue Flag;
1506
1507  SmallVector<SDValue, 6> RetOps;
1508  RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1509  // Operand #1 = Bytes To Pop
1510  RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(),
1511                   MVT::i16));
1512
1513  // Copy the result values into the output registers.
1514  for (unsigned i = 0; i != RVLocs.size(); ++i) {
1515    CCValAssign &VA = RVLocs[i];
1516    assert(VA.isRegLoc() && "Can only return in registers!");
1517    SDValue ValToCopy = OutVals[i];
1518    EVT ValVT = ValToCopy.getValueType();
1519
1520    // Promote values to the appropriate types
1521    if (VA.getLocInfo() == CCValAssign::SExt)
1522      ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
1523    else if (VA.getLocInfo() == CCValAssign::ZExt)
1524      ValToCopy = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), ValToCopy);
1525    else if (VA.getLocInfo() == CCValAssign::AExt)
1526      ValToCopy = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), ValToCopy);
1527    else if (VA.getLocInfo() == CCValAssign::BCvt)
1528      ValToCopy = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), ValToCopy);
1529
1530    // If this is x86-64, and we disabled SSE, we can't return FP values,
1531    // or SSE or MMX vectors.
1532    if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
1533         VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
1534          (Subtarget->is64Bit() && !Subtarget->hasSSE1())) {
1535      report_fatal_error("SSE register return with SSE disabled");
1536    }
1537    // Likewise we can't return F64 values with SSE1 only.  gcc does so, but
1538    // llvm-gcc has never done it right and no one has noticed, so this
1539    // should be OK for now.
1540    if (ValVT == MVT::f64 &&
1541        (Subtarget->is64Bit() && !Subtarget->hasSSE2()))
1542      report_fatal_error("SSE2 register return with SSE2 disabled");
1543
1544    // Returns in ST0/ST1 are handled specially: these are pushed as operands to
1545    // the RET instruction and handled by the FP Stackifier.
1546    if (VA.getLocReg() == X86::ST0 ||
1547        VA.getLocReg() == X86::ST1) {
1548      // If this is a copy from an xmm register to ST(0), use an FPExtend to
1549      // change the value to the FP stack register class.
1550      if (isScalarFPTypeInSSEReg(VA.getValVT()))
1551        ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
1552      RetOps.push_back(ValToCopy);
1553      // Don't emit a copytoreg.
1554      continue;
1555    }
1556
1557    // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
1558    // which is returned in RAX / RDX.
1559    if (Subtarget->is64Bit()) {
1560      if (ValVT == MVT::x86mmx) {
1561        if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1562          ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ValToCopy);
1563          ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
1564                                  ValToCopy);
1565          // If we don't have SSE2 available, convert to v4f32 so the generated
1566          // register is legal.
1567          if (!Subtarget->hasSSE2())
1568            ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32,ValToCopy);
1569        }
1570      }
1571    }
1572
1573    Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
1574    Flag = Chain.getValue(1);
1575  }
1576
1577  // The x86-64 ABI for returning structs by value requires that we copy
1578  // the sret argument into %rax for the return. We saved the argument into
1579  // a virtual register in the entry block, so now we copy the value out
1580  // and into %rax.
1581  if (Subtarget->is64Bit() &&
1582      DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
1583    MachineFunction &MF = DAG.getMachineFunction();
1584    X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1585    unsigned Reg = FuncInfo->getSRetReturnReg();
1586    assert(Reg &&
1587           "SRetReturnReg should have been set in LowerFormalArguments().");
1588    SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
1589
1590    Chain = DAG.getCopyToReg(Chain, dl, X86::RAX, Val, Flag);
1591    Flag = Chain.getValue(1);
1592
1593    // RAX now acts like a return value.
1594    MRI.addLiveOut(X86::RAX);
1595  }
1596
1597  RetOps[0] = Chain;  // Update chain.
1598
1599  // Add the flag if we have it.
1600  if (Flag.getNode())
1601    RetOps.push_back(Flag);
1602
1603  return DAG.getNode(X86ISD::RET_FLAG, dl,
1604                     MVT::Other, &RetOps[0], RetOps.size());
1605}
1606
1607bool X86TargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
1608  if (N->getNumValues() != 1)
1609    return false;
1610  if (!N->hasNUsesOfValue(1, 0))
1611    return false;
1612
1613  SDValue TCChain = Chain;
1614  SDNode *Copy = *N->use_begin();
1615  if (Copy->getOpcode() == ISD::CopyToReg) {
1616    // If the copy has a glue operand, we conservatively assume it isn't safe to
1617    // perform a tail call.
1618    if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
1619      return false;
1620    TCChain = Copy->getOperand(0);
1621  } else if (Copy->getOpcode() != ISD::FP_EXTEND)
1622    return false;
1623
1624  bool HasRet = false;
1625  for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
1626       UI != UE; ++UI) {
1627    if (UI->getOpcode() != X86ISD::RET_FLAG)
1628      return false;
1629    HasRet = true;
1630  }
1631
1632  if (!HasRet)
1633    return false;
1634
1635  Chain = TCChain;
1636  return true;
1637}
1638
1639EVT
1640X86TargetLowering::getTypeForExtArgOrReturn(LLVMContext &Context, EVT VT,
1641                                            ISD::NodeType ExtendKind) const {
1642  MVT ReturnMVT;
1643  // TODO: Is this also valid on 32-bit?
1644  if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
1645    ReturnMVT = MVT::i8;
1646  else
1647    ReturnMVT = MVT::i32;
1648
1649  EVT MinVT = getRegisterType(Context, ReturnMVT);
1650  return VT.bitsLT(MinVT) ? MinVT : VT;
1651}
1652
1653/// LowerCallResult - Lower the result values of a call into the
1654/// appropriate copies out of appropriate physical registers.
1655///
1656SDValue
1657X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1658                                   CallingConv::ID CallConv, bool isVarArg,
1659                                   const SmallVectorImpl<ISD::InputArg> &Ins,
1660                                   DebugLoc dl, SelectionDAG &DAG,
1661                                   SmallVectorImpl<SDValue> &InVals) const {
1662
1663  // Assign locations to each value returned by this call.
1664  SmallVector<CCValAssign, 16> RVLocs;
1665  bool Is64Bit = Subtarget->is64Bit();
1666  CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1667                 getTargetMachine(), RVLocs, *DAG.getContext());
1668  CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
1669
1670  // Copy all of the result registers out of their specified physreg.
1671  for (unsigned i = 0; i != RVLocs.size(); ++i) {
1672    CCValAssign &VA = RVLocs[i];
1673    EVT CopyVT = VA.getValVT();
1674
1675    // If this is x86-64, and we disabled SSE, we can't return FP values
1676    if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
1677        ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
1678      report_fatal_error("SSE register return with SSE disabled");
1679    }
1680
1681    SDValue Val;
1682
1683    // If this is a call to a function that returns an fp value on the floating
1684    // point stack, we must guarantee the value is popped from the stack, so
1685    // a CopyFromReg is not good enough - the copy instruction may be eliminated
1686    // if the return value is not used. We use the FpPOP_RETVAL instruction
1687    // instead.
1688    if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1) {
1689      // If we prefer to use the value in xmm registers, copy it out as f80 and
1690      // use a truncate to move it from fp stack reg to xmm reg.
1691      if (isScalarFPTypeInSSEReg(VA.getValVT())) CopyVT = MVT::f80;
1692      SDValue Ops[] = { Chain, InFlag };
1693      Chain = SDValue(DAG.getMachineNode(X86::FpPOP_RETVAL, dl, CopyVT,
1694                                         MVT::Other, MVT::Glue, Ops, 2), 1);
1695      Val = Chain.getValue(0);
1696
1697      // Round the f80 to the right size, which also moves it to the appropriate
1698      // xmm register.
1699      if (CopyVT != VA.getValVT())
1700        Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
1701                          // This truncation won't change the value.
1702                          DAG.getIntPtrConstant(1));
1703    } else {
1704      Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1705                                 CopyVT, InFlag).getValue(1);
1706      Val = Chain.getValue(0);
1707    }
1708    InFlag = Chain.getValue(2);
1709    InVals.push_back(Val);
1710  }
1711
1712  return Chain;
1713}
1714
1715
1716//===----------------------------------------------------------------------===//
1717//                C & StdCall & Fast Calling Convention implementation
1718//===----------------------------------------------------------------------===//
1719//  StdCall calling convention seems to be standard for many Windows' API
1720//  routines and around. It differs from C calling convention just a little:
1721//  callee should clean up the stack, not caller. Symbols should be also
1722//  decorated in some fancy way :) It doesn't support any vector arguments.
1723//  For info on fast calling convention see Fast Calling Convention (tail call)
1724//  implementation LowerX86_32FastCCCallTo.
1725
1726/// CallIsStructReturn - Determines whether a call uses struct return
1727/// semantics.
1728enum StructReturnType {
1729  NotStructReturn,
1730  RegStructReturn,
1731  StackStructReturn
1732};
1733static StructReturnType
1734callIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
1735  if (Outs.empty())
1736    return NotStructReturn;
1737
1738  const ISD::ArgFlagsTy &Flags = Outs[0].Flags;
1739  if (!Flags.isSRet())
1740    return NotStructReturn;
1741  if (Flags.isInReg())
1742    return RegStructReturn;
1743  return StackStructReturn;
1744}
1745
1746/// ArgsAreStructReturn - Determines whether a function uses struct
1747/// return semantics.
1748static StructReturnType
1749argsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
1750  if (Ins.empty())
1751    return NotStructReturn;
1752
1753  const ISD::ArgFlagsTy &Flags = Ins[0].Flags;
1754  if (!Flags.isSRet())
1755    return NotStructReturn;
1756  if (Flags.isInReg())
1757    return RegStructReturn;
1758  return StackStructReturn;
1759}
1760
1761/// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
1762/// by "Src" to address "Dst" with size and alignment information specified by
1763/// the specific parameter attribute. The copy will be passed as a byval
1764/// function parameter.
1765static SDValue
1766CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
1767                          ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
1768                          DebugLoc dl) {
1769  SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
1770
1771  return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
1772                       /*isVolatile*/false, /*AlwaysInline=*/true,
1773                       MachinePointerInfo(), MachinePointerInfo());
1774}
1775
1776/// IsTailCallConvention - Return true if the calling convention is one that
1777/// supports tail call optimization.
1778static bool IsTailCallConvention(CallingConv::ID CC) {
1779  return (CC == CallingConv::Fast || CC == CallingConv::GHC);
1780}
1781
1782bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
1783  if (!CI->isTailCall() || getTargetMachine().Options.DisableTailCalls)
1784    return false;
1785
1786  CallSite CS(CI);
1787  CallingConv::ID CalleeCC = CS.getCallingConv();
1788  if (!IsTailCallConvention(CalleeCC) && CalleeCC != CallingConv::C)
1789    return false;
1790
1791  return true;
1792}
1793
1794/// FuncIsMadeTailCallSafe - Return true if the function is being made into
1795/// a tailcall target by changing its ABI.
1796static bool FuncIsMadeTailCallSafe(CallingConv::ID CC,
1797                                   bool GuaranteedTailCallOpt) {
1798  return GuaranteedTailCallOpt && IsTailCallConvention(CC);
1799}
1800
1801SDValue
1802X86TargetLowering::LowerMemArgument(SDValue Chain,
1803                                    CallingConv::ID CallConv,
1804                                    const SmallVectorImpl<ISD::InputArg> &Ins,
1805                                    DebugLoc dl, SelectionDAG &DAG,
1806                                    const CCValAssign &VA,
1807                                    MachineFrameInfo *MFI,
1808                                    unsigned i) const {
1809  // Create the nodes corresponding to a load from this parameter slot.
1810  ISD::ArgFlagsTy Flags = Ins[i].Flags;
1811  bool AlwaysUseMutable = FuncIsMadeTailCallSafe(CallConv,
1812                              getTargetMachine().Options.GuaranteedTailCallOpt);
1813  bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
1814  EVT ValVT;
1815
1816  // If value is passed by pointer we have address passed instead of the value
1817  // itself.
1818  if (VA.getLocInfo() == CCValAssign::Indirect)
1819    ValVT = VA.getLocVT();
1820  else
1821    ValVT = VA.getValVT();
1822
1823  // FIXME: For now, all byval parameter objects are marked mutable. This can be
1824  // changed with more analysis.
1825  // In case of tail call optimization mark all arguments mutable. Since they
1826  // could be overwritten by lowering of arguments in case of a tail call.
1827  if (Flags.isByVal()) {
1828    unsigned Bytes = Flags.getByValSize();
1829    if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
1830    int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
1831    return DAG.getFrameIndex(FI, getPointerTy());
1832  } else {
1833    int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
1834                                    VA.getLocMemOffset(), isImmutable);
1835    SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
1836    return DAG.getLoad(ValVT, dl, Chain, FIN,
1837                       MachinePointerInfo::getFixedStack(FI),
1838                       false, false, false, 0);
1839  }
1840}
1841
1842SDValue
1843X86TargetLowering::LowerFormalArguments(SDValue Chain,
1844                                        CallingConv::ID CallConv,
1845                                        bool isVarArg,
1846                                      const SmallVectorImpl<ISD::InputArg> &Ins,
1847                                        DebugLoc dl,
1848                                        SelectionDAG &DAG,
1849                                        SmallVectorImpl<SDValue> &InVals)
1850                                          const {
1851  MachineFunction &MF = DAG.getMachineFunction();
1852  X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1853
1854  const Function* Fn = MF.getFunction();
1855  if (Fn->hasExternalLinkage() &&
1856      Subtarget->isTargetCygMing() &&
1857      Fn->getName() == "main")
1858    FuncInfo->setForceFramePointer(true);
1859
1860  MachineFrameInfo *MFI = MF.getFrameInfo();
1861  bool Is64Bit = Subtarget->is64Bit();
1862  bool IsWindows = Subtarget->isTargetWindows();
1863  bool IsWin64 = Subtarget->isTargetWin64();
1864
1865  assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
1866         "Var args not supported with calling convention fastcc or ghc");
1867
1868  // Assign locations to all of the incoming arguments.
1869  SmallVector<CCValAssign, 16> ArgLocs;
1870  CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1871                 ArgLocs, *DAG.getContext());
1872
1873  // Allocate shadow area for Win64
1874  if (IsWin64) {
1875    CCInfo.AllocateStack(32, 8);
1876  }
1877
1878  CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
1879
1880  unsigned LastVal = ~0U;
1881  SDValue ArgValue;
1882  for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1883    CCValAssign &VA = ArgLocs[i];
1884    // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
1885    // places.
1886    assert(VA.getValNo() != LastVal &&
1887           "Don't support value assigned to multiple locs yet");
1888    (void)LastVal;
1889    LastVal = VA.getValNo();
1890
1891    if (VA.isRegLoc()) {
1892      EVT RegVT = VA.getLocVT();
1893      const TargetRegisterClass *RC;
1894      if (RegVT == MVT::i32)
1895        RC = &X86::GR32RegClass;
1896      else if (Is64Bit && RegVT == MVT::i64)
1897        RC = &X86::GR64RegClass;
1898      else if (RegVT == MVT::f32)
1899        RC = &X86::FR32RegClass;
1900      else if (RegVT == MVT::f64)
1901        RC = &X86::FR64RegClass;
1902      else if (RegVT.is256BitVector())
1903        RC = &X86::VR256RegClass;
1904      else if (RegVT.is128BitVector())
1905        RC = &X86::VR128RegClass;
1906      else if (RegVT == MVT::x86mmx)
1907        RC = &X86::VR64RegClass;
1908      else
1909        llvm_unreachable("Unknown argument type!");
1910
1911      unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
1912      ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
1913
1914      // If this is an 8 or 16-bit value, it is really passed promoted to 32
1915      // bits.  Insert an assert[sz]ext to capture this, then truncate to the
1916      // right size.
1917      if (VA.getLocInfo() == CCValAssign::SExt)
1918        ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
1919                               DAG.getValueType(VA.getValVT()));
1920      else if (VA.getLocInfo() == CCValAssign::ZExt)
1921        ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
1922                               DAG.getValueType(VA.getValVT()));
1923      else if (VA.getLocInfo() == CCValAssign::BCvt)
1924        ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
1925
1926      if (VA.isExtInLoc()) {
1927        // Handle MMX values passed in XMM regs.
1928        if (RegVT.isVector()) {
1929          ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(),
1930                                 ArgValue);
1931        } else
1932          ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
1933      }
1934    } else {
1935      assert(VA.isMemLoc());
1936      ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
1937    }
1938
1939    // If value is passed via pointer - do a load.
1940    if (VA.getLocInfo() == CCValAssign::Indirect)
1941      ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
1942                             MachinePointerInfo(), false, false, false, 0);
1943
1944    InVals.push_back(ArgValue);
1945  }
1946
1947  // The x86-64 ABI for returning structs by value requires that we copy
1948  // the sret argument into %rax for the return. Save the argument into
1949  // a virtual register so that we can access it from the return points.
1950  if (Is64Bit && MF.getFunction()->hasStructRetAttr()) {
1951    X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1952    unsigned Reg = FuncInfo->getSRetReturnReg();
1953    if (!Reg) {
1954      Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(MVT::i64));
1955      FuncInfo->setSRetReturnReg(Reg);
1956    }
1957    SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[0]);
1958    Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
1959  }
1960
1961  unsigned StackSize = CCInfo.getNextStackOffset();
1962  // Align stack specially for tail calls.
1963  if (FuncIsMadeTailCallSafe(CallConv,
1964                             MF.getTarget().Options.GuaranteedTailCallOpt))
1965    StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
1966
1967  // If the function takes variable number of arguments, make a frame index for
1968  // the start of the first vararg value... for expansion of llvm.va_start.
1969  if (isVarArg) {
1970    if (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
1971                    CallConv != CallingConv::X86_ThisCall)) {
1972      FuncInfo->setVarArgsFrameIndex(MFI->CreateFixedObject(1, StackSize,true));
1973    }
1974    if (Is64Bit) {
1975      unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
1976
1977      // FIXME: We should really autogenerate these arrays
1978      static const uint16_t GPR64ArgRegsWin64[] = {
1979        X86::RCX, X86::RDX, X86::R8,  X86::R9
1980      };
1981      static const uint16_t GPR64ArgRegs64Bit[] = {
1982        X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
1983      };
1984      static const uint16_t XMMArgRegs64Bit[] = {
1985        X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
1986        X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
1987      };
1988      const uint16_t *GPR64ArgRegs;
1989      unsigned NumXMMRegs = 0;
1990
1991      if (IsWin64) {
1992        // The XMM registers which might contain var arg parameters are shadowed
1993        // in their paired GPR.  So we only need to save the GPR to their home
1994        // slots.
1995        TotalNumIntRegs = 4;
1996        GPR64ArgRegs = GPR64ArgRegsWin64;
1997      } else {
1998        TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
1999        GPR64ArgRegs = GPR64ArgRegs64Bit;
2000
2001        NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs64Bit,
2002                                                TotalNumXMMRegs);
2003      }
2004      unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
2005                                                       TotalNumIntRegs);
2006
2007      bool NoImplicitFloatOps = Fn->hasFnAttr(Attribute::NoImplicitFloat);
2008      assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
2009             "SSE register cannot be used when SSE is disabled!");
2010      assert(!(NumXMMRegs && MF.getTarget().Options.UseSoftFloat &&
2011               NoImplicitFloatOps) &&
2012             "SSE register cannot be used when SSE is disabled!");
2013      if (MF.getTarget().Options.UseSoftFloat || NoImplicitFloatOps ||
2014          !Subtarget->hasSSE1())
2015        // Kernel mode asks for SSE to be disabled, so don't push them
2016        // on the stack.
2017        TotalNumXMMRegs = 0;
2018
2019      if (IsWin64) {
2020        const TargetFrameLowering &TFI = *getTargetMachine().getFrameLowering();
2021        // Get to the caller-allocated home save location.  Add 8 to account
2022        // for the return address.
2023        int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2024        FuncInfo->setRegSaveFrameIndex(
2025          MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
2026        // Fixup to set vararg frame on shadow area (4 x i64).
2027        if (NumIntRegs < 4)
2028          FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
2029      } else {
2030        // For X86-64, if there are vararg parameters that are passed via
2031        // registers, then we must store them to their spots on the stack so
2032        // they may be loaded by deferencing the result of va_next.
2033        FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
2034        FuncInfo->setVarArgsFPOffset(TotalNumIntRegs * 8 + NumXMMRegs * 16);
2035        FuncInfo->setRegSaveFrameIndex(
2036          MFI->CreateStackObject(TotalNumIntRegs * 8 + TotalNumXMMRegs * 16, 16,
2037                               false));
2038      }
2039
2040      // Store the integer parameter registers.
2041      SmallVector<SDValue, 8> MemOps;
2042      SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
2043                                        getPointerTy());
2044      unsigned Offset = FuncInfo->getVarArgsGPOffset();
2045      for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
2046        SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
2047                                  DAG.getIntPtrConstant(Offset));
2048        unsigned VReg = MF.addLiveIn(GPR64ArgRegs[NumIntRegs],
2049                                     &X86::GR64RegClass);
2050        SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
2051        SDValue Store =
2052          DAG.getStore(Val.getValue(1), dl, Val, FIN,
2053                       MachinePointerInfo::getFixedStack(
2054                         FuncInfo->getRegSaveFrameIndex(), Offset),
2055                       false, false, 0);
2056        MemOps.push_back(Store);
2057        Offset += 8;
2058      }
2059
2060      if (TotalNumXMMRegs != 0 && NumXMMRegs != TotalNumXMMRegs) {
2061        // Now store the XMM (fp + vector) parameter registers.
2062        SmallVector<SDValue, 11> SaveXMMOps;
2063        SaveXMMOps.push_back(Chain);
2064
2065        unsigned AL = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2066        SDValue ALVal = DAG.getCopyFromReg(DAG.getEntryNode(), dl, AL, MVT::i8);
2067        SaveXMMOps.push_back(ALVal);
2068
2069        SaveXMMOps.push_back(DAG.getIntPtrConstant(
2070                               FuncInfo->getRegSaveFrameIndex()));
2071        SaveXMMOps.push_back(DAG.getIntPtrConstant(
2072                               FuncInfo->getVarArgsFPOffset()));
2073
2074        for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
2075          unsigned VReg = MF.addLiveIn(XMMArgRegs64Bit[NumXMMRegs],
2076                                       &X86::VR128RegClass);
2077          SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::v4f32);
2078          SaveXMMOps.push_back(Val);
2079        }
2080        MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
2081                                     MVT::Other,
2082                                     &SaveXMMOps[0], SaveXMMOps.size()));
2083      }
2084
2085      if (!MemOps.empty())
2086        Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2087                            &MemOps[0], MemOps.size());
2088    }
2089  }
2090
2091  // Some CCs need callee pop.
2092  if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2093                       MF.getTarget().Options.GuaranteedTailCallOpt)) {
2094    FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
2095  } else {
2096    FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
2097    // If this is an sret function, the return should pop the hidden pointer.
2098    if (!Is64Bit && !IsTailCallConvention(CallConv) && !IsWindows &&
2099        argsAreStructReturn(Ins) == StackStructReturn)
2100      FuncInfo->setBytesToPopOnReturn(4);
2101  }
2102
2103  if (!Is64Bit) {
2104    // RegSaveFrameIndex is X86-64 only.
2105    FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
2106    if (CallConv == CallingConv::X86_FastCall ||
2107        CallConv == CallingConv::X86_ThisCall)
2108      // fastcc functions can't have varargs.
2109      FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
2110  }
2111
2112  FuncInfo->setArgumentStackSize(StackSize);
2113
2114  return Chain;
2115}
2116
2117SDValue
2118X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
2119                                    SDValue StackPtr, SDValue Arg,
2120                                    DebugLoc dl, SelectionDAG &DAG,
2121                                    const CCValAssign &VA,
2122                                    ISD::ArgFlagsTy Flags) const {
2123  unsigned LocMemOffset = VA.getLocMemOffset();
2124  SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
2125  PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
2126  if (Flags.isByVal())
2127    return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
2128
2129  return DAG.getStore(Chain, dl, Arg, PtrOff,
2130                      MachinePointerInfo::getStack(LocMemOffset),
2131                      false, false, 0);
2132}
2133
2134/// EmitTailCallLoadRetAddr - Emit a load of return address if tail call
2135/// optimization is performed and it is required.
2136SDValue
2137X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
2138                                           SDValue &OutRetAddr, SDValue Chain,
2139                                           bool IsTailCall, bool Is64Bit,
2140                                           int FPDiff, DebugLoc dl) const {
2141  // Adjust the Return address stack slot.
2142  EVT VT = getPointerTy();
2143  OutRetAddr = getReturnAddressFrameIndex(DAG);
2144
2145  // Load the "old" Return address.
2146  OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
2147                           false, false, false, 0);
2148  return SDValue(OutRetAddr.getNode(), 1);
2149}
2150
2151/// EmitTailCallStoreRetAddr - Emit a store of the return address if tail call
2152/// optimization is performed and it is required (FPDiff!=0).
2153static SDValue
2154EmitTailCallStoreRetAddr(SelectionDAG & DAG, MachineFunction &MF,
2155                         SDValue Chain, SDValue RetAddrFrIdx,
2156                         bool Is64Bit, int FPDiff, DebugLoc dl) {
2157  // Store the return address to the appropriate stack slot.
2158  if (!FPDiff) return Chain;
2159  // Calculate the new stack slot for the return address.
2160  int SlotSize = Is64Bit ? 8 : 4;
2161  int NewReturnAddrFI =
2162    MF.getFrameInfo()->CreateFixedObject(SlotSize, FPDiff-SlotSize, false);
2163  EVT VT = Is64Bit ? MVT::i64 : MVT::i32;
2164  SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, VT);
2165  Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
2166                       MachinePointerInfo::getFixedStack(NewReturnAddrFI),
2167                       false, false, 0);
2168  return Chain;
2169}
2170
2171SDValue
2172X86TargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2173                             SmallVectorImpl<SDValue> &InVals) const {
2174  SelectionDAG &DAG                     = CLI.DAG;
2175  DebugLoc &dl                          = CLI.DL;
2176  SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs;
2177  SmallVector<SDValue, 32> &OutVals     = CLI.OutVals;
2178  SmallVector<ISD::InputArg, 32> &Ins   = CLI.Ins;
2179  SDValue Chain                         = CLI.Chain;
2180  SDValue Callee                        = CLI.Callee;
2181  CallingConv::ID CallConv              = CLI.CallConv;
2182  bool &isTailCall                      = CLI.IsTailCall;
2183  bool isVarArg                         = CLI.IsVarArg;
2184
2185  MachineFunction &MF = DAG.getMachineFunction();
2186  bool Is64Bit        = Subtarget->is64Bit();
2187  bool IsWin64        = Subtarget->isTargetWin64();
2188  bool IsWindows      = Subtarget->isTargetWindows();
2189  StructReturnType SR = callIsStructReturn(Outs);
2190  bool IsSibcall      = false;
2191
2192  if (MF.getTarget().Options.DisableTailCalls)
2193    isTailCall = false;
2194
2195  if (isTailCall) {
2196    // Check if it's really possible to do a tail call.
2197    isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
2198                    isVarArg, SR != NotStructReturn,
2199                    MF.getFunction()->hasStructRetAttr(),
2200                    Outs, OutVals, Ins, DAG);
2201
2202    // Sibcalls are automatically detected tailcalls which do not require
2203    // ABI changes.
2204    if (!MF.getTarget().Options.GuaranteedTailCallOpt && isTailCall)
2205      IsSibcall = true;
2206
2207    if (isTailCall)
2208      ++NumTailCalls;
2209  }
2210
2211  assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2212         "Var args not supported with calling convention fastcc or ghc");
2213
2214  // Analyze operands of the call, assigning locations to each operand.
2215  SmallVector<CCValAssign, 16> ArgLocs;
2216  CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
2217                 ArgLocs, *DAG.getContext());
2218
2219  // Allocate shadow area for Win64
2220  if (IsWin64) {
2221    CCInfo.AllocateStack(32, 8);
2222  }
2223
2224  CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2225
2226  // Get a count of how many bytes are to be pushed on the stack.
2227  unsigned NumBytes = CCInfo.getNextStackOffset();
2228  if (IsSibcall)
2229    // This is a sibcall. The memory operands are available in caller's
2230    // own caller's stack.
2231    NumBytes = 0;
2232  else if (getTargetMachine().Options.GuaranteedTailCallOpt &&
2233           IsTailCallConvention(CallConv))
2234    NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
2235
2236  int FPDiff = 0;
2237  if (isTailCall && !IsSibcall) {
2238    // Lower arguments at fp - stackoffset + fpdiff.
2239    unsigned NumBytesCallerPushed =
2240      MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn();
2241    FPDiff = NumBytesCallerPushed - NumBytes;
2242
2243    // Set the delta of movement of the returnaddr stackslot.
2244    // But only set if delta is greater than previous delta.
2245    if (FPDiff < (MF.getInfo<X86MachineFunctionInfo>()->getTCReturnAddrDelta()))
2246      MF.getInfo<X86MachineFunctionInfo>()->setTCReturnAddrDelta(FPDiff);
2247  }
2248
2249  if (!IsSibcall)
2250    Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true));
2251
2252  SDValue RetAddrFrIdx;
2253  // Load return address for tail calls.
2254  if (isTailCall && FPDiff)
2255    Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
2256                                    Is64Bit, FPDiff, dl);
2257
2258  SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2259  SmallVector<SDValue, 8> MemOpChains;
2260  SDValue StackPtr;
2261
2262  // Walk the register/memloc assignments, inserting copies/loads.  In the case
2263  // of tail call optimization arguments are handle later.
2264  for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2265    CCValAssign &VA = ArgLocs[i];
2266    EVT RegVT = VA.getLocVT();
2267    SDValue Arg = OutVals[i];
2268    ISD::ArgFlagsTy Flags = Outs[i].Flags;
2269    bool isByVal = Flags.isByVal();
2270
2271    // Promote the value if needed.
2272    switch (VA.getLocInfo()) {
2273    default: llvm_unreachable("Unknown loc info!");
2274    case CCValAssign::Full: break;
2275    case CCValAssign::SExt:
2276      Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
2277      break;
2278    case CCValAssign::ZExt:
2279      Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
2280      break;
2281    case CCValAssign::AExt:
2282      if (RegVT.is128BitVector()) {
2283        // Special case: passing MMX values in XMM registers.
2284        Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
2285        Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
2286        Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
2287      } else
2288        Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
2289      break;
2290    case CCValAssign::BCvt:
2291      Arg = DAG.getNode(ISD::BITCAST, dl, RegVT, Arg);
2292      break;
2293    case CCValAssign::Indirect: {
2294      // Store the argument.
2295      SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
2296      int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
2297      Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
2298                           MachinePointerInfo::getFixedStack(FI),
2299                           false, false, 0);
2300      Arg = SpillSlot;
2301      break;
2302    }
2303    }
2304
2305    if (VA.isRegLoc()) {
2306      RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2307      if (isVarArg && IsWin64) {
2308        // Win64 ABI requires argument XMM reg to be copied to the corresponding
2309        // shadow reg if callee is a varargs function.
2310        unsigned ShadowReg = 0;
2311        switch (VA.getLocReg()) {
2312        case X86::XMM0: ShadowReg = X86::RCX; break;
2313        case X86::XMM1: ShadowReg = X86::RDX; break;
2314        case X86::XMM2: ShadowReg = X86::R8; break;
2315        case X86::XMM3: ShadowReg = X86::R9; break;
2316        }
2317        if (ShadowReg)
2318          RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
2319      }
2320    } else if (!IsSibcall && (!isTailCall || isByVal)) {
2321      assert(VA.isMemLoc());
2322      if (StackPtr.getNode() == 0)
2323        StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr, getPointerTy());
2324      MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
2325                                             dl, DAG, VA, Flags));
2326    }
2327  }
2328
2329  if (!MemOpChains.empty())
2330    Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2331                        &MemOpChains[0], MemOpChains.size());
2332
2333  if (Subtarget->isPICStyleGOT()) {
2334    // ELF / PIC requires GOT in the EBX register before function calls via PLT
2335    // GOT pointer.
2336    if (!isTailCall) {
2337      RegsToPass.push_back(std::make_pair(unsigned(X86::EBX),
2338               DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), getPointerTy())));
2339    } else {
2340      // If we are tail calling and generating PIC/GOT style code load the
2341      // address of the callee into ECX. The value in ecx is used as target of
2342      // the tail jump. This is done to circumvent the ebx/callee-saved problem
2343      // for tail calls on PIC/GOT architectures. Normally we would just put the
2344      // address of GOT into ebx and then call target@PLT. But for tail calls
2345      // ebx would be restored (since ebx is callee saved) before jumping to the
2346      // target@PLT.
2347
2348      // Note: The actual moving to ECX is done further down.
2349      GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2350      if (G && !G->getGlobal()->hasHiddenVisibility() &&
2351          !G->getGlobal()->hasProtectedVisibility())
2352        Callee = LowerGlobalAddress(Callee, DAG);
2353      else if (isa<ExternalSymbolSDNode>(Callee))
2354        Callee = LowerExternalSymbol(Callee, DAG);
2355    }
2356  }
2357
2358  if (Is64Bit && isVarArg && !IsWin64) {
2359    // From AMD64 ABI document:
2360    // For calls that may call functions that use varargs or stdargs
2361    // (prototype-less calls or calls to functions containing ellipsis (...) in
2362    // the declaration) %al is used as hidden argument to specify the number
2363    // of SSE registers used. The contents of %al do not need to match exactly
2364    // the number of registers, but must be an ubound on the number of SSE
2365    // registers used and is in the range 0 - 8 inclusive.
2366
2367    // Count the number of XMM registers allocated.
2368    static const uint16_t XMMArgRegs[] = {
2369      X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2370      X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2371    };
2372    unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
2373    assert((Subtarget->hasSSE1() || !NumXMMRegs)
2374           && "SSE registers cannot be used when SSE is disabled");
2375
2376    RegsToPass.push_back(std::make_pair(unsigned(X86::AL),
2377                                        DAG.getConstant(NumXMMRegs, MVT::i8)));
2378  }
2379
2380  // For tail calls lower the arguments to the 'real' stack slot.
2381  if (isTailCall) {
2382    // Force all the incoming stack arguments to be loaded from the stack
2383    // before any new outgoing arguments are stored to the stack, because the
2384    // outgoing stack slots may alias the incoming argument stack slots, and
2385    // the alias isn't otherwise explicit. This is slightly more conservative
2386    // than necessary, because it means that each store effectively depends
2387    // on every argument instead of just those arguments it would clobber.
2388    SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
2389
2390    SmallVector<SDValue, 8> MemOpChains2;
2391    SDValue FIN;
2392    int FI = 0;
2393    if (getTargetMachine().Options.GuaranteedTailCallOpt) {
2394      for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2395        CCValAssign &VA = ArgLocs[i];
2396        if (VA.isRegLoc())
2397          continue;
2398        assert(VA.isMemLoc());
2399        SDValue Arg = OutVals[i];
2400        ISD::ArgFlagsTy Flags = Outs[i].Flags;
2401        // Create frame index.
2402        int32_t Offset = VA.getLocMemOffset()+FPDiff;
2403        uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
2404        FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
2405        FIN = DAG.getFrameIndex(FI, getPointerTy());
2406
2407        if (Flags.isByVal()) {
2408          // Copy relative to framepointer.
2409          SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
2410          if (StackPtr.getNode() == 0)
2411            StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr,
2412                                          getPointerTy());
2413          Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
2414
2415          MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
2416                                                           ArgChain,
2417                                                           Flags, DAG, dl));
2418        } else {
2419          // Store relative to framepointer.
2420          MemOpChains2.push_back(
2421            DAG.getStore(ArgChain, dl, Arg, FIN,
2422                         MachinePointerInfo::getFixedStack(FI),
2423                         false, false, 0));
2424        }
2425      }
2426    }
2427
2428    if (!MemOpChains2.empty())
2429      Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2430                          &MemOpChains2[0], MemOpChains2.size());
2431
2432    // Store the return address to the appropriate stack slot.
2433    Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx, Is64Bit,
2434                                     FPDiff, dl);
2435  }
2436
2437  // Build a sequence of copy-to-reg nodes chained together with token chain
2438  // and flag operands which copy the outgoing args into registers.
2439  SDValue InFlag;
2440  for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2441    Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2442                             RegsToPass[i].second, InFlag);
2443    InFlag = Chain.getValue(1);
2444  }
2445
2446  if (getTargetMachine().getCodeModel() == CodeModel::Large) {
2447    assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
2448    // In the 64-bit large code model, we have to make all calls
2449    // through a register, since the call instruction's 32-bit
2450    // pc-relative offset may not be large enough to hold the whole
2451    // address.
2452  } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2453    // If the callee is a GlobalAddress node (quite common, every direct call
2454    // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
2455    // it.
2456
2457    // We should use extra load for direct calls to dllimported functions in
2458    // non-JIT mode.
2459    const GlobalValue *GV = G->getGlobal();
2460    if (!GV->hasDLLImportLinkage()) {
2461      unsigned char OpFlags = 0;
2462      bool ExtraLoad = false;
2463      unsigned WrapperKind = ISD::DELETED_NODE;
2464
2465      // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
2466      // external symbols most go through the PLT in PIC mode.  If the symbol
2467      // has hidden or protected visibility, or if it is static or local, then
2468      // we don't need to use the PLT - we can directly call it.
2469      if (Subtarget->isTargetELF() &&
2470          getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
2471          GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
2472        OpFlags = X86II::MO_PLT;
2473      } else if (Subtarget->isPICStyleStubAny() &&
2474                 (GV->isDeclaration() || GV->isWeakForLinker()) &&
2475                 (!Subtarget->getTargetTriple().isMacOSX() ||
2476                  Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2477        // PC-relative references to external symbols should go through $stub,
2478        // unless we're building with the leopard linker or later, which
2479        // automatically synthesizes these stubs.
2480        OpFlags = X86II::MO_DARWIN_STUB;
2481      } else if (Subtarget->isPICStyleRIPRel() &&
2482                 isa<Function>(GV) &&
2483                 cast<Function>(GV)->hasFnAttr(Attribute::NonLazyBind)) {
2484        // If the function is marked as non-lazy, generate an indirect call
2485        // which loads from the GOT directly. This avoids runtime overhead
2486        // at the cost of eager binding (and one extra byte of encoding).
2487        OpFlags = X86II::MO_GOTPCREL;
2488        WrapperKind = X86ISD::WrapperRIP;
2489        ExtraLoad = true;
2490      }
2491
2492      Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
2493                                          G->getOffset(), OpFlags);
2494
2495      // Add a wrapper if needed.
2496      if (WrapperKind != ISD::DELETED_NODE)
2497        Callee = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Callee);
2498      // Add extra indirection if needed.
2499      if (ExtraLoad)
2500        Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Callee,
2501                             MachinePointerInfo::getGOT(),
2502                             false, false, false, 0);
2503    }
2504  } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2505    unsigned char OpFlags = 0;
2506
2507    // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
2508    // external symbols should go through the PLT.
2509    if (Subtarget->isTargetELF() &&
2510        getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2511      OpFlags = X86II::MO_PLT;
2512    } else if (Subtarget->isPICStyleStubAny() &&
2513               (!Subtarget->getTargetTriple().isMacOSX() ||
2514                Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2515      // PC-relative references to external symbols should go through $stub,
2516      // unless we're building with the leopard linker or later, which
2517      // automatically synthesizes these stubs.
2518      OpFlags = X86II::MO_DARWIN_STUB;
2519    }
2520
2521    Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
2522                                         OpFlags);
2523  }
2524
2525  // Returns a chain & a flag for retval copy to use.
2526  SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2527  SmallVector<SDValue, 8> Ops;
2528
2529  if (!IsSibcall && isTailCall) {
2530    Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
2531                           DAG.getIntPtrConstant(0, true), InFlag);
2532    InFlag = Chain.getValue(1);
2533  }
2534
2535  Ops.push_back(Chain);
2536  Ops.push_back(Callee);
2537
2538  if (isTailCall)
2539    Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
2540
2541  // Add argument registers to the end of the list so that they are known live
2542  // into the call.
2543  for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2544    Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2545                                  RegsToPass[i].second.getValueType()));
2546
2547  // Add a register mask operand representing the call-preserved registers.
2548  const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
2549  const uint32_t *Mask = TRI->getCallPreservedMask(CallConv);
2550  assert(Mask && "Missing call preserved mask for calling convention");
2551  Ops.push_back(DAG.getRegisterMask(Mask));
2552
2553  if (InFlag.getNode())
2554    Ops.push_back(InFlag);
2555
2556  if (isTailCall) {
2557    // We used to do:
2558    //// If this is the first return lowered for this function, add the regs
2559    //// to the liveout set for the function.
2560    // This isn't right, although it's probably harmless on x86; liveouts
2561    // should be computed from returns not tail calls.  Consider a void
2562    // function making a tail call to a function returning int.
2563    return DAG.getNode(X86ISD::TC_RETURN, dl,
2564                       NodeTys, &Ops[0], Ops.size());
2565  }
2566
2567  Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, &Ops[0], Ops.size());
2568  InFlag = Chain.getValue(1);
2569
2570  // Create the CALLSEQ_END node.
2571  unsigned NumBytesForCalleeToPush;
2572  if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2573                       getTargetMachine().Options.GuaranteedTailCallOpt))
2574    NumBytesForCalleeToPush = NumBytes;    // Callee pops everything
2575  else if (!Is64Bit && !IsTailCallConvention(CallConv) && !IsWindows &&
2576           SR == StackStructReturn)
2577    // If this is a call to a struct-return function, the callee
2578    // pops the hidden struct pointer, so we have to push it back.
2579    // This is common for Darwin/X86, Linux & Mingw32 targets.
2580    // For MSVC Win32 targets, the caller pops the hidden struct pointer.
2581    NumBytesForCalleeToPush = 4;
2582  else
2583    NumBytesForCalleeToPush = 0;  // Callee pops nothing.
2584
2585  // Returns a flag for retval copy to use.
2586  if (!IsSibcall) {
2587    Chain = DAG.getCALLSEQ_END(Chain,
2588                               DAG.getIntPtrConstant(NumBytes, true),
2589                               DAG.getIntPtrConstant(NumBytesForCalleeToPush,
2590                                                     true),
2591                               InFlag);
2592    InFlag = Chain.getValue(1);
2593  }
2594
2595  // Handle result values, copying them out of physregs into vregs that we
2596  // return.
2597  return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
2598                         Ins, dl, DAG, InVals);
2599}
2600
2601
2602//===----------------------------------------------------------------------===//
2603//                Fast Calling Convention (tail call) implementation
2604//===----------------------------------------------------------------------===//
2605
2606//  Like std call, callee cleans arguments, convention except that ECX is
2607//  reserved for storing the tail called function address. Only 2 registers are
2608//  free for argument passing (inreg). Tail call optimization is performed
2609//  provided:
2610//                * tailcallopt is enabled
2611//                * caller/callee are fastcc
2612//  On X86_64 architecture with GOT-style position independent code only local
2613//  (within module) calls are supported at the moment.
2614//  To keep the stack aligned according to platform abi the function
2615//  GetAlignedArgumentStackSize ensures that argument delta is always multiples
2616//  of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
2617//  If a tail called function callee has more arguments than the caller the
2618//  caller needs to make sure that there is room to move the RETADDR to. This is
2619//  achieved by reserving an area the size of the argument delta right after the
2620//  original REtADDR, but before the saved framepointer or the spilled registers
2621//  e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
2622//  stack layout:
2623//    arg1
2624//    arg2
2625//    RETADDR
2626//    [ new RETADDR
2627//      move area ]
2628//    (possible EBP)
2629//    ESI
2630//    EDI
2631//    local1 ..
2632
2633/// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
2634/// for a 16 byte align requirement.
2635unsigned
2636X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
2637                                               SelectionDAG& DAG) const {
2638  MachineFunction &MF = DAG.getMachineFunction();
2639  const TargetMachine &TM = MF.getTarget();
2640  const TargetFrameLowering &TFI = *TM.getFrameLowering();
2641  unsigned StackAlignment = TFI.getStackAlignment();
2642  uint64_t AlignMask = StackAlignment - 1;
2643  int64_t Offset = StackSize;
2644  uint64_t SlotSize = TD->getPointerSize();
2645  if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
2646    // Number smaller than 12 so just add the difference.
2647    Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
2648  } else {
2649    // Mask out lower bits, add stackalignment once plus the 12 bytes.
2650    Offset = ((~AlignMask) & Offset) + StackAlignment +
2651      (StackAlignment-SlotSize);
2652  }
2653  return Offset;
2654}
2655
2656/// MatchingStackOffset - Return true if the given stack call argument is
2657/// already available in the same position (relatively) of the caller's
2658/// incoming argument stack.
2659static
2660bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
2661                         MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
2662                         const X86InstrInfo *TII) {
2663  unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
2664  int FI = INT_MAX;
2665  if (Arg.getOpcode() == ISD::CopyFromReg) {
2666    unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
2667    if (!TargetRegisterInfo::isVirtualRegister(VR))
2668      return false;
2669    MachineInstr *Def = MRI->getVRegDef(VR);
2670    if (!Def)
2671      return false;
2672    if (!Flags.isByVal()) {
2673      if (!TII->isLoadFromStackSlot(Def, FI))
2674        return false;
2675    } else {
2676      unsigned Opcode = Def->getOpcode();
2677      if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r) &&
2678          Def->getOperand(1).isFI()) {
2679        FI = Def->getOperand(1).getIndex();
2680        Bytes = Flags.getByValSize();
2681      } else
2682        return false;
2683    }
2684  } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
2685    if (Flags.isByVal())
2686      // ByVal argument is passed in as a pointer but it's now being
2687      // dereferenced. e.g.
2688      // define @foo(%struct.X* %A) {
2689      //   tail call @bar(%struct.X* byval %A)
2690      // }
2691      return false;
2692    SDValue Ptr = Ld->getBasePtr();
2693    FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
2694    if (!FINode)
2695      return false;
2696    FI = FINode->getIndex();
2697  } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
2698    FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
2699    FI = FINode->getIndex();
2700    Bytes = Flags.getByValSize();
2701  } else
2702    return false;
2703
2704  assert(FI != INT_MAX);
2705  if (!MFI->isFixedObjectIndex(FI))
2706    return false;
2707  return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
2708}
2709
2710/// IsEligibleForTailCallOptimization - Check whether the call is eligible
2711/// for tail call optimization. Targets which want to do tail call
2712/// optimization should implement this function.
2713bool
2714X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
2715                                                     CallingConv::ID CalleeCC,
2716                                                     bool isVarArg,
2717                                                     bool isCalleeStructRet,
2718                                                     bool isCallerStructRet,
2719                                    const SmallVectorImpl<ISD::OutputArg> &Outs,
2720                                    const SmallVectorImpl<SDValue> &OutVals,
2721                                    const SmallVectorImpl<ISD::InputArg> &Ins,
2722                                                     SelectionDAG& DAG) const {
2723  if (!IsTailCallConvention(CalleeCC) &&
2724      CalleeCC != CallingConv::C)
2725    return false;
2726
2727  // If -tailcallopt is specified, make fastcc functions tail-callable.
2728  const MachineFunction &MF = DAG.getMachineFunction();
2729  const Function *CallerF = DAG.getMachineFunction().getFunction();
2730  CallingConv::ID CallerCC = CallerF->getCallingConv();
2731  bool CCMatch = CallerCC == CalleeCC;
2732
2733  if (getTargetMachine().Options.GuaranteedTailCallOpt) {
2734    if (IsTailCallConvention(CalleeCC) && CCMatch)
2735      return true;
2736    return false;
2737  }
2738
2739  // Look for obvious safe cases to perform tail call optimization that do not
2740  // require ABI changes. This is what gcc calls sibcall.
2741
2742  // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
2743  // emit a special epilogue.
2744  if (RegInfo->needsStackRealignment(MF))
2745    return false;
2746
2747  // Also avoid sibcall optimization if either caller or callee uses struct
2748  // return semantics.
2749  if (isCalleeStructRet || isCallerStructRet)
2750    return false;
2751
2752  // An stdcall caller is expected to clean up its arguments; the callee
2753  // isn't going to do that.
2754  if (!CCMatch && CallerCC==CallingConv::X86_StdCall)
2755    return false;
2756
2757  // Do not sibcall optimize vararg calls unless all arguments are passed via
2758  // registers.
2759  if (isVarArg && !Outs.empty()) {
2760
2761    // Optimizing for varargs on Win64 is unlikely to be safe without
2762    // additional testing.
2763    if (Subtarget->isTargetWin64())
2764      return false;
2765
2766    SmallVector<CCValAssign, 16> ArgLocs;
2767    CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
2768                   getTargetMachine(), ArgLocs, *DAG.getContext());
2769
2770    CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2771    for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
2772      if (!ArgLocs[i].isRegLoc())
2773        return false;
2774  }
2775
2776  // If the call result is in ST0 / ST1, it needs to be popped off the x87
2777  // stack.  Therefore, if it's not used by the call it is not safe to optimize
2778  // this into a sibcall.
2779  bool Unused = false;
2780  for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
2781    if (!Ins[i].Used) {
2782      Unused = true;
2783      break;
2784    }
2785  }
2786  if (Unused) {
2787    SmallVector<CCValAssign, 16> RVLocs;
2788    CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(),
2789                   getTargetMachine(), RVLocs, *DAG.getContext());
2790    CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2791    for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2792      CCValAssign &VA = RVLocs[i];
2793      if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1)
2794        return false;
2795    }
2796  }
2797
2798  // If the calling conventions do not match, then we'd better make sure the
2799  // results are returned in the same way as what the caller expects.
2800  if (!CCMatch) {
2801    SmallVector<CCValAssign, 16> RVLocs1;
2802    CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(),
2803                    getTargetMachine(), RVLocs1, *DAG.getContext());
2804    CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
2805
2806    SmallVector<CCValAssign, 16> RVLocs2;
2807    CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(),
2808                    getTargetMachine(), RVLocs2, *DAG.getContext());
2809    CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
2810
2811    if (RVLocs1.size() != RVLocs2.size())
2812      return false;
2813    for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
2814      if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
2815        return false;
2816      if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
2817        return false;
2818      if (RVLocs1[i].isRegLoc()) {
2819        if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
2820          return false;
2821      } else {
2822        if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
2823          return false;
2824      }
2825    }
2826  }
2827
2828  // If the callee takes no arguments then go on to check the results of the
2829  // call.
2830  if (!Outs.empty()) {
2831    // Check if stack adjustment is needed. For now, do not do this if any
2832    // argument is passed on the stack.
2833    SmallVector<CCValAssign, 16> ArgLocs;
2834    CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
2835                   getTargetMachine(), ArgLocs, *DAG.getContext());
2836
2837    // Allocate shadow area for Win64
2838    if (Subtarget->isTargetWin64()) {
2839      CCInfo.AllocateStack(32, 8);
2840    }
2841
2842    CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2843    if (CCInfo.getNextStackOffset()) {
2844      MachineFunction &MF = DAG.getMachineFunction();
2845      if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
2846        return false;
2847
2848      // Check if the arguments are already laid out in the right way as
2849      // the caller's fixed stack objects.
2850      MachineFrameInfo *MFI = MF.getFrameInfo();
2851      const MachineRegisterInfo *MRI = &MF.getRegInfo();
2852      const X86InstrInfo *TII =
2853        ((const X86TargetMachine&)getTargetMachine()).getInstrInfo();
2854      for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2855        CCValAssign &VA = ArgLocs[i];
2856        SDValue Arg = OutVals[i];
2857        ISD::ArgFlagsTy Flags = Outs[i].Flags;
2858        if (VA.getLocInfo() == CCValAssign::Indirect)
2859          return false;
2860        if (!VA.isRegLoc()) {
2861          if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2862                                   MFI, MRI, TII))
2863            return false;
2864        }
2865      }
2866    }
2867
2868    // If the tailcall address may be in a register, then make sure it's
2869    // possible to register allocate for it. In 32-bit, the call address can
2870    // only target EAX, EDX, or ECX since the tail call must be scheduled after
2871    // callee-saved registers are restored. These happen to be the same
2872    // registers used to pass 'inreg' arguments so watch out for those.
2873    if (!Subtarget->is64Bit() &&
2874        !isa<GlobalAddressSDNode>(Callee) &&
2875        !isa<ExternalSymbolSDNode>(Callee)) {
2876      unsigned NumInRegs = 0;
2877      for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2878        CCValAssign &VA = ArgLocs[i];
2879        if (!VA.isRegLoc())
2880          continue;
2881        unsigned Reg = VA.getLocReg();
2882        switch (Reg) {
2883        default: break;
2884        case X86::EAX: case X86::EDX: case X86::ECX:
2885          if (++NumInRegs == 3)
2886            return false;
2887          break;
2888        }
2889      }
2890    }
2891  }
2892
2893  return true;
2894}
2895
2896FastISel *
2897X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
2898                                  const TargetLibraryInfo *libInfo) const {
2899  return X86::createFastISel(funcInfo, libInfo);
2900}
2901
2902
2903//===----------------------------------------------------------------------===//
2904//                           Other Lowering Hooks
2905//===----------------------------------------------------------------------===//
2906
2907static bool MayFoldLoad(SDValue Op) {
2908  return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
2909}
2910
2911static bool MayFoldIntoStore(SDValue Op) {
2912  return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
2913}
2914
2915static bool isTargetShuffle(unsigned Opcode) {
2916  switch(Opcode) {
2917  default: return false;
2918  case X86ISD::PSHUFD:
2919  case X86ISD::PSHUFHW:
2920  case X86ISD::PSHUFLW:
2921  case X86ISD::SHUFP:
2922  case X86ISD::PALIGN:
2923  case X86ISD::MOVLHPS:
2924  case X86ISD::MOVLHPD:
2925  case X86ISD::MOVHLPS:
2926  case X86ISD::MOVLPS:
2927  case X86ISD::MOVLPD:
2928  case X86ISD::MOVSHDUP:
2929  case X86ISD::MOVSLDUP:
2930  case X86ISD::MOVDDUP:
2931  case X86ISD::MOVSS:
2932  case X86ISD::MOVSD:
2933  case X86ISD::UNPCKL:
2934  case X86ISD::UNPCKH:
2935  case X86ISD::VPERMILP:
2936  case X86ISD::VPERM2X128:
2937  case X86ISD::VPERMI:
2938    return true;
2939  }
2940}
2941
2942static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2943                                    SDValue V1, SelectionDAG &DAG) {
2944  switch(Opc) {
2945  default: llvm_unreachable("Unknown x86 shuffle node");
2946  case X86ISD::MOVSHDUP:
2947  case X86ISD::MOVSLDUP:
2948  case X86ISD::MOVDDUP:
2949    return DAG.getNode(Opc, dl, VT, V1);
2950  }
2951}
2952
2953static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2954                                    SDValue V1, unsigned TargetMask,
2955                                    SelectionDAG &DAG) {
2956  switch(Opc) {
2957  default: llvm_unreachable("Unknown x86 shuffle node");
2958  case X86ISD::PSHUFD:
2959  case X86ISD::PSHUFHW:
2960  case X86ISD::PSHUFLW:
2961  case X86ISD::VPERMILP:
2962  case X86ISD::VPERMI:
2963    return DAG.getNode(Opc, dl, VT, V1, DAG.getConstant(TargetMask, MVT::i8));
2964  }
2965}
2966
2967static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2968                                    SDValue V1, SDValue V2, unsigned TargetMask,
2969                                    SelectionDAG &DAG) {
2970  switch(Opc) {
2971  default: llvm_unreachable("Unknown x86 shuffle node");
2972  case X86ISD::PALIGN:
2973  case X86ISD::SHUFP:
2974  case X86ISD::VPERM2X128:
2975    return DAG.getNode(Opc, dl, VT, V1, V2,
2976                       DAG.getConstant(TargetMask, MVT::i8));
2977  }
2978}
2979
2980static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2981                                    SDValue V1, SDValue V2, SelectionDAG &DAG) {
2982  switch(Opc) {
2983  default: llvm_unreachable("Unknown x86 shuffle node");
2984  case X86ISD::MOVLHPS:
2985  case X86ISD::MOVLHPD:
2986  case X86ISD::MOVHLPS:
2987  case X86ISD::MOVLPS:
2988  case X86ISD::MOVLPD:
2989  case X86ISD::MOVSS:
2990  case X86ISD::MOVSD:
2991  case X86ISD::UNPCKL:
2992  case X86ISD::UNPCKH:
2993    return DAG.getNode(Opc, dl, VT, V1, V2);
2994  }
2995}
2996
2997SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
2998  MachineFunction &MF = DAG.getMachineFunction();
2999  X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
3000  int ReturnAddrIndex = FuncInfo->getRAIndex();
3001
3002  if (ReturnAddrIndex == 0) {
3003    // Set up a frame object for the return address.
3004    uint64_t SlotSize = TD->getPointerSize();
3005    ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize, -SlotSize,
3006                                                           false);
3007    FuncInfo->setRAIndex(ReturnAddrIndex);
3008  }
3009
3010  return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
3011}
3012
3013
3014bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
3015                                       bool hasSymbolicDisplacement) {
3016  // Offset should fit into 32 bit immediate field.
3017  if (!isInt<32>(Offset))
3018    return false;
3019
3020  // If we don't have a symbolic displacement - we don't have any extra
3021  // restrictions.
3022  if (!hasSymbolicDisplacement)
3023    return true;
3024
3025  // FIXME: Some tweaks might be needed for medium code model.
3026  if (M != CodeModel::Small && M != CodeModel::Kernel)
3027    return false;
3028
3029  // For small code model we assume that latest object is 16MB before end of 31
3030  // bits boundary. We may also accept pretty large negative constants knowing
3031  // that all objects are in the positive half of address space.
3032  if (M == CodeModel::Small && Offset < 16*1024*1024)
3033    return true;
3034
3035  // For kernel code model we know that all object resist in the negative half
3036  // of 32bits address space. We may not accept negative offsets, since they may
3037  // be just off and we may accept pretty large positive ones.
3038  if (M == CodeModel::Kernel && Offset > 0)
3039    return true;
3040
3041  return false;
3042}
3043
3044/// isCalleePop - Determines whether the callee is required to pop its
3045/// own arguments. Callee pop is necessary to support tail calls.
3046bool X86::isCalleePop(CallingConv::ID CallingConv,
3047                      bool is64Bit, bool IsVarArg, bool TailCallOpt) {
3048  if (IsVarArg)
3049    return false;
3050
3051  switch (CallingConv) {
3052  default:
3053    return false;
3054  case CallingConv::X86_StdCall:
3055    return !is64Bit;
3056  case CallingConv::X86_FastCall:
3057    return !is64Bit;
3058  case CallingConv::X86_ThisCall:
3059    return !is64Bit;
3060  case CallingConv::Fast:
3061    return TailCallOpt;
3062  case CallingConv::GHC:
3063    return TailCallOpt;
3064  }
3065}
3066
3067/// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
3068/// specific condition code, returning the condition code and the LHS/RHS of the
3069/// comparison to make.
3070static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
3071                               SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
3072  if (!isFP) {
3073    if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
3074      if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
3075        // X > -1   -> X == 0, jump !sign.
3076        RHS = DAG.getConstant(0, RHS.getValueType());
3077        return X86::COND_NS;
3078      }
3079      if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
3080        // X < 0   -> X == 0, jump on sign.
3081        return X86::COND_S;
3082      }
3083      if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
3084        // X < 1   -> X <= 0
3085        RHS = DAG.getConstant(0, RHS.getValueType());
3086        return X86::COND_LE;
3087      }
3088    }
3089
3090    switch (SetCCOpcode) {
3091    default: llvm_unreachable("Invalid integer condition!");
3092    case ISD::SETEQ:  return X86::COND_E;
3093    case ISD::SETGT:  return X86::COND_G;
3094    case ISD::SETGE:  return X86::COND_GE;
3095    case ISD::SETLT:  return X86::COND_L;
3096    case ISD::SETLE:  return X86::COND_LE;
3097    case ISD::SETNE:  return X86::COND_NE;
3098    case ISD::SETULT: return X86::COND_B;
3099    case ISD::SETUGT: return X86::COND_A;
3100    case ISD::SETULE: return X86::COND_BE;
3101    case ISD::SETUGE: return X86::COND_AE;
3102    }
3103  }
3104
3105  // First determine if it is required or is profitable to flip the operands.
3106
3107  // If LHS is a foldable load, but RHS is not, flip the condition.
3108  if (ISD::isNON_EXTLoad(LHS.getNode()) &&
3109      !ISD::isNON_EXTLoad(RHS.getNode())) {
3110    SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
3111    std::swap(LHS, RHS);
3112  }
3113
3114  switch (SetCCOpcode) {
3115  default: break;
3116  case ISD::SETOLT:
3117  case ISD::SETOLE:
3118  case ISD::SETUGT:
3119  case ISD::SETUGE:
3120    std::swap(LHS, RHS);
3121    break;
3122  }
3123
3124  // On a floating point condition, the flags are set as follows:
3125  // ZF  PF  CF   op
3126  //  0 | 0 | 0 | X > Y
3127  //  0 | 0 | 1 | X < Y
3128  //  1 | 0 | 0 | X == Y
3129  //  1 | 1 | 1 | unordered
3130  switch (SetCCOpcode) {
3131  default: llvm_unreachable("Condcode should be pre-legalized away");
3132  case ISD::SETUEQ:
3133  case ISD::SETEQ:   return X86::COND_E;
3134  case ISD::SETOLT:              // flipped
3135  case ISD::SETOGT:
3136  case ISD::SETGT:   return X86::COND_A;
3137  case ISD::SETOLE:              // flipped
3138  case ISD::SETOGE:
3139  case ISD::SETGE:   return X86::COND_AE;
3140  case ISD::SETUGT:              // flipped
3141  case ISD::SETULT:
3142  case ISD::SETLT:   return X86::COND_B;
3143  case ISD::SETUGE:              // flipped
3144  case ISD::SETULE:
3145  case ISD::SETLE:   return X86::COND_BE;
3146  case ISD::SETONE:
3147  case ISD::SETNE:   return X86::COND_NE;
3148  case ISD::SETUO:   return X86::COND_P;
3149  case ISD::SETO:    return X86::COND_NP;
3150  case ISD::SETOEQ:
3151  case ISD::SETUNE:  return X86::COND_INVALID;
3152  }
3153}
3154
3155/// hasFPCMov - is there a floating point cmov for the specific X86 condition
3156/// code. Current x86 isa includes the following FP cmov instructions:
3157/// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
3158static bool hasFPCMov(unsigned X86CC) {
3159  switch (X86CC) {
3160  default:
3161    return false;
3162  case X86::COND_B:
3163  case X86::COND_BE:
3164  case X86::COND_E:
3165  case X86::COND_P:
3166  case X86::COND_A:
3167  case X86::COND_AE:
3168  case X86::COND_NE:
3169  case X86::COND_NP:
3170    return true;
3171  }
3172}
3173
3174/// isFPImmLegal - Returns true if the target can instruction select the
3175/// specified FP immediate natively. If false, the legalizer will
3176/// materialize the FP immediate as a load from a constant pool.
3177bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3178  for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
3179    if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
3180      return true;
3181  }
3182  return false;
3183}
3184
3185/// isUndefOrInRange - Return true if Val is undef or if its value falls within
3186/// the specified range (L, H].
3187static bool isUndefOrInRange(int Val, int Low, int Hi) {
3188  return (Val < 0) || (Val >= Low && Val < Hi);
3189}
3190
3191/// isUndefOrEqual - Val is either less than zero (undef) or equal to the
3192/// specified value.
3193static bool isUndefOrEqual(int Val, int CmpVal) {
3194  if (Val < 0 || Val == CmpVal)
3195    return true;
3196  return false;
3197}
3198
3199/// isSequentialOrUndefInRange - Return true if every element in Mask, beginning
3200/// from position Pos and ending in Pos+Size, falls within the specified
3201/// sequential range (L, L+Pos]. or is undef.
3202static bool isSequentialOrUndefInRange(ArrayRef<int> Mask,
3203                                       unsigned Pos, unsigned Size, int Low) {
3204  for (unsigned i = Pos, e = Pos+Size; i != e; ++i, ++Low)
3205    if (!isUndefOrEqual(Mask[i], Low))
3206      return false;
3207  return true;
3208}
3209
3210/// isPSHUFDMask - Return true if the node specifies a shuffle of elements that
3211/// is suitable for input to PSHUFD or PSHUFW.  That is, it doesn't reference
3212/// the second operand.
3213static bool isPSHUFDMask(ArrayRef<int> Mask, EVT VT) {
3214  if (VT == MVT::v4f32 || VT == MVT::v4i32 )
3215    return (Mask[0] < 4 && Mask[1] < 4 && Mask[2] < 4 && Mask[3] < 4);
3216  if (VT == MVT::v2f64 || VT == MVT::v2i64)
3217    return (Mask[0] < 2 && Mask[1] < 2);
3218  return false;
3219}
3220
3221/// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that
3222/// is suitable for input to PSHUFHW.
3223static bool isPSHUFHWMask(ArrayRef<int> Mask, EVT VT, bool HasAVX2) {
3224  if (VT != MVT::v8i16 && (!HasAVX2 || VT != MVT::v16i16))
3225    return false;
3226
3227  // Lower quadword copied in order or undef.
3228  if (!isSequentialOrUndefInRange(Mask, 0, 4, 0))
3229    return false;
3230
3231  // Upper quadword shuffled.
3232  for (unsigned i = 4; i != 8; ++i)
3233    if (!isUndefOrInRange(Mask[i], 4, 8))
3234      return false;
3235
3236  if (VT == MVT::v16i16) {
3237    // Lower quadword copied in order or undef.
3238    if (!isSequentialOrUndefInRange(Mask, 8, 4, 8))
3239      return false;
3240
3241    // Upper quadword shuffled.
3242    for (unsigned i = 12; i != 16; ++i)
3243      if (!isUndefOrInRange(Mask[i], 12, 16))
3244        return false;
3245  }
3246
3247  return true;
3248}
3249
3250/// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that
3251/// is suitable for input to PSHUFLW.
3252static bool isPSHUFLWMask(ArrayRef<int> Mask, EVT VT, bool HasAVX2) {
3253  if (VT != MVT::v8i16 && (!HasAVX2 || VT != MVT::v16i16))
3254    return false;
3255
3256  // Upper quadword copied in order.
3257  if (!isSequentialOrUndefInRange(Mask, 4, 4, 4))
3258    return false;
3259
3260  // Lower quadword shuffled.
3261  for (unsigned i = 0; i != 4; ++i)
3262    if (!isUndefOrInRange(Mask[i], 0, 4))
3263      return false;
3264
3265  if (VT == MVT::v16i16) {
3266    // Upper quadword copied in order.
3267    if (!isSequentialOrUndefInRange(Mask, 12, 4, 12))
3268      return false;
3269
3270    // Lower quadword shuffled.
3271    for (unsigned i = 8; i != 12; ++i)
3272      if (!isUndefOrInRange(Mask[i], 8, 12))
3273        return false;
3274  }
3275
3276  return true;
3277}
3278
3279/// isPALIGNRMask - Return true if the node specifies a shuffle of elements that
3280/// is suitable for input to PALIGNR.
3281static bool isPALIGNRMask(ArrayRef<int> Mask, EVT VT,
3282                          const X86Subtarget *Subtarget) {
3283  if ((VT.getSizeInBits() == 128 && !Subtarget->hasSSSE3()) ||
3284      (VT.getSizeInBits() == 256 && !Subtarget->hasAVX2()))
3285    return false;
3286
3287  unsigned NumElts = VT.getVectorNumElements();
3288  unsigned NumLanes = VT.getSizeInBits()/128;
3289  unsigned NumLaneElts = NumElts/NumLanes;
3290
3291  // Do not handle 64-bit element shuffles with palignr.
3292  if (NumLaneElts == 2)
3293    return false;
3294
3295  for (unsigned l = 0; l != NumElts; l+=NumLaneElts) {
3296    unsigned i;
3297    for (i = 0; i != NumLaneElts; ++i) {
3298      if (Mask[i+l] >= 0)
3299        break;
3300    }
3301
3302    // Lane is all undef, go to next lane
3303    if (i == NumLaneElts)
3304      continue;
3305
3306    int Start = Mask[i+l];
3307
3308    // Make sure its in this lane in one of the sources
3309    if (!isUndefOrInRange(Start, l, l+NumLaneElts) &&
3310        !isUndefOrInRange(Start, l+NumElts, l+NumElts+NumLaneElts))
3311      return false;
3312
3313    // If not lane 0, then we must match lane 0
3314    if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Start, Mask[i]+l))
3315      return false;
3316
3317    // Correct second source to be contiguous with first source
3318    if (Start >= (int)NumElts)
3319      Start -= NumElts - NumLaneElts;
3320
3321    // Make sure we're shifting in the right direction.
3322    if (Start <= (int)(i+l))
3323      return false;
3324
3325    Start -= i;
3326
3327    // Check the rest of the elements to see if they are consecutive.
3328    for (++i; i != NumLaneElts; ++i) {
3329      int Idx = Mask[i+l];
3330
3331      // Make sure its in this lane
3332      if (!isUndefOrInRange(Idx, l, l+NumLaneElts) &&
3333          !isUndefOrInRange(Idx, l+NumElts, l+NumElts+NumLaneElts))
3334        return false;
3335
3336      // If not lane 0, then we must match lane 0
3337      if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Idx, Mask[i]+l))
3338        return false;
3339
3340      if (Idx >= (int)NumElts)
3341        Idx -= NumElts - NumLaneElts;
3342
3343      if (!isUndefOrEqual(Idx, Start+i))
3344        return false;
3345
3346    }
3347  }
3348
3349  return true;
3350}
3351
3352/// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
3353/// the two vector operands have swapped position.
3354static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask,
3355                                     unsigned NumElems) {
3356  for (unsigned i = 0; i != NumElems; ++i) {
3357    int idx = Mask[i];
3358    if (idx < 0)
3359      continue;
3360    else if (idx < (int)NumElems)
3361      Mask[i] = idx + NumElems;
3362    else
3363      Mask[i] = idx - NumElems;
3364  }
3365}
3366
3367/// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
3368/// specifies a shuffle of elements that is suitable for input to 128/256-bit
3369/// SHUFPS and SHUFPD. If Commuted is true, then it checks for sources to be
3370/// reverse of what x86 shuffles want.
3371static bool isSHUFPMask(ArrayRef<int> Mask, EVT VT, bool HasAVX,
3372                        bool Commuted = false) {
3373  if (!HasAVX && VT.getSizeInBits() == 256)
3374    return false;
3375
3376  unsigned NumElems = VT.getVectorNumElements();
3377  unsigned NumLanes = VT.getSizeInBits()/128;
3378  unsigned NumLaneElems = NumElems/NumLanes;
3379
3380  if (NumLaneElems != 2 && NumLaneElems != 4)
3381    return false;
3382
3383  // VSHUFPSY divides the resulting vector into 4 chunks.
3384  // The sources are also splitted into 4 chunks, and each destination
3385  // chunk must come from a different source chunk.
3386  //
3387  //  SRC1 =>   X7    X6    X5    X4    X3    X2    X1    X0
3388  //  SRC2 =>   Y7    Y6    Y5    Y4    Y3    Y2    Y1    Y9
3389  //
3390  //  DST  =>  Y7..Y4,   Y7..Y4,   X7..X4,   X7..X4,
3391  //           Y3..Y0,   Y3..Y0,   X3..X0,   X3..X0
3392  //
3393  // VSHUFPDY divides the resulting vector into 4 chunks.
3394  // The sources are also splitted into 4 chunks, and each destination
3395  // chunk must come from a different source chunk.
3396  //
3397  //  SRC1 =>      X3       X2       X1       X0
3398  //  SRC2 =>      Y3       Y2       Y1       Y0
3399  //
3400  //  DST  =>  Y3..Y2,  X3..X2,  Y1..Y0,  X1..X0
3401  //
3402  unsigned HalfLaneElems = NumLaneElems/2;
3403  for (unsigned l = 0; l != NumElems; l += NumLaneElems) {
3404    for (unsigned i = 0; i != NumLaneElems; ++i) {
3405      int Idx = Mask[i+l];
3406      unsigned RngStart = l + ((Commuted == (i<HalfLaneElems)) ? NumElems : 0);
3407      if (!isUndefOrInRange(Idx, RngStart, RngStart+NumLaneElems))
3408        return false;
3409      // For VSHUFPSY, the mask of the second half must be the same as the
3410      // first but with the appropriate offsets. This works in the same way as
3411      // VPERMILPS works with masks.
3412      if (NumElems != 8 || l == 0 || Mask[i] < 0)
3413        continue;
3414      if (!isUndefOrEqual(Idx, Mask[i]+l))
3415        return false;
3416    }
3417  }
3418
3419  return true;
3420}
3421
3422/// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
3423/// specifies a shuffle of elements that is suitable for input to MOVHLPS.
3424static bool isMOVHLPSMask(ArrayRef<int> Mask, EVT VT) {
3425  if (!VT.is128BitVector())
3426    return false;
3427
3428  unsigned NumElems = VT.getVectorNumElements();
3429
3430  if (NumElems != 4)
3431    return false;
3432
3433  // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
3434  return isUndefOrEqual(Mask[0], 6) &&
3435         isUndefOrEqual(Mask[1], 7) &&
3436         isUndefOrEqual(Mask[2], 2) &&
3437         isUndefOrEqual(Mask[3], 3);
3438}
3439
3440/// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
3441/// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
3442/// <2, 3, 2, 3>
3443static bool isMOVHLPS_v_undef_Mask(ArrayRef<int> Mask, EVT VT) {
3444  if (!VT.is128BitVector())
3445    return false;
3446
3447  unsigned NumElems = VT.getVectorNumElements();
3448
3449  if (NumElems != 4)
3450    return false;
3451
3452  return isUndefOrEqual(Mask[0], 2) &&
3453         isUndefOrEqual(Mask[1], 3) &&
3454         isUndefOrEqual(Mask[2], 2) &&
3455         isUndefOrEqual(Mask[3], 3);
3456}
3457
3458/// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
3459/// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
3460static bool isMOVLPMask(ArrayRef<int> Mask, EVT VT) {
3461  if (!VT.is128BitVector())
3462    return false;
3463
3464  unsigned NumElems = VT.getVectorNumElements();
3465
3466  if (NumElems != 2 && NumElems != 4)
3467    return false;
3468
3469  for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3470    if (!isUndefOrEqual(Mask[i], i + NumElems))
3471      return false;
3472
3473  for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
3474    if (!isUndefOrEqual(Mask[i], i))
3475      return false;
3476
3477  return true;
3478}
3479
3480/// isMOVLHPSMask - Return true if the specified VECTOR_SHUFFLE operand
3481/// specifies a shuffle of elements that is suitable for input to MOVLHPS.
3482static bool isMOVLHPSMask(ArrayRef<int> Mask, EVT VT) {
3483  if (!VT.is128BitVector())
3484    return false;
3485
3486  unsigned NumElems = VT.getVectorNumElements();
3487
3488  if (NumElems != 2 && NumElems != 4)
3489    return false;
3490
3491  for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3492    if (!isUndefOrEqual(Mask[i], i))
3493      return false;
3494
3495  for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3496    if (!isUndefOrEqual(Mask[i + e], i + NumElems))
3497      return false;
3498
3499  return true;
3500}
3501
3502//
3503// Some special combinations that can be optimized.
3504//
3505static
3506SDValue Compact8x32ShuffleNode(ShuffleVectorSDNode *SVOp,
3507                               SelectionDAG &DAG) {
3508  EVT VT = SVOp->getValueType(0);
3509  DebugLoc dl = SVOp->getDebugLoc();
3510
3511  if (VT != MVT::v8i32 && VT != MVT::v8f32)
3512    return SDValue();
3513
3514  ArrayRef<int> Mask = SVOp->getMask();
3515
3516  // These are the special masks that may be optimized.
3517  static const int MaskToOptimizeEven[] = {0, 8, 2, 10, 4, 12, 6, 14};
3518  static const int MaskToOptimizeOdd[]  = {1, 9, 3, 11, 5, 13, 7, 15};
3519  bool MatchEvenMask = true;
3520  bool MatchOddMask  = true;
3521  for (int i=0; i<8; ++i) {
3522    if (!isUndefOrEqual(Mask[i], MaskToOptimizeEven[i]))
3523      MatchEvenMask = false;
3524    if (!isUndefOrEqual(Mask[i], MaskToOptimizeOdd[i]))
3525      MatchOddMask = false;
3526  }
3527
3528  if (!MatchEvenMask && !MatchOddMask)
3529    return SDValue();
3530
3531  SDValue UndefNode = DAG.getNode(ISD::UNDEF, dl, VT);
3532
3533  SDValue Op0 = SVOp->getOperand(0);
3534  SDValue Op1 = SVOp->getOperand(1);
3535
3536  if (MatchEvenMask) {
3537    // Shift the second operand right to 32 bits.
3538    static const int ShiftRightMask[] = {-1, 0, -1, 2, -1, 4, -1, 6 };
3539    Op1 = DAG.getVectorShuffle(VT, dl, Op1, UndefNode, ShiftRightMask);
3540  } else {
3541    // Shift the first operand left to 32 bits.
3542    static const int ShiftLeftMask[] = {1, -1, 3, -1, 5, -1, 7, -1 };
3543    Op0 = DAG.getVectorShuffle(VT, dl, Op0, UndefNode, ShiftLeftMask);
3544  }
3545  static const int BlendMask[] = {0, 9, 2, 11, 4, 13, 6, 15};
3546  return DAG.getVectorShuffle(VT, dl, Op0, Op1, BlendMask);
3547}
3548
3549/// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
3550/// specifies a shuffle of elements that is suitable for input to UNPCKL.
3551static bool isUNPCKLMask(ArrayRef<int> Mask, EVT VT,
3552                         bool HasAVX2, bool V2IsSplat = false) {
3553  unsigned NumElts = VT.getVectorNumElements();
3554
3555  assert((VT.is128BitVector() || VT.is256BitVector()) &&
3556         "Unsupported vector type for unpckh");
3557
3558  if (VT.getSizeInBits() == 256 && NumElts != 4 && NumElts != 8 &&
3559      (!HasAVX2 || (NumElts != 16 && NumElts != 32)))
3560    return false;
3561
3562  // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3563  // independently on 128-bit lanes.
3564  unsigned NumLanes = VT.getSizeInBits()/128;
3565  unsigned NumLaneElts = NumElts/NumLanes;
3566
3567  for (unsigned l = 0; l != NumLanes; ++l) {
3568    for (unsigned i = l*NumLaneElts, j = l*NumLaneElts;
3569         i != (l+1)*NumLaneElts;
3570         i += 2, ++j) {
3571      int BitI  = Mask[i];
3572      int BitI1 = Mask[i+1];
3573      if (!isUndefOrEqual(BitI, j))
3574        return false;
3575      if (V2IsSplat) {
3576        if (!isUndefOrEqual(BitI1, NumElts))
3577          return false;
3578      } else {
3579        if (!isUndefOrEqual(BitI1, j + NumElts))
3580          return false;
3581      }
3582    }
3583  }
3584
3585  return true;
3586}
3587
3588/// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
3589/// specifies a shuffle of elements that is suitable for input to UNPCKH.
3590static bool isUNPCKHMask(ArrayRef<int> Mask, EVT VT,
3591                         bool HasAVX2, bool V2IsSplat = false) {
3592  unsigned NumElts = VT.getVectorNumElements();
3593
3594  assert((VT.is128BitVector() || VT.is256BitVector()) &&
3595         "Unsupported vector type for unpckh");
3596
3597  if (VT.getSizeInBits() == 256 && NumElts != 4 && NumElts != 8 &&
3598      (!HasAVX2 || (NumElts != 16 && NumElts != 32)))
3599    return false;
3600
3601  // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3602  // independently on 128-bit lanes.
3603  unsigned NumLanes = VT.getSizeInBits()/128;
3604  unsigned NumLaneElts = NumElts/NumLanes;
3605
3606  for (unsigned l = 0; l != NumLanes; ++l) {
3607    for (unsigned i = l*NumLaneElts, j = (l*NumLaneElts)+NumLaneElts/2;
3608         i != (l+1)*NumLaneElts; i += 2, ++j) {
3609      int BitI  = Mask[i];
3610      int BitI1 = Mask[i+1];
3611      if (!isUndefOrEqual(BitI, j))
3612        return false;
3613      if (V2IsSplat) {
3614        if (isUndefOrEqual(BitI1, NumElts))
3615          return false;
3616      } else {
3617        if (!isUndefOrEqual(BitI1, j+NumElts))
3618          return false;
3619      }
3620    }
3621  }
3622  return true;
3623}
3624
3625/// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
3626/// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
3627/// <0, 0, 1, 1>
3628static bool isUNPCKL_v_undef_Mask(ArrayRef<int> Mask, EVT VT,
3629                                  bool HasAVX2) {
3630  unsigned NumElts = VT.getVectorNumElements();
3631
3632  assert((VT.is128BitVector() || VT.is256BitVector()) &&
3633         "Unsupported vector type for unpckh");
3634
3635  if (VT.getSizeInBits() == 256 && NumElts != 4 && NumElts != 8 &&
3636      (!HasAVX2 || (NumElts != 16 && NumElts != 32)))
3637    return false;
3638
3639  // For 256-bit i64/f64, use MOVDDUPY instead, so reject the matching pattern
3640  // FIXME: Need a better way to get rid of this, there's no latency difference
3641  // between UNPCKLPD and MOVDDUP, the later should always be checked first and
3642  // the former later. We should also remove the "_undef" special mask.
3643  if (NumElts == 4 && VT.getSizeInBits() == 256)
3644    return false;
3645
3646  // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3647  // independently on 128-bit lanes.
3648  unsigned NumLanes = VT.getSizeInBits()/128;
3649  unsigned NumLaneElts = NumElts/NumLanes;
3650
3651  for (unsigned l = 0; l != NumLanes; ++l) {
3652    for (unsigned i = l*NumLaneElts, j = l*NumLaneElts;
3653         i != (l+1)*NumLaneElts;
3654         i += 2, ++j) {
3655      int BitI  = Mask[i];
3656      int BitI1 = Mask[i+1];
3657
3658      if (!isUndefOrEqual(BitI, j))
3659        return false;
3660      if (!isUndefOrEqual(BitI1, j))
3661        return false;
3662    }
3663  }
3664
3665  return true;
3666}
3667
3668/// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
3669/// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
3670/// <2, 2, 3, 3>
3671static bool isUNPCKH_v_undef_Mask(ArrayRef<int> Mask, EVT VT, bool HasAVX2) {
3672  unsigned NumElts = VT.getVectorNumElements();
3673
3674  assert((VT.is128BitVector() || VT.is256BitVector()) &&
3675         "Unsupported vector type for unpckh");
3676
3677  if (VT.getSizeInBits() == 256 && NumElts != 4 && NumElts != 8 &&
3678      (!HasAVX2 || (NumElts != 16 && NumElts != 32)))
3679    return false;
3680
3681  // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3682  // independently on 128-bit lanes.
3683  unsigned NumLanes = VT.getSizeInBits()/128;
3684  unsigned NumLaneElts = NumElts/NumLanes;
3685
3686  for (unsigned l = 0; l != NumLanes; ++l) {
3687    for (unsigned i = l*NumLaneElts, j = (l*NumLaneElts)+NumLaneElts/2;
3688         i != (l+1)*NumLaneElts; i += 2, ++j) {
3689      int BitI  = Mask[i];
3690      int BitI1 = Mask[i+1];
3691      if (!isUndefOrEqual(BitI, j))
3692        return false;
3693      if (!isUndefOrEqual(BitI1, j))
3694        return false;
3695    }
3696  }
3697  return true;
3698}
3699
3700/// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
3701/// specifies a shuffle of elements that is suitable for input to MOVSS,
3702/// MOVSD, and MOVD, i.e. setting the lowest element.
3703static bool isMOVLMask(ArrayRef<int> Mask, EVT VT) {
3704  if (VT.getVectorElementType().getSizeInBits() < 32)
3705    return false;
3706  if (!VT.is128BitVector())
3707    return false;
3708
3709  unsigned NumElts = VT.getVectorNumElements();
3710
3711  if (!isUndefOrEqual(Mask[0], NumElts))
3712    return false;
3713
3714  for (unsigned i = 1; i != NumElts; ++i)
3715    if (!isUndefOrEqual(Mask[i], i))
3716      return false;
3717
3718  return true;
3719}
3720
3721/// isVPERM2X128Mask - Match 256-bit shuffles where the elements are considered
3722/// as permutations between 128-bit chunks or halves. As an example: this
3723/// shuffle bellow:
3724///   vector_shuffle <4, 5, 6, 7, 12, 13, 14, 15>
3725/// The first half comes from the second half of V1 and the second half from the
3726/// the second half of V2.
3727static bool isVPERM2X128Mask(ArrayRef<int> Mask, EVT VT, bool HasAVX) {
3728  if (!HasAVX || !VT.is256BitVector())
3729    return false;
3730
3731  // The shuffle result is divided into half A and half B. In total the two
3732  // sources have 4 halves, namely: C, D, E, F. The final values of A and
3733  // B must come from C, D, E or F.
3734  unsigned HalfSize = VT.getVectorNumElements()/2;
3735  bool MatchA = false, MatchB = false;
3736
3737  // Check if A comes from one of C, D, E, F.
3738  for (unsigned Half = 0; Half != 4; ++Half) {
3739    if (isSequentialOrUndefInRange(Mask, 0, HalfSize, Half*HalfSize)) {
3740      MatchA = true;
3741      break;
3742    }
3743  }
3744
3745  // Check if B comes from one of C, D, E, F.
3746  for (unsigned Half = 0; Half != 4; ++Half) {
3747    if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, Half*HalfSize)) {
3748      MatchB = true;
3749      break;
3750    }
3751  }
3752
3753  return MatchA && MatchB;
3754}
3755
3756/// getShuffleVPERM2X128Immediate - Return the appropriate immediate to shuffle
3757/// the specified VECTOR_MASK mask with VPERM2F128/VPERM2I128 instructions.
3758static unsigned getShuffleVPERM2X128Immediate(ShuffleVectorSDNode *SVOp) {
3759  EVT VT = SVOp->getValueType(0);
3760
3761  unsigned HalfSize = VT.getVectorNumElements()/2;
3762
3763  unsigned FstHalf = 0, SndHalf = 0;
3764  for (unsigned i = 0; i < HalfSize; ++i) {
3765    if (SVOp->getMaskElt(i) > 0) {
3766      FstHalf = SVOp->getMaskElt(i)/HalfSize;
3767      break;
3768    }
3769  }
3770  for (unsigned i = HalfSize; i < HalfSize*2; ++i) {
3771    if (SVOp->getMaskElt(i) > 0) {
3772      SndHalf = SVOp->getMaskElt(i)/HalfSize;
3773      break;
3774    }
3775  }
3776
3777  return (FstHalf | (SndHalf << 4));
3778}
3779
3780/// isVPERMILPMask - Return true if the specified VECTOR_SHUFFLE operand
3781/// specifies a shuffle of elements that is suitable for input to VPERMILPD*.
3782/// Note that VPERMIL mask matching is different depending whether theunderlying
3783/// type is 32 or 64. In the VPERMILPS the high half of the mask should point
3784/// to the same elements of the low, but to the higher half of the source.
3785/// In VPERMILPD the two lanes could be shuffled independently of each other
3786/// with the same restriction that lanes can't be crossed. Also handles PSHUFDY.
3787static bool isVPERMILPMask(ArrayRef<int> Mask, EVT VT, bool HasAVX) {
3788  if (!HasAVX)
3789    return false;
3790
3791  unsigned NumElts = VT.getVectorNumElements();
3792  // Only match 256-bit with 32/64-bit types
3793  if (VT.getSizeInBits() != 256 || (NumElts != 4 && NumElts != 8))
3794    return false;
3795
3796  unsigned NumLanes = VT.getSizeInBits()/128;
3797  unsigned LaneSize = NumElts/NumLanes;
3798  for (unsigned l = 0; l != NumElts; l += LaneSize) {
3799    for (unsigned i = 0; i != LaneSize; ++i) {
3800      if (!isUndefOrInRange(Mask[i+l], l, l+LaneSize))
3801        return false;
3802      if (NumElts != 8 || l == 0)
3803        continue;
3804      // VPERMILPS handling
3805      if (Mask[i] < 0)
3806        continue;
3807      if (!isUndefOrEqual(Mask[i+l], Mask[i]+l))
3808        return false;
3809    }
3810  }
3811
3812  return true;
3813}
3814
3815/// isCommutedMOVLMask - Returns true if the shuffle mask is except the reverse
3816/// of what x86 movss want. X86 movs requires the lowest  element to be lowest
3817/// element of vector 2 and the other elements to come from vector 1 in order.
3818static bool isCommutedMOVLMask(ArrayRef<int> Mask, EVT VT,
3819                               bool V2IsSplat = false, bool V2IsUndef = false) {
3820  if (!VT.is128BitVector())
3821    return false;
3822
3823  unsigned NumOps = VT.getVectorNumElements();
3824  if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
3825    return false;
3826
3827  if (!isUndefOrEqual(Mask[0], 0))
3828    return false;
3829
3830  for (unsigned i = 1; i != NumOps; ++i)
3831    if (!(isUndefOrEqual(Mask[i], i+NumOps) ||
3832          (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) ||
3833          (V2IsSplat && isUndefOrEqual(Mask[i], NumOps))))
3834      return false;
3835
3836  return true;
3837}
3838
3839/// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3840/// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
3841/// Masks to match: <1, 1, 3, 3> or <1, 1, 3, 3, 5, 5, 7, 7>
3842static bool isMOVSHDUPMask(ArrayRef<int> Mask, EVT VT,
3843                           const X86Subtarget *Subtarget) {
3844  if (!Subtarget->hasSSE3())
3845    return false;
3846
3847  unsigned NumElems = VT.getVectorNumElements();
3848
3849  if ((VT.getSizeInBits() == 128 && NumElems != 4) ||
3850      (VT.getSizeInBits() == 256 && NumElems != 8))
3851    return false;
3852
3853  // "i+1" is the value the indexed mask element must have
3854  for (unsigned i = 0; i != NumElems; i += 2)
3855    if (!isUndefOrEqual(Mask[i], i+1) ||
3856        !isUndefOrEqual(Mask[i+1], i+1))
3857      return false;
3858
3859  return true;
3860}
3861
3862/// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3863/// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
3864/// Masks to match: <0, 0, 2, 2> or <0, 0, 2, 2, 4, 4, 6, 6>
3865static bool isMOVSLDUPMask(ArrayRef<int> Mask, EVT VT,
3866                           const X86Subtarget *Subtarget) {
3867  if (!Subtarget->hasSSE3())
3868    return false;
3869
3870  unsigned NumElems = VT.getVectorNumElements();
3871
3872  if ((VT.getSizeInBits() == 128 && NumElems != 4) ||
3873      (VT.getSizeInBits() == 256 && NumElems != 8))
3874    return false;
3875
3876  // "i" is the value the indexed mask element must have
3877  for (unsigned i = 0; i != NumElems; i += 2)
3878    if (!isUndefOrEqual(Mask[i], i) ||
3879        !isUndefOrEqual(Mask[i+1], i))
3880      return false;
3881
3882  return true;
3883}
3884
3885/// isMOVDDUPYMask - Return true if the specified VECTOR_SHUFFLE operand
3886/// specifies a shuffle of elements that is suitable for input to 256-bit
3887/// version of MOVDDUP.
3888static bool isMOVDDUPYMask(ArrayRef<int> Mask, EVT VT, bool HasAVX) {
3889  if (!HasAVX || !VT.is256BitVector())
3890    return false;
3891
3892  unsigned NumElts = VT.getVectorNumElements();
3893  if (NumElts != 4)
3894    return false;
3895
3896  for (unsigned i = 0; i != NumElts/2; ++i)
3897    if (!isUndefOrEqual(Mask[i], 0))
3898      return false;
3899  for (unsigned i = NumElts/2; i != NumElts; ++i)
3900    if (!isUndefOrEqual(Mask[i], NumElts/2))
3901      return false;
3902  return true;
3903}
3904
3905/// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3906/// specifies a shuffle of elements that is suitable for input to 128-bit
3907/// version of MOVDDUP.
3908static bool isMOVDDUPMask(ArrayRef<int> Mask, EVT VT) {
3909  if (!VT.is128BitVector())
3910    return false;
3911
3912  unsigned e = VT.getVectorNumElements() / 2;
3913  for (unsigned i = 0; i != e; ++i)
3914    if (!isUndefOrEqual(Mask[i], i))
3915      return false;
3916  for (unsigned i = 0; i != e; ++i)
3917    if (!isUndefOrEqual(Mask[e+i], i))
3918      return false;
3919  return true;
3920}
3921
3922/// isVEXTRACTF128Index - Return true if the specified
3923/// EXTRACT_SUBVECTOR operand specifies a vector extract that is
3924/// suitable for input to VEXTRACTF128.
3925bool X86::isVEXTRACTF128Index(SDNode *N) {
3926  if (!isa<ConstantSDNode>(N->getOperand(1).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(1).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/// isVINSERTF128Index - Return true if the specified INSERT_SUBVECTOR
3942/// operand specifies a subvector insert that is suitable for input to
3943/// VINSERTF128.
3944bool X86::isVINSERTF128Index(SDNode *N) {
3945  if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
3946    return false;
3947
3948  // The index should be aligned on a 128-bit boundary.
3949  uint64_t Index =
3950    cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
3951
3952  unsigned VL = N->getValueType(0).getVectorNumElements();
3953  unsigned VBits = N->getValueType(0).getSizeInBits();
3954  unsigned ElSize = VBits / VL;
3955  bool Result = (Index * ElSize) % 128 == 0;
3956
3957  return Result;
3958}
3959
3960/// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
3961/// the specified VECTOR_SHUFFLE mask with PSHUF* and SHUFP* instructions.
3962/// Handles 128-bit and 256-bit.
3963static unsigned getShuffleSHUFImmediate(ShuffleVectorSDNode *N) {
3964  EVT VT = N->getValueType(0);
3965
3966  assert((VT.is128BitVector() || VT.is256BitVector()) &&
3967         "Unsupported vector type for PSHUF/SHUFP");
3968
3969  // Handle 128 and 256-bit vector lengths. AVX defines PSHUF/SHUFP to operate
3970  // independently on 128-bit lanes.
3971  unsigned NumElts = VT.getVectorNumElements();
3972  unsigned NumLanes = VT.getSizeInBits()/128;
3973  unsigned NumLaneElts = NumElts/NumLanes;
3974
3975  assert((NumLaneElts == 2 || NumLaneElts == 4) &&
3976         "Only supports 2 or 4 elements per lane");
3977
3978  unsigned Shift = (NumLaneElts == 4) ? 1 : 0;
3979  unsigned Mask = 0;
3980  for (unsigned i = 0; i != NumElts; ++i) {
3981    int Elt = N->getMaskElt(i);
3982    if (Elt < 0) continue;
3983    Elt &= NumLaneElts - 1;
3984    unsigned ShAmt = (i << Shift) % 8;
3985    Mask |= Elt << ShAmt;
3986  }
3987
3988  return Mask;
3989}
3990
3991/// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
3992/// the specified VECTOR_SHUFFLE mask with the PSHUFHW instruction.
3993static unsigned getShufflePSHUFHWImmediate(ShuffleVectorSDNode *N) {
3994  EVT VT = N->getValueType(0);
3995
3996  assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
3997         "Unsupported vector type for PSHUFHW");
3998
3999  unsigned NumElts = VT.getVectorNumElements();
4000
4001  unsigned Mask = 0;
4002  for (unsigned l = 0; l != NumElts; l += 8) {
4003    // 8 nodes per lane, but we only care about the last 4.
4004    for (unsigned i = 0; i < 4; ++i) {
4005      int Elt = N->getMaskElt(l+i+4);
4006      if (Elt < 0) continue;
4007      Elt &= 0x3; // only 2-bits.
4008      Mask |= Elt << (i * 2);
4009    }
4010  }
4011
4012  return Mask;
4013}
4014
4015/// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
4016/// the specified VECTOR_SHUFFLE mask with the PSHUFLW instruction.
4017static unsigned getShufflePSHUFLWImmediate(ShuffleVectorSDNode *N) {
4018  EVT VT = N->getValueType(0);
4019
4020  assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4021         "Unsupported vector type for PSHUFHW");
4022
4023  unsigned NumElts = VT.getVectorNumElements();
4024
4025  unsigned Mask = 0;
4026  for (unsigned l = 0; l != NumElts; l += 8) {
4027    // 8 nodes per lane, but we only care about the first 4.
4028    for (unsigned i = 0; i < 4; ++i) {
4029      int Elt = N->getMaskElt(l+i);
4030      if (Elt < 0) continue;
4031      Elt &= 0x3; // only 2-bits
4032      Mask |= Elt << (i * 2);
4033    }
4034  }
4035
4036  return Mask;
4037}
4038
4039/// getShufflePALIGNRImmediate - Return the appropriate immediate to shuffle
4040/// the specified VECTOR_SHUFFLE mask with the PALIGNR instruction.
4041static unsigned getShufflePALIGNRImmediate(ShuffleVectorSDNode *SVOp) {
4042  EVT VT = SVOp->getValueType(0);
4043  unsigned EltSize = VT.getVectorElementType().getSizeInBits() >> 3;
4044
4045  unsigned NumElts = VT.getVectorNumElements();
4046  unsigned NumLanes = VT.getSizeInBits()/128;
4047  unsigned NumLaneElts = NumElts/NumLanes;
4048
4049  int Val = 0;
4050  unsigned i;
4051  for (i = 0; i != NumElts; ++i) {
4052    Val = SVOp->getMaskElt(i);
4053    if (Val >= 0)
4054      break;
4055  }
4056  if (Val >= (int)NumElts)
4057    Val -= NumElts - NumLaneElts;
4058
4059  assert(Val - i > 0 && "PALIGNR imm should be positive");
4060  return (Val - i) * EltSize;
4061}
4062
4063/// getExtractVEXTRACTF128Immediate - Return the appropriate immediate
4064/// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF128
4065/// instructions.
4066unsigned X86::getExtractVEXTRACTF128Immediate(SDNode *N) {
4067  if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4068    llvm_unreachable("Illegal extract subvector for VEXTRACTF128");
4069
4070  uint64_t Index =
4071    cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4072
4073  EVT VecVT = N->getOperand(0).getValueType();
4074  EVT ElVT = VecVT.getVectorElementType();
4075
4076  unsigned NumElemsPerChunk = 128 / ElVT.getSizeInBits();
4077  return Index / NumElemsPerChunk;
4078}
4079
4080/// getInsertVINSERTF128Immediate - Return the appropriate immediate
4081/// to insert at the specified INSERT_SUBVECTOR index with VINSERTF128
4082/// instructions.
4083unsigned X86::getInsertVINSERTF128Immediate(SDNode *N) {
4084  if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4085    llvm_unreachable("Illegal insert subvector for VINSERTF128");
4086
4087  uint64_t Index =
4088    cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4089
4090  EVT VecVT = N->getValueType(0);
4091  EVT ElVT = VecVT.getVectorElementType();
4092
4093  unsigned NumElemsPerChunk = 128 / ElVT.getSizeInBits();
4094  return Index / NumElemsPerChunk;
4095}
4096
4097/// getShuffleCLImmediate - Return the appropriate immediate to shuffle
4098/// the specified VECTOR_SHUFFLE mask with VPERMQ and VPERMPD instructions.
4099/// Handles 256-bit.
4100static unsigned getShuffleCLImmediate(ShuffleVectorSDNode *N) {
4101  EVT VT = N->getValueType(0);
4102
4103  unsigned NumElts = VT.getVectorNumElements();
4104
4105  assert((VT.is256BitVector() && NumElts == 4) &&
4106         "Unsupported vector type for VPERMQ/VPERMPD");
4107
4108  unsigned Mask = 0;
4109  for (unsigned i = 0; i != NumElts; ++i) {
4110    int Elt = N->getMaskElt(i);
4111    if (Elt < 0)
4112      continue;
4113    Mask |= Elt << (i*2);
4114  }
4115
4116  return Mask;
4117}
4118/// isZeroNode - Returns true if Elt is a constant zero or a floating point
4119/// constant +0.0.
4120bool X86::isZeroNode(SDValue Elt) {
4121  return ((isa<ConstantSDNode>(Elt) &&
4122           cast<ConstantSDNode>(Elt)->isNullValue()) ||
4123          (isa<ConstantFPSDNode>(Elt) &&
4124           cast<ConstantFPSDNode>(Elt)->getValueAPF().isPosZero()));
4125}
4126
4127/// CommuteVectorShuffle - Swap vector_shuffle operands as well as values in
4128/// their permute mask.
4129static SDValue CommuteVectorShuffle(ShuffleVectorSDNode *SVOp,
4130                                    SelectionDAG &DAG) {
4131  EVT VT = SVOp->getValueType(0);
4132  unsigned NumElems = VT.getVectorNumElements();
4133  SmallVector<int, 8> MaskVec;
4134
4135  for (unsigned i = 0; i != NumElems; ++i) {
4136    int Idx = SVOp->getMaskElt(i);
4137    if (Idx >= 0) {
4138      if (Idx < (int)NumElems)
4139        Idx += NumElems;
4140      else
4141        Idx -= NumElems;
4142    }
4143    MaskVec.push_back(Idx);
4144  }
4145  return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(1),
4146                              SVOp->getOperand(0), &MaskVec[0]);
4147}
4148
4149/// ShouldXformToMOVHLPS - Return true if the node should be transformed to
4150/// match movhlps. The lower half elements should come from upper half of
4151/// V1 (and in order), and the upper half elements should come from the upper
4152/// half of V2 (and in order).
4153static bool ShouldXformToMOVHLPS(ArrayRef<int> Mask, EVT VT) {
4154  if (!VT.is128BitVector())
4155    return false;
4156  if (VT.getVectorNumElements() != 4)
4157    return false;
4158  for (unsigned i = 0, e = 2; i != e; ++i)
4159    if (!isUndefOrEqual(Mask[i], i+2))
4160      return false;
4161  for (unsigned i = 2; i != 4; ++i)
4162    if (!isUndefOrEqual(Mask[i], i+4))
4163      return false;
4164  return true;
4165}
4166
4167/// isScalarLoadToVector - Returns true if the node is a scalar load that
4168/// is promoted to a vector. It also returns the LoadSDNode by reference if
4169/// required.
4170static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = NULL) {
4171  if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
4172    return false;
4173  N = N->getOperand(0).getNode();
4174  if (!ISD::isNON_EXTLoad(N))
4175    return false;
4176  if (LD)
4177    *LD = cast<LoadSDNode>(N);
4178  return true;
4179}
4180
4181// Test whether the given value is a vector value which will be legalized
4182// into a load.
4183static bool WillBeConstantPoolLoad(SDNode *N) {
4184  if (N->getOpcode() != ISD::BUILD_VECTOR)
4185    return false;
4186
4187  // Check for any non-constant elements.
4188  for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
4189    switch (N->getOperand(i).getNode()->getOpcode()) {
4190    case ISD::UNDEF:
4191    case ISD::ConstantFP:
4192    case ISD::Constant:
4193      break;
4194    default:
4195      return false;
4196    }
4197
4198  // Vectors of all-zeros and all-ones are materialized with special
4199  // instructions rather than being loaded.
4200  return !ISD::isBuildVectorAllZeros(N) &&
4201         !ISD::isBuildVectorAllOnes(N);
4202}
4203
4204/// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
4205/// match movlp{s|d}. The lower half elements should come from lower half of
4206/// V1 (and in order), and the upper half elements should come from the upper
4207/// half of V2 (and in order). And since V1 will become the source of the
4208/// MOVLP, it must be either a vector load or a scalar load to vector.
4209static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2,
4210                               ArrayRef<int> Mask, EVT VT) {
4211  if (!VT.is128BitVector())
4212    return false;
4213
4214  if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
4215    return false;
4216  // Is V2 is a vector load, don't do this transformation. We will try to use
4217  // load folding shufps op.
4218  if (ISD::isNON_EXTLoad(V2) || WillBeConstantPoolLoad(V2))
4219    return false;
4220
4221  unsigned NumElems = VT.getVectorNumElements();
4222
4223  if (NumElems != 2 && NumElems != 4)
4224    return false;
4225  for (unsigned i = 0, e = NumElems/2; i != e; ++i)
4226    if (!isUndefOrEqual(Mask[i], i))
4227      return false;
4228  for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
4229    if (!isUndefOrEqual(Mask[i], i+NumElems))
4230      return false;
4231  return true;
4232}
4233
4234/// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
4235/// all the same.
4236static bool isSplatVector(SDNode *N) {
4237  if (N->getOpcode() != ISD::BUILD_VECTOR)
4238    return false;
4239
4240  SDValue SplatValue = N->getOperand(0);
4241  for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
4242    if (N->getOperand(i) != SplatValue)
4243      return false;
4244  return true;
4245}
4246
4247/// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
4248/// to an zero vector.
4249/// FIXME: move to dag combiner / method on ShuffleVectorSDNode
4250static bool isZeroShuffle(ShuffleVectorSDNode *N) {
4251  SDValue V1 = N->getOperand(0);
4252  SDValue V2 = N->getOperand(1);
4253  unsigned NumElems = N->getValueType(0).getVectorNumElements();
4254  for (unsigned i = 0; i != NumElems; ++i) {
4255    int Idx = N->getMaskElt(i);
4256    if (Idx >= (int)NumElems) {
4257      unsigned Opc = V2.getOpcode();
4258      if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
4259        continue;
4260      if (Opc != ISD::BUILD_VECTOR ||
4261          !X86::isZeroNode(V2.getOperand(Idx-NumElems)))
4262        return false;
4263    } else if (Idx >= 0) {
4264      unsigned Opc = V1.getOpcode();
4265      if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
4266        continue;
4267      if (Opc != ISD::BUILD_VECTOR ||
4268          !X86::isZeroNode(V1.getOperand(Idx)))
4269        return false;
4270    }
4271  }
4272  return true;
4273}
4274
4275/// getZeroVector - Returns a vector of specified type with all zero elements.
4276///
4277static SDValue getZeroVector(EVT VT, const X86Subtarget *Subtarget,
4278                             SelectionDAG &DAG, DebugLoc dl) {
4279  assert(VT.isVector() && "Expected a vector type");
4280  unsigned Size = VT.getSizeInBits();
4281
4282  // Always build SSE zero vectors as <4 x i32> bitcasted
4283  // to their dest type. This ensures they get CSE'd.
4284  SDValue Vec;
4285  if (Size == 128) {  // SSE
4286    if (Subtarget->hasSSE2()) {  // SSE2
4287      SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4288      Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4289    } else { // SSE1
4290      SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4291      Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
4292    }
4293  } else if (Size == 256) { // AVX
4294    if (Subtarget->hasAVX2()) { // AVX2
4295      SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4296      SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4297      Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops, 8);
4298    } else {
4299      // 256-bit logic and arithmetic instructions in AVX are all
4300      // floating-point, no support for integer ops. Emit fp zeroed vectors.
4301      SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4302      SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4303      Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops, 8);
4304    }
4305  } else
4306    llvm_unreachable("Unexpected vector type");
4307
4308  return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4309}
4310
4311/// getOnesVector - Returns a vector of specified type with all bits set.
4312/// Always build ones vectors as <4 x i32> or <8 x i32>. For 256-bit types with
4313/// no AVX2 supprt, use two <4 x i32> inserted in a <8 x i32> appropriately.
4314/// Then bitcast to their original type, ensuring they get CSE'd.
4315static SDValue getOnesVector(EVT VT, bool HasAVX2, SelectionDAG &DAG,
4316                             DebugLoc dl) {
4317  assert(VT.isVector() && "Expected a vector type");
4318  unsigned Size = VT.getSizeInBits();
4319
4320  SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
4321  SDValue Vec;
4322  if (Size == 256) {
4323    if (HasAVX2) { // AVX2
4324      SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4325      Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops, 8);
4326    } else { // AVX
4327      Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4328      Vec = Concat128BitVectors(Vec, Vec, MVT::v8i32, 8, DAG, dl);
4329    }
4330  } else if (Size == 128) {
4331    Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4332  } else
4333    llvm_unreachable("Unexpected vector type");
4334
4335  return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4336}
4337
4338/// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
4339/// that point to V2 points to its first element.
4340static void NormalizeMask(SmallVectorImpl<int> &Mask, unsigned NumElems) {
4341  for (unsigned i = 0; i != NumElems; ++i) {
4342    if (Mask[i] > (int)NumElems) {
4343      Mask[i] = NumElems;
4344    }
4345  }
4346}
4347
4348/// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
4349/// operation of specified width.
4350static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
4351                       SDValue V2) {
4352  unsigned NumElems = VT.getVectorNumElements();
4353  SmallVector<int, 8> Mask;
4354  Mask.push_back(NumElems);
4355  for (unsigned i = 1; i != NumElems; ++i)
4356    Mask.push_back(i);
4357  return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4358}
4359
4360/// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
4361static SDValue getUnpackl(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
4362                          SDValue V2) {
4363  unsigned NumElems = VT.getVectorNumElements();
4364  SmallVector<int, 8> Mask;
4365  for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
4366    Mask.push_back(i);
4367    Mask.push_back(i + NumElems);
4368  }
4369  return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4370}
4371
4372/// getUnpackh - Returns a vector_shuffle node for an unpackh operation.
4373static SDValue getUnpackh(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
4374                          SDValue V2) {
4375  unsigned NumElems = VT.getVectorNumElements();
4376  SmallVector<int, 8> Mask;
4377  for (unsigned i = 0, Half = NumElems/2; i != Half; ++i) {
4378    Mask.push_back(i + Half);
4379    Mask.push_back(i + NumElems + Half);
4380  }
4381  return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4382}
4383
4384// PromoteSplati8i16 - All i16 and i8 vector types can't be used directly by
4385// a generic shuffle instruction because the target has no such instructions.
4386// Generate shuffles which repeat i16 and i8 several times until they can be
4387// represented by v4f32 and then be manipulated by target suported shuffles.
4388static SDValue PromoteSplati8i16(SDValue V, SelectionDAG &DAG, int &EltNo) {
4389  EVT VT = V.getValueType();
4390  int NumElems = VT.getVectorNumElements();
4391  DebugLoc dl = V.getDebugLoc();
4392
4393  while (NumElems > 4) {
4394    if (EltNo < NumElems/2) {
4395      V = getUnpackl(DAG, dl, VT, V, V);
4396    } else {
4397      V = getUnpackh(DAG, dl, VT, V, V);
4398      EltNo -= NumElems/2;
4399    }
4400    NumElems >>= 1;
4401  }
4402  return V;
4403}
4404
4405/// getLegalSplat - Generate a legal splat with supported x86 shuffles
4406static SDValue getLegalSplat(SelectionDAG &DAG, SDValue V, int EltNo) {
4407  EVT VT = V.getValueType();
4408  DebugLoc dl = V.getDebugLoc();
4409  unsigned Size = VT.getSizeInBits();
4410
4411  if (Size == 128) {
4412    V = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V);
4413    int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo };
4414    V = DAG.getVectorShuffle(MVT::v4f32, dl, V, DAG.getUNDEF(MVT::v4f32),
4415                             &SplatMask[0]);
4416  } else if (Size == 256) {
4417    // To use VPERMILPS to splat scalars, the second half of indicies must
4418    // refer to the higher part, which is a duplication of the lower one,
4419    // because VPERMILPS can only handle in-lane permutations.
4420    int SplatMask[8] = { EltNo, EltNo, EltNo, EltNo,
4421                         EltNo+4, EltNo+4, EltNo+4, EltNo+4 };
4422
4423    V = DAG.getNode(ISD::BITCAST, dl, MVT::v8f32, V);
4424    V = DAG.getVectorShuffle(MVT::v8f32, dl, V, DAG.getUNDEF(MVT::v8f32),
4425                             &SplatMask[0]);
4426  } else
4427    llvm_unreachable("Vector size not supported");
4428
4429  return DAG.getNode(ISD::BITCAST, dl, VT, V);
4430}
4431
4432/// PromoteSplat - Splat is promoted to target supported vector shuffles.
4433static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG) {
4434  EVT SrcVT = SV->getValueType(0);
4435  SDValue V1 = SV->getOperand(0);
4436  DebugLoc dl = SV->getDebugLoc();
4437
4438  int EltNo = SV->getSplatIndex();
4439  int NumElems = SrcVT.getVectorNumElements();
4440  unsigned Size = SrcVT.getSizeInBits();
4441
4442  assert(((Size == 128 && NumElems > 4) || Size == 256) &&
4443          "Unknown how to promote splat for type");
4444
4445  // Extract the 128-bit part containing the splat element and update
4446  // the splat element index when it refers to the higher register.
4447  if (Size == 256) {
4448    V1 = Extract128BitVector(V1, EltNo, DAG, dl);
4449    if (EltNo >= NumElems/2)
4450      EltNo -= NumElems/2;
4451  }
4452
4453  // All i16 and i8 vector types can't be used directly by a generic shuffle
4454  // instruction because the target has no such instruction. Generate shuffles
4455  // which repeat i16 and i8 several times until they fit in i32, and then can
4456  // be manipulated by target suported shuffles.
4457  EVT EltVT = SrcVT.getVectorElementType();
4458  if (EltVT == MVT::i8 || EltVT == MVT::i16)
4459    V1 = PromoteSplati8i16(V1, DAG, EltNo);
4460
4461  // Recreate the 256-bit vector and place the same 128-bit vector
4462  // into the low and high part. This is necessary because we want
4463  // to use VPERM* to shuffle the vectors
4464  if (Size == 256) {
4465    V1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, SrcVT, V1, V1);
4466  }
4467
4468  return getLegalSplat(DAG, V1, EltNo);
4469}
4470
4471/// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
4472/// vector of zero or undef vector.  This produces a shuffle where the low
4473/// element of V2 is swizzled into the zero/undef vector, landing at element
4474/// Idx.  This produces a shuffle mask like 4,1,2,3 (idx=0) or  0,1,2,4 (idx=3).
4475static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
4476                                           bool IsZero,
4477                                           const X86Subtarget *Subtarget,
4478                                           SelectionDAG &DAG) {
4479  EVT VT = V2.getValueType();
4480  SDValue V1 = IsZero
4481    ? getZeroVector(VT, Subtarget, DAG, V2.getDebugLoc()) : DAG.getUNDEF(VT);
4482  unsigned NumElems = VT.getVectorNumElements();
4483  SmallVector<int, 16> MaskVec;
4484  for (unsigned i = 0; i != NumElems; ++i)
4485    // If this is the insertion idx, put the low elt of V2 here.
4486    MaskVec.push_back(i == Idx ? NumElems : i);
4487  return DAG.getVectorShuffle(VT, V2.getDebugLoc(), V1, V2, &MaskVec[0]);
4488}
4489
4490/// getTargetShuffleMask - Calculates the shuffle mask corresponding to the
4491/// target specific opcode. Returns true if the Mask could be calculated.
4492/// Sets IsUnary to true if only uses one source.
4493static bool getTargetShuffleMask(SDNode *N, MVT VT,
4494                                 SmallVectorImpl<int> &Mask, bool &IsUnary) {
4495  unsigned NumElems = VT.getVectorNumElements();
4496  SDValue ImmN;
4497
4498  IsUnary = false;
4499  switch(N->getOpcode()) {
4500  case X86ISD::SHUFP:
4501    ImmN = N->getOperand(N->getNumOperands()-1);
4502    DecodeSHUFPMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4503    break;
4504  case X86ISD::UNPCKH:
4505    DecodeUNPCKHMask(VT, Mask);
4506    break;
4507  case X86ISD::UNPCKL:
4508    DecodeUNPCKLMask(VT, Mask);
4509    break;
4510  case X86ISD::MOVHLPS:
4511    DecodeMOVHLPSMask(NumElems, Mask);
4512    break;
4513  case X86ISD::MOVLHPS:
4514    DecodeMOVLHPSMask(NumElems, Mask);
4515    break;
4516  case X86ISD::PSHUFD:
4517  case X86ISD::VPERMILP:
4518    ImmN = N->getOperand(N->getNumOperands()-1);
4519    DecodePSHUFMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4520    IsUnary = true;
4521    break;
4522  case X86ISD::PSHUFHW:
4523    ImmN = N->getOperand(N->getNumOperands()-1);
4524    DecodePSHUFHWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4525    IsUnary = true;
4526    break;
4527  case X86ISD::PSHUFLW:
4528    ImmN = N->getOperand(N->getNumOperands()-1);
4529    DecodePSHUFLWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4530    IsUnary = true;
4531    break;
4532  case X86ISD::VPERMI:
4533    ImmN = N->getOperand(N->getNumOperands()-1);
4534    DecodeVPERMMask(cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4535    IsUnary = true;
4536    break;
4537  case X86ISD::MOVSS:
4538  case X86ISD::MOVSD: {
4539    // The index 0 always comes from the first element of the second source,
4540    // this is why MOVSS and MOVSD are used in the first place. The other
4541    // elements come from the other positions of the first source vector
4542    Mask.push_back(NumElems);
4543    for (unsigned i = 1; i != NumElems; ++i) {
4544      Mask.push_back(i);
4545    }
4546    break;
4547  }
4548  case X86ISD::VPERM2X128:
4549    ImmN = N->getOperand(N->getNumOperands()-1);
4550    DecodeVPERM2X128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4551    if (Mask.empty()) return false;
4552    break;
4553  case X86ISD::MOVDDUP:
4554  case X86ISD::MOVLHPD:
4555  case X86ISD::MOVLPD:
4556  case X86ISD::MOVLPS:
4557  case X86ISD::MOVSHDUP:
4558  case X86ISD::MOVSLDUP:
4559  case X86ISD::PALIGN:
4560    // Not yet implemented
4561    return false;
4562  default: llvm_unreachable("unknown target shuffle node");
4563  }
4564
4565  return true;
4566}
4567
4568/// getShuffleScalarElt - Returns the scalar element that will make up the ith
4569/// element of the result of the vector shuffle.
4570static SDValue getShuffleScalarElt(SDNode *N, unsigned Index, SelectionDAG &DAG,
4571                                   unsigned Depth) {
4572  if (Depth == 6)
4573    return SDValue();  // Limit search depth.
4574
4575  SDValue V = SDValue(N, 0);
4576  EVT VT = V.getValueType();
4577  unsigned Opcode = V.getOpcode();
4578
4579  // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
4580  if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
4581    int Elt = SV->getMaskElt(Index);
4582
4583    if (Elt < 0)
4584      return DAG.getUNDEF(VT.getVectorElementType());
4585
4586    unsigned NumElems = VT.getVectorNumElements();
4587    SDValue NewV = (Elt < (int)NumElems) ? SV->getOperand(0)
4588                                         : SV->getOperand(1);
4589    return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG, Depth+1);
4590  }
4591
4592  // Recurse into target specific vector shuffles to find scalars.
4593  if (isTargetShuffle(Opcode)) {
4594    MVT ShufVT = V.getValueType().getSimpleVT();
4595    unsigned NumElems = ShufVT.getVectorNumElements();
4596    SmallVector<int, 16> ShuffleMask;
4597    SDValue ImmN;
4598    bool IsUnary;
4599
4600    if (!getTargetShuffleMask(N, ShufVT, ShuffleMask, IsUnary))
4601      return SDValue();
4602
4603    int Elt = ShuffleMask[Index];
4604    if (Elt < 0)
4605      return DAG.getUNDEF(ShufVT.getVectorElementType());
4606
4607    SDValue NewV = (Elt < (int)NumElems) ? N->getOperand(0)
4608                                         : N->getOperand(1);
4609    return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG,
4610                               Depth+1);
4611  }
4612
4613  // Actual nodes that may contain scalar elements
4614  if (Opcode == ISD::BITCAST) {
4615    V = V.getOperand(0);
4616    EVT SrcVT = V.getValueType();
4617    unsigned NumElems = VT.getVectorNumElements();
4618
4619    if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
4620      return SDValue();
4621  }
4622
4623  if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
4624    return (Index == 0) ? V.getOperand(0)
4625                        : DAG.getUNDEF(VT.getVectorElementType());
4626
4627  if (V.getOpcode() == ISD::BUILD_VECTOR)
4628    return V.getOperand(Index);
4629
4630  return SDValue();
4631}
4632
4633/// getNumOfConsecutiveZeros - Return the number of elements of a vector
4634/// shuffle operation which come from a consecutively from a zero. The
4635/// search can start in two different directions, from left or right.
4636static
4637unsigned getNumOfConsecutiveZeros(ShuffleVectorSDNode *SVOp, unsigned NumElems,
4638                                  bool ZerosFromLeft, SelectionDAG &DAG) {
4639  unsigned i;
4640  for (i = 0; i != NumElems; ++i) {
4641    unsigned Index = ZerosFromLeft ? i : NumElems-i-1;
4642    SDValue Elt = getShuffleScalarElt(SVOp, Index, DAG, 0);
4643    if (!(Elt.getNode() &&
4644         (Elt.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elt))))
4645      break;
4646  }
4647
4648  return i;
4649}
4650
4651/// isShuffleMaskConsecutive - Check if the shuffle mask indicies [MaskI, MaskE)
4652/// correspond consecutively to elements from one of the vector operands,
4653/// starting from its index OpIdx. Also tell OpNum which source vector operand.
4654static
4655bool isShuffleMaskConsecutive(ShuffleVectorSDNode *SVOp,
4656                              unsigned MaskI, unsigned MaskE, unsigned OpIdx,
4657                              unsigned NumElems, unsigned &OpNum) {
4658  bool SeenV1 = false;
4659  bool SeenV2 = false;
4660
4661  for (unsigned i = MaskI; i != MaskE; ++i, ++OpIdx) {
4662    int Idx = SVOp->getMaskElt(i);
4663    // Ignore undef indicies
4664    if (Idx < 0)
4665      continue;
4666
4667    if (Idx < (int)NumElems)
4668      SeenV1 = true;
4669    else
4670      SeenV2 = true;
4671
4672    // Only accept consecutive elements from the same vector
4673    if ((Idx % NumElems != OpIdx) || (SeenV1 && SeenV2))
4674      return false;
4675  }
4676
4677  OpNum = SeenV1 ? 0 : 1;
4678  return true;
4679}
4680
4681/// isVectorShiftRight - Returns true if the shuffle can be implemented as a
4682/// logical left shift of a vector.
4683static bool isVectorShiftRight(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4684                               bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4685  unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
4686  unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems,
4687              false /* check zeros from right */, DAG);
4688  unsigned OpSrc;
4689
4690  if (!NumZeros)
4691    return false;
4692
4693  // Considering the elements in the mask that are not consecutive zeros,
4694  // check if they consecutively come from only one of the source vectors.
4695  //
4696  //               V1 = {X, A, B, C}     0
4697  //                         \  \  \    /
4698  //   vector_shuffle V1, V2 <1, 2, 3, X>
4699  //
4700  if (!isShuffleMaskConsecutive(SVOp,
4701            0,                   // Mask Start Index
4702            NumElems-NumZeros,   // Mask End Index(exclusive)
4703            NumZeros,            // Where to start looking in the src vector
4704            NumElems,            // Number of elements in vector
4705            OpSrc))              // Which source operand ?
4706    return false;
4707
4708  isLeft = false;
4709  ShAmt = NumZeros;
4710  ShVal = SVOp->getOperand(OpSrc);
4711  return true;
4712}
4713
4714/// isVectorShiftLeft - Returns true if the shuffle can be implemented as a
4715/// logical left shift of a vector.
4716static bool isVectorShiftLeft(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4717                              bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4718  unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
4719  unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems,
4720              true /* check zeros from left */, DAG);
4721  unsigned OpSrc;
4722
4723  if (!NumZeros)
4724    return false;
4725
4726  // Considering the elements in the mask that are not consecutive zeros,
4727  // check if they consecutively come from only one of the source vectors.
4728  //
4729  //                           0    { A, B, X, X } = V2
4730  //                          / \    /  /
4731  //   vector_shuffle V1, V2 <X, X, 4, 5>
4732  //
4733  if (!isShuffleMaskConsecutive(SVOp,
4734            NumZeros,     // Mask Start Index
4735            NumElems,     // Mask End Index(exclusive)
4736            0,            // Where to start looking in the src vector
4737            NumElems,     // Number of elements in vector
4738            OpSrc))       // Which source operand ?
4739    return false;
4740
4741  isLeft = true;
4742  ShAmt = NumZeros;
4743  ShVal = SVOp->getOperand(OpSrc);
4744  return true;
4745}
4746
4747/// isVectorShift - Returns true if the shuffle can be implemented as a
4748/// logical left or right shift of a vector.
4749static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4750                          bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4751  // Although the logic below support any bitwidth size, there are no
4752  // shift instructions which handle more than 128-bit vectors.
4753  if (!SVOp->getValueType(0).is128BitVector())
4754    return false;
4755
4756  if (isVectorShiftLeft(SVOp, DAG, isLeft, ShVal, ShAmt) ||
4757      isVectorShiftRight(SVOp, DAG, isLeft, ShVal, ShAmt))
4758    return true;
4759
4760  return false;
4761}
4762
4763/// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
4764///
4765static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
4766                                       unsigned NumNonZero, unsigned NumZero,
4767                                       SelectionDAG &DAG,
4768                                       const X86Subtarget* Subtarget,
4769                                       const TargetLowering &TLI) {
4770  if (NumNonZero > 8)
4771    return SDValue();
4772
4773  DebugLoc dl = Op.getDebugLoc();
4774  SDValue V(0, 0);
4775  bool First = true;
4776  for (unsigned i = 0; i < 16; ++i) {
4777    bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
4778    if (ThisIsNonZero && First) {
4779      if (NumZero)
4780        V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
4781      else
4782        V = DAG.getUNDEF(MVT::v8i16);
4783      First = false;
4784    }
4785
4786    if ((i & 1) != 0) {
4787      SDValue ThisElt(0, 0), LastElt(0, 0);
4788      bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
4789      if (LastIsNonZero) {
4790        LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
4791                              MVT::i16, Op.getOperand(i-1));
4792      }
4793      if (ThisIsNonZero) {
4794        ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
4795        ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
4796                              ThisElt, DAG.getConstant(8, MVT::i8));
4797        if (LastIsNonZero)
4798          ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
4799      } else
4800        ThisElt = LastElt;
4801
4802      if (ThisElt.getNode())
4803        V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
4804                        DAG.getIntPtrConstant(i/2));
4805    }
4806  }
4807
4808  return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V);
4809}
4810
4811/// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
4812///
4813static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
4814                                     unsigned NumNonZero, unsigned NumZero,
4815                                     SelectionDAG &DAG,
4816                                     const X86Subtarget* Subtarget,
4817                                     const TargetLowering &TLI) {
4818  if (NumNonZero > 4)
4819    return SDValue();
4820
4821  DebugLoc dl = Op.getDebugLoc();
4822  SDValue V(0, 0);
4823  bool First = true;
4824  for (unsigned i = 0; i < 8; ++i) {
4825    bool isNonZero = (NonZeros & (1 << i)) != 0;
4826    if (isNonZero) {
4827      if (First) {
4828        if (NumZero)
4829          V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
4830        else
4831          V = DAG.getUNDEF(MVT::v8i16);
4832        First = false;
4833      }
4834      V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
4835                      MVT::v8i16, V, Op.getOperand(i),
4836                      DAG.getIntPtrConstant(i));
4837    }
4838  }
4839
4840  return V;
4841}
4842
4843/// getVShift - Return a vector logical shift node.
4844///
4845static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
4846                         unsigned NumBits, SelectionDAG &DAG,
4847                         const TargetLowering &TLI, DebugLoc dl) {
4848  assert(VT.is128BitVector() && "Unknown type for VShift");
4849  EVT ShVT = MVT::v2i64;
4850  unsigned Opc = isLeft ? X86ISD::VSHLDQ : X86ISD::VSRLDQ;
4851  SrcOp = DAG.getNode(ISD::BITCAST, dl, ShVT, SrcOp);
4852  return DAG.getNode(ISD::BITCAST, dl, VT,
4853                     DAG.getNode(Opc, dl, ShVT, SrcOp,
4854                             DAG.getConstant(NumBits,
4855                                  TLI.getShiftAmountTy(SrcOp.getValueType()))));
4856}
4857
4858SDValue
4859X86TargetLowering::LowerAsSplatVectorLoad(SDValue SrcOp, EVT VT, DebugLoc dl,
4860                                          SelectionDAG &DAG) const {
4861
4862  // Check if the scalar load can be widened into a vector load. And if
4863  // the address is "base + cst" see if the cst can be "absorbed" into
4864  // the shuffle mask.
4865  if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
4866    SDValue Ptr = LD->getBasePtr();
4867    if (!ISD::isNormalLoad(LD) || LD->isVolatile())
4868      return SDValue();
4869    EVT PVT = LD->getValueType(0);
4870    if (PVT != MVT::i32 && PVT != MVT::f32)
4871      return SDValue();
4872
4873    int FI = -1;
4874    int64_t Offset = 0;
4875    if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
4876      FI = FINode->getIndex();
4877      Offset = 0;
4878    } else if (DAG.isBaseWithConstantOffset(Ptr) &&
4879               isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
4880      FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
4881      Offset = Ptr.getConstantOperandVal(1);
4882      Ptr = Ptr.getOperand(0);
4883    } else {
4884      return SDValue();
4885    }
4886
4887    // FIXME: 256-bit vector instructions don't require a strict alignment,
4888    // improve this code to support it better.
4889    unsigned RequiredAlign = VT.getSizeInBits()/8;
4890    SDValue Chain = LD->getChain();
4891    // Make sure the stack object alignment is at least 16 or 32.
4892    MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
4893    if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
4894      if (MFI->isFixedObjectIndex(FI)) {
4895        // Can't change the alignment. FIXME: It's possible to compute
4896        // the exact stack offset and reference FI + adjust offset instead.
4897        // If someone *really* cares about this. That's the way to implement it.
4898        return SDValue();
4899      } else {
4900        MFI->setObjectAlignment(FI, RequiredAlign);
4901      }
4902    }
4903
4904    // (Offset % 16 or 32) must be multiple of 4. Then address is then
4905    // Ptr + (Offset & ~15).
4906    if (Offset < 0)
4907      return SDValue();
4908    if ((Offset % RequiredAlign) & 3)
4909      return SDValue();
4910    int64_t StartOffset = Offset & ~(RequiredAlign-1);
4911    if (StartOffset)
4912      Ptr = DAG.getNode(ISD::ADD, Ptr.getDebugLoc(), Ptr.getValueType(),
4913                        Ptr,DAG.getConstant(StartOffset, Ptr.getValueType()));
4914
4915    int EltNo = (Offset - StartOffset) >> 2;
4916    unsigned NumElems = VT.getVectorNumElements();
4917
4918    EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
4919    SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
4920                             LD->getPointerInfo().getWithOffset(StartOffset),
4921                             false, false, false, 0);
4922
4923    SmallVector<int, 8> Mask;
4924    for (unsigned i = 0; i != NumElems; ++i)
4925      Mask.push_back(EltNo);
4926
4927    return DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &Mask[0]);
4928  }
4929
4930  return SDValue();
4931}
4932
4933/// EltsFromConsecutiveLoads - Given the initializing elements 'Elts' of a
4934/// vector of type 'VT', see if the elements can be replaced by a single large
4935/// load which has the same value as a build_vector whose operands are 'elts'.
4936///
4937/// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
4938///
4939/// FIXME: we'd also like to handle the case where the last elements are zero
4940/// rather than undef via VZEXT_LOAD, but we do not detect that case today.
4941/// There's even a handy isZeroNode for that purpose.
4942static SDValue EltsFromConsecutiveLoads(EVT VT, SmallVectorImpl<SDValue> &Elts,
4943                                        DebugLoc &DL, SelectionDAG &DAG) {
4944  EVT EltVT = VT.getVectorElementType();
4945  unsigned NumElems = Elts.size();
4946
4947  LoadSDNode *LDBase = NULL;
4948  unsigned LastLoadedElt = -1U;
4949
4950  // For each element in the initializer, see if we've found a load or an undef.
4951  // If we don't find an initial load element, or later load elements are
4952  // non-consecutive, bail out.
4953  for (unsigned i = 0; i < NumElems; ++i) {
4954    SDValue Elt = Elts[i];
4955
4956    if (!Elt.getNode() ||
4957        (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
4958      return SDValue();
4959    if (!LDBase) {
4960      if (Elt.getNode()->getOpcode() == ISD::UNDEF)
4961        return SDValue();
4962      LDBase = cast<LoadSDNode>(Elt.getNode());
4963      LastLoadedElt = i;
4964      continue;
4965    }
4966    if (Elt.getOpcode() == ISD::UNDEF)
4967      continue;
4968
4969    LoadSDNode *LD = cast<LoadSDNode>(Elt);
4970    if (!DAG.isConsecutiveLoad(LD, LDBase, EltVT.getSizeInBits()/8, i))
4971      return SDValue();
4972    LastLoadedElt = i;
4973  }
4974
4975  // If we have found an entire vector of loads and undefs, then return a large
4976  // load of the entire vector width starting at the base pointer.  If we found
4977  // consecutive loads for the low half, generate a vzext_load node.
4978  if (LastLoadedElt == NumElems - 1) {
4979    if (DAG.InferPtrAlignment(LDBase->getBasePtr()) >= 16)
4980      return DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
4981                         LDBase->getPointerInfo(),
4982                         LDBase->isVolatile(), LDBase->isNonTemporal(),
4983                         LDBase->isInvariant(), 0);
4984    return DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
4985                       LDBase->getPointerInfo(),
4986                       LDBase->isVolatile(), LDBase->isNonTemporal(),
4987                       LDBase->isInvariant(), LDBase->getAlignment());
4988  }
4989  if (NumElems == 4 && LastLoadedElt == 1 &&
4990      DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) {
4991    SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
4992    SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
4993    SDValue ResNode =
4994        DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops, 2, MVT::i64,
4995                                LDBase->getPointerInfo(),
4996                                LDBase->getAlignment(),
4997                                false/*isVolatile*/, true/*ReadMem*/,
4998                                false/*WriteMem*/);
4999
5000    // Make sure the newly-created LOAD is in the same position as LDBase in
5001    // terms of dependency. We create a TokenFactor for LDBase and ResNode, and
5002    // update uses of LDBase's output chain to use the TokenFactor.
5003    if (LDBase->hasAnyUseOfValue(1)) {
5004      SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5005                             SDValue(LDBase, 1), SDValue(ResNode.getNode(), 1));
5006      DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5007      DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5008                             SDValue(ResNode.getNode(), 1));
5009    }
5010
5011    return DAG.getNode(ISD::BITCAST, DL, VT, ResNode);
5012  }
5013  return SDValue();
5014}
5015
5016/// LowerVectorBroadcast - Attempt to use the vbroadcast instruction
5017/// to generate a splat value for the following cases:
5018/// 1. A splat BUILD_VECTOR which uses a single scalar load, or a constant.
5019/// 2. A splat shuffle which uses a scalar_to_vector node which comes from
5020/// a scalar load, or a constant.
5021/// The VBROADCAST node is returned when a pattern is found,
5022/// or SDValue() otherwise.
5023SDValue
5024X86TargetLowering::LowerVectorBroadcast(SDValue &Op, SelectionDAG &DAG) const {
5025  if (!Subtarget->hasAVX())
5026    return SDValue();
5027
5028  EVT VT = Op.getValueType();
5029  DebugLoc dl = Op.getDebugLoc();
5030
5031  assert((VT.is128BitVector() || VT.is256BitVector()) &&
5032         "Unsupported vector type for broadcast.");
5033
5034  SDValue Ld;
5035  bool ConstSplatVal;
5036
5037  switch (Op.getOpcode()) {
5038    default:
5039      // Unknown pattern found.
5040      return SDValue();
5041
5042    case ISD::BUILD_VECTOR: {
5043      // The BUILD_VECTOR node must be a splat.
5044      if (!isSplatVector(Op.getNode()))
5045        return SDValue();
5046
5047      Ld = Op.getOperand(0);
5048      ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5049                     Ld.getOpcode() == ISD::ConstantFP);
5050
5051      // The suspected load node has several users. Make sure that all
5052      // of its users are from the BUILD_VECTOR node.
5053      // Constants may have multiple users.
5054      if (!ConstSplatVal && !Ld->hasNUsesOfValue(VT.getVectorNumElements(), 0))
5055        return SDValue();
5056      break;
5057    }
5058
5059    case ISD::VECTOR_SHUFFLE: {
5060      ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5061
5062      // Shuffles must have a splat mask where the first element is
5063      // broadcasted.
5064      if ((!SVOp->isSplat()) || SVOp->getMaskElt(0) != 0)
5065        return SDValue();
5066
5067      SDValue Sc = Op.getOperand(0);
5068      if (Sc.getOpcode() != ISD::SCALAR_TO_VECTOR &&
5069          Sc.getOpcode() != ISD::BUILD_VECTOR) {
5070
5071        if (!Subtarget->hasAVX2())
5072          return SDValue();
5073
5074        // Use the register form of the broadcast instruction available on AVX2.
5075        if (VT.is256BitVector())
5076          Sc = Extract128BitVector(Sc, 0, DAG, dl);
5077        return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Sc);
5078      }
5079
5080      Ld = Sc.getOperand(0);
5081      ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5082                       Ld.getOpcode() == ISD::ConstantFP);
5083
5084      // The scalar_to_vector node and the suspected
5085      // load node must have exactly one user.
5086      // Constants may have multiple users.
5087      if (!ConstSplatVal && (!Sc.hasOneUse() || !Ld.hasOneUse()))
5088        return SDValue();
5089      break;
5090    }
5091  }
5092
5093  bool Is256 = VT.is256BitVector();
5094
5095  // Handle the broadcasting a single constant scalar from the constant pool
5096  // into a vector. On Sandybridge it is still better to load a constant vector
5097  // from the constant pool and not to broadcast it from a scalar.
5098  if (ConstSplatVal && Subtarget->hasAVX2()) {
5099    EVT CVT = Ld.getValueType();
5100    assert(!CVT.isVector() && "Must not broadcast a vector type");
5101    unsigned ScalarSize = CVT.getSizeInBits();
5102
5103    if (ScalarSize == 32 || (Is256 && ScalarSize == 64)) {
5104      const Constant *C = 0;
5105      if (ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Ld))
5106        C = CI->getConstantIntValue();
5107      else if (ConstantFPSDNode *CF = dyn_cast<ConstantFPSDNode>(Ld))
5108        C = CF->getConstantFPValue();
5109
5110      assert(C && "Invalid constant type");
5111
5112      SDValue CP = DAG.getConstantPool(C, getPointerTy());
5113      unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
5114      Ld = DAG.getLoad(CVT, dl, DAG.getEntryNode(), CP,
5115                       MachinePointerInfo::getConstantPool(),
5116                       false, false, false, Alignment);
5117
5118      return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5119    }
5120  }
5121
5122  bool IsLoad = ISD::isNormalLoad(Ld.getNode());
5123  unsigned ScalarSize = Ld.getValueType().getSizeInBits();
5124
5125  // Handle AVX2 in-register broadcasts.
5126  if (!IsLoad && Subtarget->hasAVX2() &&
5127      (ScalarSize == 32 || (Is256 && ScalarSize == 64)))
5128    return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5129
5130  // The scalar source must be a normal load.
5131  if (!IsLoad)
5132    return SDValue();
5133
5134  if (ScalarSize == 32 || (Is256 && ScalarSize == 64))
5135    return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5136
5137  // The integer check is needed for the 64-bit into 128-bit so it doesn't match
5138  // double since there is no vbroadcastsd xmm
5139  if (Subtarget->hasAVX2() && Ld.getValueType().isInteger()) {
5140    if (ScalarSize == 8 || ScalarSize == 16 || ScalarSize == 64)
5141      return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5142  }
5143
5144  // Unsupported broadcast.
5145  return SDValue();
5146}
5147
5148// LowerVectorFpExtend - Recognize the scalarized FP_EXTEND from v2f32 to v2f64
5149// and convert it into X86ISD::VFPEXT due to the current ISD::FP_EXTEND has the
5150// constraint of matching input/output vector elements.
5151SDValue
5152X86TargetLowering::LowerVectorFpExtend(SDValue &Op, SelectionDAG &DAG) const {
5153  DebugLoc DL = Op.getDebugLoc();
5154  SDNode *N = Op.getNode();
5155  EVT VT = Op.getValueType();
5156  unsigned NumElts = Op.getNumOperands();
5157
5158  // Check supported types and sub-targets.
5159  //
5160  // Only v2f32 -> v2f64 needs special handling.
5161  if (VT != MVT::v2f64 || !Subtarget->hasSSE2())
5162    return SDValue();
5163
5164  SDValue VecIn;
5165  EVT VecInVT;
5166  SmallVector<int, 8> Mask;
5167  EVT SrcVT = MVT::Other;
5168
5169  // Check the patterns could be translated into X86vfpext.
5170  for (unsigned i = 0; i < NumElts; ++i) {
5171    SDValue In = N->getOperand(i);
5172    unsigned Opcode = In.getOpcode();
5173
5174    // Skip if the element is undefined.
5175    if (Opcode == ISD::UNDEF) {
5176      Mask.push_back(-1);
5177      continue;
5178    }
5179
5180    // Quit if one of the elements is not defined from 'fpext'.
5181    if (Opcode != ISD::FP_EXTEND)
5182      return SDValue();
5183
5184    // Check how the source of 'fpext' is defined.
5185    SDValue L2In = In.getOperand(0);
5186    EVT L2InVT = L2In.getValueType();
5187
5188    // Check the original type
5189    if (SrcVT == MVT::Other)
5190      SrcVT = L2InVT;
5191    else if (SrcVT != L2InVT) // Quit if non-homogenous typed.
5192      return SDValue();
5193
5194    // Check whether the value being 'fpext'ed is extracted from the same
5195    // source.
5196    Opcode = L2In.getOpcode();
5197
5198    // Quit if it's not extracted with a constant index.
5199    if (Opcode != ISD::EXTRACT_VECTOR_ELT ||
5200        !isa<ConstantSDNode>(L2In.getOperand(1)))
5201      return SDValue();
5202
5203    SDValue ExtractedFromVec = L2In.getOperand(0);
5204
5205    if (VecIn.getNode() == 0) {
5206      VecIn = ExtractedFromVec;
5207      VecInVT = ExtractedFromVec.getValueType();
5208    } else if (VecIn != ExtractedFromVec) // Quit if built from more than 1 vec.
5209      return SDValue();
5210
5211    Mask.push_back(cast<ConstantSDNode>(L2In.getOperand(1))->getZExtValue());
5212  }
5213
5214  // Quit if all operands of BUILD_VECTOR are undefined.
5215  if (!VecIn.getNode())
5216    return SDValue();
5217
5218  // Fill the remaining mask as undef.
5219  for (unsigned i = NumElts; i < VecInVT.getVectorNumElements(); ++i)
5220    Mask.push_back(-1);
5221
5222  return DAG.getNode(X86ISD::VFPEXT, DL, VT,
5223                     DAG.getVectorShuffle(VecInVT, DL,
5224                                          VecIn, DAG.getUNDEF(VecInVT),
5225                                          &Mask[0]));
5226}
5227
5228SDValue
5229X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
5230  DebugLoc dl = Op.getDebugLoc();
5231
5232  EVT VT = Op.getValueType();
5233  EVT ExtVT = VT.getVectorElementType();
5234  unsigned NumElems = Op.getNumOperands();
5235
5236  // Vectors containing all zeros can be matched by pxor and xorps later
5237  if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5238    // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
5239    // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
5240    if (VT == MVT::v4i32 || VT == MVT::v8i32)
5241      return Op;
5242
5243    return getZeroVector(VT, Subtarget, DAG, dl);
5244  }
5245
5246  // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
5247  // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use
5248  // vpcmpeqd on 256-bit vectors.
5249  if (ISD::isBuildVectorAllOnes(Op.getNode())) {
5250    if (VT == MVT::v4i32 || (VT == MVT::v8i32 && Subtarget->hasAVX2()))
5251      return Op;
5252
5253    return getOnesVector(VT, Subtarget->hasAVX2(), DAG, dl);
5254  }
5255
5256  SDValue Broadcast = LowerVectorBroadcast(Op, DAG);
5257  if (Broadcast.getNode())
5258    return Broadcast;
5259
5260  SDValue FpExt = LowerVectorFpExtend(Op, DAG);
5261  if (FpExt.getNode())
5262    return FpExt;
5263
5264  unsigned EVTBits = ExtVT.getSizeInBits();
5265
5266  unsigned NumZero  = 0;
5267  unsigned NumNonZero = 0;
5268  unsigned NonZeros = 0;
5269  bool IsAllConstants = true;
5270  SmallSet<SDValue, 8> Values;
5271  for (unsigned i = 0; i < NumElems; ++i) {
5272    SDValue Elt = Op.getOperand(i);
5273    if (Elt.getOpcode() == ISD::UNDEF)
5274      continue;
5275    Values.insert(Elt);
5276    if (Elt.getOpcode() != ISD::Constant &&
5277        Elt.getOpcode() != ISD::ConstantFP)
5278      IsAllConstants = false;
5279    if (X86::isZeroNode(Elt))
5280      NumZero++;
5281    else {
5282      NonZeros |= (1 << i);
5283      NumNonZero++;
5284    }
5285  }
5286
5287  // All undef vector. Return an UNDEF.  All zero vectors were handled above.
5288  if (NumNonZero == 0)
5289    return DAG.getUNDEF(VT);
5290
5291  // Special case for single non-zero, non-undef, element.
5292  if (NumNonZero == 1) {
5293    unsigned Idx = CountTrailingZeros_32(NonZeros);
5294    SDValue Item = Op.getOperand(Idx);
5295
5296    // If this is an insertion of an i64 value on x86-32, and if the top bits of
5297    // the value are obviously zero, truncate the value to i32 and do the
5298    // insertion that way.  Only do this if the value is non-constant or if the
5299    // value is a constant being inserted into element 0.  It is cheaper to do
5300    // a constant pool load than it is to do a movd + shuffle.
5301    if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
5302        (!IsAllConstants || Idx == 0)) {
5303      if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
5304        // Handle SSE only.
5305        assert(VT == MVT::v2i64 && "Expected an SSE value type!");
5306        EVT VecVT = MVT::v4i32;
5307        unsigned VecElts = 4;
5308
5309        // Truncate the value (which may itself be a constant) to i32, and
5310        // convert it to a vector with movd (S2V+shuffle to zero extend).
5311        Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
5312        Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
5313        Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5314
5315        // Now we have our 32-bit value zero extended in the low element of
5316        // a vector.  If Idx != 0, swizzle it into place.
5317        if (Idx != 0) {
5318          SmallVector<int, 4> Mask;
5319          Mask.push_back(Idx);
5320          for (unsigned i = 1; i != VecElts; ++i)
5321            Mask.push_back(i);
5322          Item = DAG.getVectorShuffle(VecVT, dl, Item, DAG.getUNDEF(VecVT),
5323                                      &Mask[0]);
5324        }
5325        return DAG.getNode(ISD::BITCAST, dl, VT, Item);
5326      }
5327    }
5328
5329    // If we have a constant or non-constant insertion into the low element of
5330    // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
5331    // the rest of the elements.  This will be matched as movd/movq/movss/movsd
5332    // depending on what the source datatype is.
5333    if (Idx == 0) {
5334      if (NumZero == 0)
5335        return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5336
5337      if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
5338          (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
5339        if (VT.is256BitVector()) {
5340          SDValue ZeroVec = getZeroVector(VT, Subtarget, DAG, dl);
5341          return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, ZeroVec,
5342                             Item, DAG.getIntPtrConstant(0));
5343        }
5344        assert(VT.is128BitVector() && "Expected an SSE value type!");
5345        Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5346        // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
5347        return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5348      }
5349
5350      if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
5351        Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
5352        Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
5353        if (VT.is256BitVector()) {
5354          SDValue ZeroVec = getZeroVector(MVT::v8i32, Subtarget, DAG, dl);
5355          Item = Insert128BitVector(ZeroVec, Item, 0, DAG, dl);
5356        } else {
5357          assert(VT.is128BitVector() && "Expected an SSE value type!");
5358          Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5359        }
5360        return DAG.getNode(ISD::BITCAST, dl, VT, Item);
5361      }
5362    }
5363
5364    // Is it a vector logical left shift?
5365    if (NumElems == 2 && Idx == 1 &&
5366        X86::isZeroNode(Op.getOperand(0)) &&
5367        !X86::isZeroNode(Op.getOperand(1))) {
5368      unsigned NumBits = VT.getSizeInBits();
5369      return getVShift(true, VT,
5370                       DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
5371                                   VT, Op.getOperand(1)),
5372                       NumBits/2, DAG, *this, dl);
5373    }
5374
5375    if (IsAllConstants) // Otherwise, it's better to do a constpool load.
5376      return SDValue();
5377
5378    // Otherwise, if this is a vector with i32 or f32 elements, and the element
5379    // is a non-constant being inserted into an element other than the low one,
5380    // we can't use a constant pool load.  Instead, use SCALAR_TO_VECTOR (aka
5381    // movd/movss) to move this into the low element, then shuffle it into
5382    // place.
5383    if (EVTBits == 32) {
5384      Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5385
5386      // Turn it into a shuffle of zero and zero-extended scalar to vector.
5387      Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0, Subtarget, DAG);
5388      SmallVector<int, 8> MaskVec;
5389      for (unsigned i = 0; i != NumElems; ++i)
5390        MaskVec.push_back(i == Idx ? 0 : 1);
5391      return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
5392    }
5393  }
5394
5395  // Splat is obviously ok. Let legalizer expand it to a shuffle.
5396  if (Values.size() == 1) {
5397    if (EVTBits == 32) {
5398      // Instead of a shuffle like this:
5399      // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
5400      // Check if it's possible to issue this instead.
5401      // shuffle (vload ptr)), undef, <1, 1, 1, 1>
5402      unsigned Idx = CountTrailingZeros_32(NonZeros);
5403      SDValue Item = Op.getOperand(Idx);
5404      if (Op.getNode()->isOnlyUserOf(Item.getNode()))
5405        return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
5406    }
5407    return SDValue();
5408  }
5409
5410  // A vector full of immediates; various special cases are already
5411  // handled, so this is best done with a single constant-pool load.
5412  if (IsAllConstants)
5413    return SDValue();
5414
5415  // For AVX-length vectors, build the individual 128-bit pieces and use
5416  // shuffles to put them in place.
5417  if (VT.is256BitVector()) {
5418    SmallVector<SDValue, 32> V;
5419    for (unsigned i = 0; i != NumElems; ++i)
5420      V.push_back(Op.getOperand(i));
5421
5422    EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
5423
5424    // Build both the lower and upper subvector.
5425    SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[0], NumElems/2);
5426    SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[NumElems / 2],
5427                                NumElems/2);
5428
5429    // Recreate the wider vector with the lower and upper part.
5430    return Concat128BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
5431  }
5432
5433  // Let legalizer expand 2-wide build_vectors.
5434  if (EVTBits == 64) {
5435    if (NumNonZero == 1) {
5436      // One half is zero or undef.
5437      unsigned Idx = CountTrailingZeros_32(NonZeros);
5438      SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
5439                                 Op.getOperand(Idx));
5440      return getShuffleVectorZeroOrUndef(V2, Idx, true, Subtarget, DAG);
5441    }
5442    return SDValue();
5443  }
5444
5445  // If element VT is < 32 bits, convert it to inserts into a zero vector.
5446  if (EVTBits == 8 && NumElems == 16) {
5447    SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
5448                                        Subtarget, *this);
5449    if (V.getNode()) return V;
5450  }
5451
5452  if (EVTBits == 16 && NumElems == 8) {
5453    SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
5454                                      Subtarget, *this);
5455    if (V.getNode()) return V;
5456  }
5457
5458  // If element VT is == 32 bits, turn it into a number of shuffles.
5459  SmallVector<SDValue, 8> V(NumElems);
5460  if (NumElems == 4 && NumZero > 0) {
5461    for (unsigned i = 0; i < 4; ++i) {
5462      bool isZero = !(NonZeros & (1 << i));
5463      if (isZero)
5464        V[i] = getZeroVector(VT, Subtarget, DAG, dl);
5465      else
5466        V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
5467    }
5468
5469    for (unsigned i = 0; i < 2; ++i) {
5470      switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
5471        default: break;
5472        case 0:
5473          V[i] = V[i*2];  // Must be a zero vector.
5474          break;
5475        case 1:
5476          V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
5477          break;
5478        case 2:
5479          V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
5480          break;
5481        case 3:
5482          V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
5483          break;
5484      }
5485    }
5486
5487    bool Reverse1 = (NonZeros & 0x3) == 2;
5488    bool Reverse2 = ((NonZeros & (0x3 << 2)) >> 2) == 2;
5489    int MaskVec[] = {
5490      Reverse1 ? 1 : 0,
5491      Reverse1 ? 0 : 1,
5492      static_cast<int>(Reverse2 ? NumElems+1 : NumElems),
5493      static_cast<int>(Reverse2 ? NumElems   : NumElems+1)
5494    };
5495    return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
5496  }
5497
5498  if (Values.size() > 1 && VT.is128BitVector()) {
5499    // Check for a build vector of consecutive loads.
5500    for (unsigned i = 0; i < NumElems; ++i)
5501      V[i] = Op.getOperand(i);
5502
5503    // Check for elements which are consecutive loads.
5504    SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG);
5505    if (LD.getNode())
5506      return LD;
5507
5508    // For SSE 4.1, use insertps to put the high elements into the low element.
5509    if (getSubtarget()->hasSSE41()) {
5510      SDValue Result;
5511      if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
5512        Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
5513      else
5514        Result = DAG.getUNDEF(VT);
5515
5516      for (unsigned i = 1; i < NumElems; ++i) {
5517        if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
5518        Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
5519                             Op.getOperand(i), DAG.getIntPtrConstant(i));
5520      }
5521      return Result;
5522    }
5523
5524    // Otherwise, expand into a number of unpckl*, start by extending each of
5525    // our (non-undef) elements to the full vector width with the element in the
5526    // bottom slot of the vector (which generates no code for SSE).
5527    for (unsigned i = 0; i < NumElems; ++i) {
5528      if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
5529        V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
5530      else
5531        V[i] = DAG.getUNDEF(VT);
5532    }
5533
5534    // Next, we iteratively mix elements, e.g. for v4f32:
5535    //   Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
5536    //         : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
5537    //   Step 2: unpcklps X, Y ==>    <3, 2, 1, 0>
5538    unsigned EltStride = NumElems >> 1;
5539    while (EltStride != 0) {
5540      for (unsigned i = 0; i < EltStride; ++i) {
5541        // If V[i+EltStride] is undef and this is the first round of mixing,
5542        // then it is safe to just drop this shuffle: V[i] is already in the
5543        // right place, the one element (since it's the first round) being
5544        // inserted as undef can be dropped.  This isn't safe for successive
5545        // rounds because they will permute elements within both vectors.
5546        if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
5547            EltStride == NumElems/2)
5548          continue;
5549
5550        V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
5551      }
5552      EltStride >>= 1;
5553    }
5554    return V[0];
5555  }
5556  return SDValue();
5557}
5558
5559// LowerAVXCONCAT_VECTORS - 256-bit AVX can use the vinsertf128 instruction
5560// to create 256-bit vectors from two other 128-bit ones.
5561static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5562  DebugLoc dl = Op.getDebugLoc();
5563  EVT ResVT = Op.getValueType();
5564
5565  assert(ResVT.is256BitVector() && "Value type must be 256-bit wide");
5566
5567  SDValue V1 = Op.getOperand(0);
5568  SDValue V2 = Op.getOperand(1);
5569  unsigned NumElems = ResVT.getVectorNumElements();
5570
5571  return Concat128BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
5572}
5573
5574SDValue
5575X86TargetLowering::LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) const {
5576  assert(Op.getNumOperands() == 2);
5577
5578  // 256-bit AVX can use the vinsertf128 instruction to create 256-bit vectors
5579  // from two other 128-bit ones.
5580  return LowerAVXCONCAT_VECTORS(Op, DAG);
5581}
5582
5583// Try to lower a shuffle node into a simple blend instruction.
5584static SDValue LowerVECTOR_SHUFFLEtoBlend(ShuffleVectorSDNode *SVOp,
5585                                          const X86Subtarget *Subtarget,
5586                                          SelectionDAG &DAG) {
5587  SDValue V1 = SVOp->getOperand(0);
5588  SDValue V2 = SVOp->getOperand(1);
5589  DebugLoc dl = SVOp->getDebugLoc();
5590  MVT VT = SVOp->getValueType(0).getSimpleVT();
5591  unsigned NumElems = VT.getVectorNumElements();
5592
5593  if (!Subtarget->hasSSE41())
5594    return SDValue();
5595
5596  unsigned ISDNo = 0;
5597  MVT OpTy;
5598
5599  switch (VT.SimpleTy) {
5600  default: return SDValue();
5601  case MVT::v8i16:
5602    ISDNo = X86ISD::BLENDPW;
5603    OpTy = MVT::v8i16;
5604    break;
5605  case MVT::v4i32:
5606  case MVT::v4f32:
5607    ISDNo = X86ISD::BLENDPS;
5608    OpTy = MVT::v4f32;
5609    break;
5610  case MVT::v2i64:
5611  case MVT::v2f64:
5612    ISDNo = X86ISD::BLENDPD;
5613    OpTy = MVT::v2f64;
5614    break;
5615  case MVT::v8i32:
5616  case MVT::v8f32:
5617    if (!Subtarget->hasAVX())
5618      return SDValue();
5619    ISDNo = X86ISD::BLENDPS;
5620    OpTy = MVT::v8f32;
5621    break;
5622  case MVT::v4i64:
5623  case MVT::v4f64:
5624    if (!Subtarget->hasAVX())
5625      return SDValue();
5626    ISDNo = X86ISD::BLENDPD;
5627    OpTy = MVT::v4f64;
5628    break;
5629  }
5630  assert(ISDNo && "Invalid Op Number");
5631
5632  unsigned MaskVals = 0;
5633
5634  for (unsigned i = 0; i != NumElems; ++i) {
5635    int EltIdx = SVOp->getMaskElt(i);
5636    if (EltIdx == (int)i || EltIdx < 0)
5637      MaskVals |= (1<<i);
5638    else if (EltIdx == (int)(i + NumElems))
5639      continue; // Bit is set to zero;
5640    else
5641      return SDValue();
5642  }
5643
5644  V1 = DAG.getNode(ISD::BITCAST, dl, OpTy, V1);
5645  V2 = DAG.getNode(ISD::BITCAST, dl, OpTy, V2);
5646  SDValue Ret =  DAG.getNode(ISDNo, dl, OpTy, V1, V2,
5647                             DAG.getConstant(MaskVals, MVT::i32));
5648  return DAG.getNode(ISD::BITCAST, dl, VT, Ret);
5649}
5650
5651// v8i16 shuffles - Prefer shuffles in the following order:
5652// 1. [all]   pshuflw, pshufhw, optional move
5653// 2. [ssse3] 1 x pshufb
5654// 3. [ssse3] 2 x pshufb + 1 x por
5655// 4. [all]   mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
5656SDValue
5657X86TargetLowering::LowerVECTOR_SHUFFLEv8i16(SDValue Op,
5658                                            SelectionDAG &DAG) const {
5659  ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5660  SDValue V1 = SVOp->getOperand(0);
5661  SDValue V2 = SVOp->getOperand(1);
5662  DebugLoc dl = SVOp->getDebugLoc();
5663  SmallVector<int, 8> MaskVals;
5664
5665  // Determine if more than 1 of the words in each of the low and high quadwords
5666  // of the result come from the same quadword of one of the two inputs.  Undef
5667  // mask values count as coming from any quadword, for better codegen.
5668  unsigned LoQuad[] = { 0, 0, 0, 0 };
5669  unsigned HiQuad[] = { 0, 0, 0, 0 };
5670  std::bitset<4> InputQuads;
5671  for (unsigned i = 0; i < 8; ++i) {
5672    unsigned *Quad = i < 4 ? LoQuad : HiQuad;
5673    int EltIdx = SVOp->getMaskElt(i);
5674    MaskVals.push_back(EltIdx);
5675    if (EltIdx < 0) {
5676      ++Quad[0];
5677      ++Quad[1];
5678      ++Quad[2];
5679      ++Quad[3];
5680      continue;
5681    }
5682    ++Quad[EltIdx / 4];
5683    InputQuads.set(EltIdx / 4);
5684  }
5685
5686  int BestLoQuad = -1;
5687  unsigned MaxQuad = 1;
5688  for (unsigned i = 0; i < 4; ++i) {
5689    if (LoQuad[i] > MaxQuad) {
5690      BestLoQuad = i;
5691      MaxQuad = LoQuad[i];
5692    }
5693  }
5694
5695  int BestHiQuad = -1;
5696  MaxQuad = 1;
5697  for (unsigned i = 0; i < 4; ++i) {
5698    if (HiQuad[i] > MaxQuad) {
5699      BestHiQuad = i;
5700      MaxQuad = HiQuad[i];
5701    }
5702  }
5703
5704  // For SSSE3, If all 8 words of the result come from only 1 quadword of each
5705  // of the two input vectors, shuffle them into one input vector so only a
5706  // single pshufb instruction is necessary. If There are more than 2 input
5707  // quads, disable the next transformation since it does not help SSSE3.
5708  bool V1Used = InputQuads[0] || InputQuads[1];
5709  bool V2Used = InputQuads[2] || InputQuads[3];
5710  if (Subtarget->hasSSSE3()) {
5711    if (InputQuads.count() == 2 && V1Used && V2Used) {
5712      BestLoQuad = InputQuads[0] ? 0 : 1;
5713      BestHiQuad = InputQuads[2] ? 2 : 3;
5714    }
5715    if (InputQuads.count() > 2) {
5716      BestLoQuad = -1;
5717      BestHiQuad = -1;
5718    }
5719  }
5720
5721  // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
5722  // the shuffle mask.  If a quad is scored as -1, that means that it contains
5723  // words from all 4 input quadwords.
5724  SDValue NewV;
5725  if (BestLoQuad >= 0 || BestHiQuad >= 0) {
5726    int MaskV[] = {
5727      BestLoQuad < 0 ? 0 : BestLoQuad,
5728      BestHiQuad < 0 ? 1 : BestHiQuad
5729    };
5730    NewV = DAG.getVectorShuffle(MVT::v2i64, dl,
5731                  DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1),
5732                  DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2), &MaskV[0]);
5733    NewV = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, NewV);
5734
5735    // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
5736    // source words for the shuffle, to aid later transformations.
5737    bool AllWordsInNewV = true;
5738    bool InOrder[2] = { true, true };
5739    for (unsigned i = 0; i != 8; ++i) {
5740      int idx = MaskVals[i];
5741      if (idx != (int)i)
5742        InOrder[i/4] = false;
5743      if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
5744        continue;
5745      AllWordsInNewV = false;
5746      break;
5747    }
5748
5749    bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
5750    if (AllWordsInNewV) {
5751      for (int i = 0; i != 8; ++i) {
5752        int idx = MaskVals[i];
5753        if (idx < 0)
5754          continue;
5755        idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
5756        if ((idx != i) && idx < 4)
5757          pshufhw = false;
5758        if ((idx != i) && idx > 3)
5759          pshuflw = false;
5760      }
5761      V1 = NewV;
5762      V2Used = false;
5763      BestLoQuad = 0;
5764      BestHiQuad = 1;
5765    }
5766
5767    // If we've eliminated the use of V2, and the new mask is a pshuflw or
5768    // pshufhw, that's as cheap as it gets.  Return the new shuffle.
5769    if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
5770      unsigned Opc = pshufhw ? X86ISD::PSHUFHW : X86ISD::PSHUFLW;
5771      unsigned TargetMask = 0;
5772      NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV,
5773                                  DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
5774      ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
5775      TargetMask = pshufhw ? getShufflePSHUFHWImmediate(SVOp):
5776                             getShufflePSHUFLWImmediate(SVOp);
5777      V1 = NewV.getOperand(0);
5778      return getTargetShuffleNode(Opc, dl, MVT::v8i16, V1, TargetMask, DAG);
5779    }
5780  }
5781
5782  // If we have SSSE3, and all words of the result are from 1 input vector,
5783  // case 2 is generated, otherwise case 3 is generated.  If no SSSE3
5784  // is present, fall back to case 4.
5785  if (Subtarget->hasSSSE3()) {
5786    SmallVector<SDValue,16> pshufbMask;
5787
5788    // If we have elements from both input vectors, set the high bit of the
5789    // shuffle mask element to zero out elements that come from V2 in the V1
5790    // mask, and elements that come from V1 in the V2 mask, so that the two
5791    // results can be OR'd together.
5792    bool TwoInputs = V1Used && V2Used;
5793    for (unsigned i = 0; i != 8; ++i) {
5794      int EltIdx = MaskVals[i] * 2;
5795      int Idx0 = (TwoInputs && (EltIdx >= 16)) ? 0x80 : EltIdx;
5796      int Idx1 = (TwoInputs && (EltIdx >= 16)) ? 0x80 : EltIdx+1;
5797      pshufbMask.push_back(DAG.getConstant(Idx0,   MVT::i8));
5798      pshufbMask.push_back(DAG.getConstant(Idx1, MVT::i8));
5799    }
5800    V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V1);
5801    V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
5802                     DAG.getNode(ISD::BUILD_VECTOR, dl,
5803                                 MVT::v16i8, &pshufbMask[0], 16));
5804    if (!TwoInputs)
5805      return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5806
5807    // Calculate the shuffle mask for the second input, shuffle it, and
5808    // OR it with the first shuffled input.
5809    pshufbMask.clear();
5810    for (unsigned i = 0; i != 8; ++i) {
5811      int EltIdx = MaskVals[i] * 2;
5812      int Idx0 = (EltIdx < 16) ? 0x80 : EltIdx - 16;
5813      int Idx1 = (EltIdx < 16) ? 0x80 : EltIdx - 15;
5814      pshufbMask.push_back(DAG.getConstant(Idx0, MVT::i8));
5815      pshufbMask.push_back(DAG.getConstant(Idx1, MVT::i8));
5816    }
5817    V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V2);
5818    V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
5819                     DAG.getNode(ISD::BUILD_VECTOR, dl,
5820                                 MVT::v16i8, &pshufbMask[0], 16));
5821    V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
5822    return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5823  }
5824
5825  // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
5826  // and update MaskVals with new element order.
5827  std::bitset<8> InOrder;
5828  if (BestLoQuad >= 0) {
5829    int MaskV[] = { -1, -1, -1, -1, 4, 5, 6, 7 };
5830    for (int i = 0; i != 4; ++i) {
5831      int idx = MaskVals[i];
5832      if (idx < 0) {
5833        InOrder.set(i);
5834      } else if ((idx / 4) == BestLoQuad) {
5835        MaskV[i] = idx & 3;
5836        InOrder.set(i);
5837      }
5838    }
5839    NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
5840                                &MaskV[0]);
5841
5842    if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3()) {
5843      ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
5844      NewV = getTargetShuffleNode(X86ISD::PSHUFLW, dl, MVT::v8i16,
5845                                  NewV.getOperand(0),
5846                                  getShufflePSHUFLWImmediate(SVOp), DAG);
5847    }
5848  }
5849
5850  // If BestHi >= 0, generate a pshufhw to put the high elements in order,
5851  // and update MaskVals with the new element order.
5852  if (BestHiQuad >= 0) {
5853    int MaskV[] = { 0, 1, 2, 3, -1, -1, -1, -1 };
5854    for (unsigned i = 4; i != 8; ++i) {
5855      int idx = MaskVals[i];
5856      if (idx < 0) {
5857        InOrder.set(i);
5858      } else if ((idx / 4) == BestHiQuad) {
5859        MaskV[i] = (idx & 3) + 4;
5860        InOrder.set(i);
5861      }
5862    }
5863    NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
5864                                &MaskV[0]);
5865
5866    if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3()) {
5867      ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
5868      NewV = getTargetShuffleNode(X86ISD::PSHUFHW, dl, MVT::v8i16,
5869                                  NewV.getOperand(0),
5870                                  getShufflePSHUFHWImmediate(SVOp), DAG);
5871    }
5872  }
5873
5874  // In case BestHi & BestLo were both -1, which means each quadword has a word
5875  // from each of the four input quadwords, calculate the InOrder bitvector now
5876  // before falling through to the insert/extract cleanup.
5877  if (BestLoQuad == -1 && BestHiQuad == -1) {
5878    NewV = V1;
5879    for (int i = 0; i != 8; ++i)
5880      if (MaskVals[i] < 0 || MaskVals[i] == i)
5881        InOrder.set(i);
5882  }
5883
5884  // The other elements are put in the right place using pextrw and pinsrw.
5885  for (unsigned i = 0; i != 8; ++i) {
5886    if (InOrder[i])
5887      continue;
5888    int EltIdx = MaskVals[i];
5889    if (EltIdx < 0)
5890      continue;
5891    SDValue ExtOp = (EltIdx < 8) ?
5892      DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
5893                  DAG.getIntPtrConstant(EltIdx)) :
5894      DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
5895                  DAG.getIntPtrConstant(EltIdx - 8));
5896    NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
5897                       DAG.getIntPtrConstant(i));
5898  }
5899  return NewV;
5900}
5901
5902// v16i8 shuffles - Prefer shuffles in the following order:
5903// 1. [ssse3] 1 x pshufb
5904// 2. [ssse3] 2 x pshufb + 1 x por
5905// 3. [all]   v8i16 shuffle + N x pextrw + rotate + pinsrw
5906static
5907SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
5908                                 SelectionDAG &DAG,
5909                                 const X86TargetLowering &TLI) {
5910  SDValue V1 = SVOp->getOperand(0);
5911  SDValue V2 = SVOp->getOperand(1);
5912  DebugLoc dl = SVOp->getDebugLoc();
5913  ArrayRef<int> MaskVals = SVOp->getMask();
5914
5915  // If we have SSSE3, case 1 is generated when all result bytes come from
5916  // one of  the inputs.  Otherwise, case 2 is generated.  If no SSSE3 is
5917  // present, fall back to case 3.
5918
5919  // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
5920  if (TLI.getSubtarget()->hasSSSE3()) {
5921    SmallVector<SDValue,16> pshufbMask;
5922
5923    // If all result elements are from one input vector, then only translate
5924    // undef mask values to 0x80 (zero out result) in the pshufb mask.
5925    //
5926    // Otherwise, we have elements from both input vectors, and must zero out
5927    // elements that come from V2 in the first mask, and V1 in the second mask
5928    // so that we can OR them together.
5929    for (unsigned i = 0; i != 16; ++i) {
5930      int EltIdx = MaskVals[i];
5931      if (EltIdx < 0 || EltIdx >= 16)
5932        EltIdx = 0x80;
5933      pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
5934    }
5935    V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
5936                     DAG.getNode(ISD::BUILD_VECTOR, dl,
5937                                 MVT::v16i8, &pshufbMask[0], 16));
5938
5939    // As PSHUFB will zero elements with negative indices, it's safe to ignore
5940    // the 2nd operand if it's undefined or zero.
5941    if (V2.getOpcode() == ISD::UNDEF ||
5942        ISD::isBuildVectorAllZeros(V2.getNode()))
5943      return V1;
5944
5945    // Calculate the shuffle mask for the second input, shuffle it, and
5946    // OR it with the first shuffled input.
5947    pshufbMask.clear();
5948    for (unsigned i = 0; i != 16; ++i) {
5949      int EltIdx = MaskVals[i];
5950      EltIdx = (EltIdx < 16) ? 0x80 : EltIdx - 16;
5951      pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
5952    }
5953    V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
5954                     DAG.getNode(ISD::BUILD_VECTOR, dl,
5955                                 MVT::v16i8, &pshufbMask[0], 16));
5956    return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
5957  }
5958
5959  // No SSSE3 - Calculate in place words and then fix all out of place words
5960  // With 0-16 extracts & inserts.  Worst case is 16 bytes out of order from
5961  // the 16 different words that comprise the two doublequadword input vectors.
5962  V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5963  V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
5964  SDValue NewV = V1;
5965  for (int i = 0; i != 8; ++i) {
5966    int Elt0 = MaskVals[i*2];
5967    int Elt1 = MaskVals[i*2+1];
5968
5969    // This word of the result is all undef, skip it.
5970    if (Elt0 < 0 && Elt1 < 0)
5971      continue;
5972
5973    // This word of the result is already in the correct place, skip it.
5974    if ((Elt0 == i*2) && (Elt1 == i*2+1))
5975      continue;
5976
5977    SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
5978    SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
5979    SDValue InsElt;
5980
5981    // If Elt0 and Elt1 are defined, are consecutive, and can be load
5982    // using a single extract together, load it and store it.
5983    if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
5984      InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
5985                           DAG.getIntPtrConstant(Elt1 / 2));
5986      NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
5987                        DAG.getIntPtrConstant(i));
5988      continue;
5989    }
5990
5991    // If Elt1 is defined, extract it from the appropriate source.  If the
5992    // source byte is not also odd, shift the extracted word left 8 bits
5993    // otherwise clear the bottom 8 bits if we need to do an or.
5994    if (Elt1 >= 0) {
5995      InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
5996                           DAG.getIntPtrConstant(Elt1 / 2));
5997      if ((Elt1 & 1) == 0)
5998        InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
5999                             DAG.getConstant(8,
6000                                  TLI.getShiftAmountTy(InsElt.getValueType())));
6001      else if (Elt0 >= 0)
6002        InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
6003                             DAG.getConstant(0xFF00, MVT::i16));
6004    }
6005    // If Elt0 is defined, extract it from the appropriate source.  If the
6006    // source byte is not also even, shift the extracted word right 8 bits. If
6007    // Elt1 was also defined, OR the extracted values together before
6008    // inserting them in the result.
6009    if (Elt0 >= 0) {
6010      SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
6011                                    Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
6012      if ((Elt0 & 1) != 0)
6013        InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
6014                              DAG.getConstant(8,
6015                                 TLI.getShiftAmountTy(InsElt0.getValueType())));
6016      else if (Elt1 >= 0)
6017        InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
6018                             DAG.getConstant(0x00FF, MVT::i16));
6019      InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
6020                         : InsElt0;
6021    }
6022    NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
6023                       DAG.getIntPtrConstant(i));
6024  }
6025  return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, NewV);
6026}
6027
6028// v32i8 shuffles - Translate to VPSHUFB if possible.
6029static
6030SDValue LowerVECTOR_SHUFFLEv32i8(ShuffleVectorSDNode *SVOp,
6031                                 SelectionDAG &DAG,
6032                                 const X86TargetLowering &TLI) {
6033  EVT VT = SVOp->getValueType(0);
6034  SDValue V1 = SVOp->getOperand(0);
6035  SDValue V2 = SVOp->getOperand(1);
6036  DebugLoc dl = SVOp->getDebugLoc();
6037  SmallVector<int, 32> MaskVals(SVOp->getMask().begin(), SVOp->getMask().end());
6038
6039  bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
6040  bool V1IsAllZero = ISD::isBuildVectorAllZeros(V1.getNode());
6041  bool V2IsAllZero = ISD::isBuildVectorAllZeros(V2.getNode());
6042
6043  // VPSHUFB may be generated if
6044  // (1) one of input vector is undefined or zeroinitializer.
6045  // The mask value 0x80 puts 0 in the corresponding slot of the vector.
6046  // And (2) the mask indexes don't cross the 128-bit lane.
6047  if (VT != MVT::v32i8 || !TLI.getSubtarget()->hasAVX2() ||
6048      (!V2IsUndef && !V2IsAllZero && !V1IsAllZero))
6049    return SDValue();
6050
6051  if (V1IsAllZero && !V2IsAllZero) {
6052    CommuteVectorShuffleMask(MaskVals, 32);
6053    V1 = V2;
6054  }
6055  SmallVector<SDValue, 32> pshufbMask;
6056  for (unsigned i = 0; i != 32; i++) {
6057    int EltIdx = MaskVals[i];
6058    if (EltIdx < 0 || EltIdx >= 32)
6059      EltIdx = 0x80;
6060    else {
6061      if ((EltIdx >= 16 && i < 16) || (EltIdx < 16 && i >= 16))
6062        // Cross lane is not allowed.
6063        return SDValue();
6064      EltIdx &= 0xf;
6065    }
6066    pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
6067  }
6068  return DAG.getNode(X86ISD::PSHUFB, dl, MVT::v32i8, V1,
6069                      DAG.getNode(ISD::BUILD_VECTOR, dl,
6070                                  MVT::v32i8, &pshufbMask[0], 32));
6071}
6072
6073/// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
6074/// ones, or rewriting v4i32 / v4f32 as 2 wide ones if possible. This can be
6075/// done when every pair / quad of shuffle mask elements point to elements in
6076/// the right sequence. e.g.
6077/// vector_shuffle X, Y, <2, 3, | 10, 11, | 0, 1, | 14, 15>
6078static
6079SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
6080                                 SelectionDAG &DAG, DebugLoc dl) {
6081  MVT VT = SVOp->getValueType(0).getSimpleVT();
6082  unsigned NumElems = VT.getVectorNumElements();
6083  MVT NewVT;
6084  unsigned Scale;
6085  switch (VT.SimpleTy) {
6086  default: llvm_unreachable("Unexpected!");
6087  case MVT::v4f32:  NewVT = MVT::v2f64; Scale = 2; break;
6088  case MVT::v4i32:  NewVT = MVT::v2i64; Scale = 2; break;
6089  case MVT::v8i16:  NewVT = MVT::v4i32; Scale = 2; break;
6090  case MVT::v16i8:  NewVT = MVT::v4i32; Scale = 4; break;
6091  case MVT::v16i16: NewVT = MVT::v8i32; Scale = 2; break;
6092  case MVT::v32i8:  NewVT = MVT::v8i32; Scale = 4; break;
6093  }
6094
6095  SmallVector<int, 8> MaskVec;
6096  for (unsigned i = 0; i != NumElems; i += Scale) {
6097    int StartIdx = -1;
6098    for (unsigned j = 0; j != Scale; ++j) {
6099      int EltIdx = SVOp->getMaskElt(i+j);
6100      if (EltIdx < 0)
6101        continue;
6102      if (StartIdx < 0)
6103        StartIdx = (EltIdx / Scale);
6104      if (EltIdx != (int)(StartIdx*Scale + j))
6105        return SDValue();
6106    }
6107    MaskVec.push_back(StartIdx);
6108  }
6109
6110  SDValue V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(0));
6111  SDValue V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(1));
6112  return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
6113}
6114
6115/// getVZextMovL - Return a zero-extending vector move low node.
6116///
6117static SDValue getVZextMovL(EVT VT, EVT OpVT,
6118                            SDValue SrcOp, SelectionDAG &DAG,
6119                            const X86Subtarget *Subtarget, DebugLoc dl) {
6120  if (VT == MVT::v2f64 || VT == MVT::v4f32) {
6121    LoadSDNode *LD = NULL;
6122    if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
6123      LD = dyn_cast<LoadSDNode>(SrcOp);
6124    if (!LD) {
6125      // movssrr and movsdrr do not clear top bits. Try to use movd, movq
6126      // instead.
6127      MVT ExtVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
6128      if ((ExtVT != MVT::i64 || Subtarget->is64Bit()) &&
6129          SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
6130          SrcOp.getOperand(0).getOpcode() == ISD::BITCAST &&
6131          SrcOp.getOperand(0).getOperand(0).getValueType() == ExtVT) {
6132        // PR2108
6133        OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
6134        return DAG.getNode(ISD::BITCAST, dl, VT,
6135                           DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
6136                                       DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6137                                                   OpVT,
6138                                                   SrcOp.getOperand(0)
6139                                                          .getOperand(0))));
6140      }
6141    }
6142  }
6143
6144  return DAG.getNode(ISD::BITCAST, dl, VT,
6145                     DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
6146                                 DAG.getNode(ISD::BITCAST, dl,
6147                                             OpVT, SrcOp)));
6148}
6149
6150/// LowerVECTOR_SHUFFLE_256 - Handle all 256-bit wide vectors shuffles
6151/// which could not be matched by any known target speficic shuffle
6152static SDValue
6153LowerVECTOR_SHUFFLE_256(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
6154
6155  SDValue NewOp = Compact8x32ShuffleNode(SVOp, DAG);
6156  if (NewOp.getNode())
6157    return NewOp;
6158
6159  EVT VT = SVOp->getValueType(0);
6160
6161  unsigned NumElems = VT.getVectorNumElements();
6162  unsigned NumLaneElems = NumElems / 2;
6163
6164  DebugLoc dl = SVOp->getDebugLoc();
6165  MVT EltVT = VT.getVectorElementType().getSimpleVT();
6166  EVT NVT = MVT::getVectorVT(EltVT, NumLaneElems);
6167  SDValue Output[2];
6168
6169  SmallVector<int, 16> Mask;
6170  for (unsigned l = 0; l < 2; ++l) {
6171    // Build a shuffle mask for the output, discovering on the fly which
6172    // input vectors to use as shuffle operands (recorded in InputUsed).
6173    // If building a suitable shuffle vector proves too hard, then bail
6174    // out with UseBuildVector set.
6175    bool UseBuildVector = false;
6176    int InputUsed[2] = { -1, -1 }; // Not yet discovered.
6177    unsigned LaneStart = l * NumLaneElems;
6178    for (unsigned i = 0; i != NumLaneElems; ++i) {
6179      // The mask element.  This indexes into the input.
6180      int Idx = SVOp->getMaskElt(i+LaneStart);
6181      if (Idx < 0) {
6182        // the mask element does not index into any input vector.
6183        Mask.push_back(-1);
6184        continue;
6185      }
6186
6187      // The input vector this mask element indexes into.
6188      int Input = Idx / NumLaneElems;
6189
6190      // Turn the index into an offset from the start of the input vector.
6191      Idx -= Input * NumLaneElems;
6192
6193      // Find or create a shuffle vector operand to hold this input.
6194      unsigned OpNo;
6195      for (OpNo = 0; OpNo < array_lengthof(InputUsed); ++OpNo) {
6196        if (InputUsed[OpNo] == Input)
6197          // This input vector is already an operand.
6198          break;
6199        if (InputUsed[OpNo] < 0) {
6200          // Create a new operand for this input vector.
6201          InputUsed[OpNo] = Input;
6202          break;
6203        }
6204      }
6205
6206      if (OpNo >= array_lengthof(InputUsed)) {
6207        // More than two input vectors used!  Give up on trying to create a
6208        // shuffle vector.  Insert all elements into a BUILD_VECTOR instead.
6209        UseBuildVector = true;
6210        break;
6211      }
6212
6213      // Add the mask index for the new shuffle vector.
6214      Mask.push_back(Idx + OpNo * NumLaneElems);
6215    }
6216
6217    if (UseBuildVector) {
6218      SmallVector<SDValue, 16> SVOps;
6219      for (unsigned i = 0; i != NumLaneElems; ++i) {
6220        // The mask element.  This indexes into the input.
6221        int Idx = SVOp->getMaskElt(i+LaneStart);
6222        if (Idx < 0) {
6223          SVOps.push_back(DAG.getUNDEF(EltVT));
6224          continue;
6225        }
6226
6227        // The input vector this mask element indexes into.
6228        int Input = Idx / NumElems;
6229
6230        // Turn the index into an offset from the start of the input vector.
6231        Idx -= Input * NumElems;
6232
6233        // Extract the vector element by hand.
6234        SVOps.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
6235                                    SVOp->getOperand(Input),
6236                                    DAG.getIntPtrConstant(Idx)));
6237      }
6238
6239      // Construct the output using a BUILD_VECTOR.
6240      Output[l] = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, &SVOps[0],
6241                              SVOps.size());
6242    } else if (InputUsed[0] < 0) {
6243      // No input vectors were used! The result is undefined.
6244      Output[l] = DAG.getUNDEF(NVT);
6245    } else {
6246      SDValue Op0 = Extract128BitVector(SVOp->getOperand(InputUsed[0] / 2),
6247                                        (InputUsed[0] % 2) * NumLaneElems,
6248                                        DAG, dl);
6249      // If only one input was used, use an undefined vector for the other.
6250      SDValue Op1 = (InputUsed[1] < 0) ? DAG.getUNDEF(NVT) :
6251        Extract128BitVector(SVOp->getOperand(InputUsed[1] / 2),
6252                            (InputUsed[1] % 2) * NumLaneElems, DAG, dl);
6253      // At least one input vector was used. Create a new shuffle vector.
6254      Output[l] = DAG.getVectorShuffle(NVT, dl, Op0, Op1, &Mask[0]);
6255    }
6256
6257    Mask.clear();
6258  }
6259
6260  // Concatenate the result back
6261  return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Output[0], Output[1]);
6262}
6263
6264/// LowerVECTOR_SHUFFLE_128v4 - Handle all 128-bit wide vectors with
6265/// 4 elements, and match them with several different shuffle types.
6266static SDValue
6267LowerVECTOR_SHUFFLE_128v4(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
6268  SDValue V1 = SVOp->getOperand(0);
6269  SDValue V2 = SVOp->getOperand(1);
6270  DebugLoc dl = SVOp->getDebugLoc();
6271  EVT VT = SVOp->getValueType(0);
6272
6273  assert(VT.is128BitVector() && "Unsupported vector size");
6274
6275  std::pair<int, int> Locs[4];
6276  int Mask1[] = { -1, -1, -1, -1 };
6277  SmallVector<int, 8> PermMask(SVOp->getMask().begin(), SVOp->getMask().end());
6278
6279  unsigned NumHi = 0;
6280  unsigned NumLo = 0;
6281  for (unsigned i = 0; i != 4; ++i) {
6282    int Idx = PermMask[i];
6283    if (Idx < 0) {
6284      Locs[i] = std::make_pair(-1, -1);
6285    } else {
6286      assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
6287      if (Idx < 4) {
6288        Locs[i] = std::make_pair(0, NumLo);
6289        Mask1[NumLo] = Idx;
6290        NumLo++;
6291      } else {
6292        Locs[i] = std::make_pair(1, NumHi);
6293        if (2+NumHi < 4)
6294          Mask1[2+NumHi] = Idx;
6295        NumHi++;
6296      }
6297    }
6298  }
6299
6300  if (NumLo <= 2 && NumHi <= 2) {
6301    // If no more than two elements come from either vector. This can be
6302    // implemented with two shuffles. First shuffle gather the elements.
6303    // The second shuffle, which takes the first shuffle as both of its
6304    // vector operands, put the elements into the right order.
6305    V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6306
6307    int Mask2[] = { -1, -1, -1, -1 };
6308
6309    for (unsigned i = 0; i != 4; ++i)
6310      if (Locs[i].first != -1) {
6311        unsigned Idx = (i < 2) ? 0 : 4;
6312        Idx += Locs[i].first * 2 + Locs[i].second;
6313        Mask2[i] = Idx;
6314      }
6315
6316    return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
6317  }
6318
6319  if (NumLo == 3 || NumHi == 3) {
6320    // Otherwise, we must have three elements from one vector, call it X, and
6321    // one element from the other, call it Y.  First, use a shufps to build an
6322    // intermediate vector with the one element from Y and the element from X
6323    // that will be in the same half in the final destination (the indexes don't
6324    // matter). Then, use a shufps to build the final vector, taking the half
6325    // containing the element from Y from the intermediate, and the other half
6326    // from X.
6327    if (NumHi == 3) {
6328      // Normalize it so the 3 elements come from V1.
6329      CommuteVectorShuffleMask(PermMask, 4);
6330      std::swap(V1, V2);
6331    }
6332
6333    // Find the element from V2.
6334    unsigned HiIndex;
6335    for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
6336      int Val = PermMask[HiIndex];
6337      if (Val < 0)
6338        continue;
6339      if (Val >= 4)
6340        break;
6341    }
6342
6343    Mask1[0] = PermMask[HiIndex];
6344    Mask1[1] = -1;
6345    Mask1[2] = PermMask[HiIndex^1];
6346    Mask1[3] = -1;
6347    V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6348
6349    if (HiIndex >= 2) {
6350      Mask1[0] = PermMask[0];
6351      Mask1[1] = PermMask[1];
6352      Mask1[2] = HiIndex & 1 ? 6 : 4;
6353      Mask1[3] = HiIndex & 1 ? 4 : 6;
6354      return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6355    }
6356
6357    Mask1[0] = HiIndex & 1 ? 2 : 0;
6358    Mask1[1] = HiIndex & 1 ? 0 : 2;
6359    Mask1[2] = PermMask[2];
6360    Mask1[3] = PermMask[3];
6361    if (Mask1[2] >= 0)
6362      Mask1[2] += 4;
6363    if (Mask1[3] >= 0)
6364      Mask1[3] += 4;
6365    return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
6366  }
6367
6368  // Break it into (shuffle shuffle_hi, shuffle_lo).
6369  int LoMask[] = { -1, -1, -1, -1 };
6370  int HiMask[] = { -1, -1, -1, -1 };
6371
6372  int *MaskPtr = LoMask;
6373  unsigned MaskIdx = 0;
6374  unsigned LoIdx = 0;
6375  unsigned HiIdx = 2;
6376  for (unsigned i = 0; i != 4; ++i) {
6377    if (i == 2) {
6378      MaskPtr = HiMask;
6379      MaskIdx = 1;
6380      LoIdx = 0;
6381      HiIdx = 2;
6382    }
6383    int Idx = PermMask[i];
6384    if (Idx < 0) {
6385      Locs[i] = std::make_pair(-1, -1);
6386    } else if (Idx < 4) {
6387      Locs[i] = std::make_pair(MaskIdx, LoIdx);
6388      MaskPtr[LoIdx] = Idx;
6389      LoIdx++;
6390    } else {
6391      Locs[i] = std::make_pair(MaskIdx, HiIdx);
6392      MaskPtr[HiIdx] = Idx;
6393      HiIdx++;
6394    }
6395  }
6396
6397  SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
6398  SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
6399  int MaskOps[] = { -1, -1, -1, -1 };
6400  for (unsigned i = 0; i != 4; ++i)
6401    if (Locs[i].first != -1)
6402      MaskOps[i] = Locs[i].first * 4 + Locs[i].second;
6403  return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
6404}
6405
6406static bool MayFoldVectorLoad(SDValue V) {
6407  if (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
6408    V = V.getOperand(0);
6409  if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
6410    V = V.getOperand(0);
6411  if (V.hasOneUse() && V.getOpcode() == ISD::BUILD_VECTOR &&
6412      V.getNumOperands() == 2 && V.getOperand(1).getOpcode() == ISD::UNDEF)
6413    // BUILD_VECTOR (load), undef
6414    V = V.getOperand(0);
6415  if (MayFoldLoad(V))
6416    return true;
6417  return false;
6418}
6419
6420// FIXME: the version above should always be used. Since there's
6421// a bug where several vector shuffles can't be folded because the
6422// DAG is not updated during lowering and a node claims to have two
6423// uses while it only has one, use this version, and let isel match
6424// another instruction if the load really happens to have more than
6425// one use. Remove this version after this bug get fixed.
6426// rdar://8434668, PR8156
6427static bool RelaxedMayFoldVectorLoad(SDValue V) {
6428  if (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
6429    V = V.getOperand(0);
6430  if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
6431    V = V.getOperand(0);
6432  if (ISD::isNormalLoad(V.getNode()))
6433    return true;
6434  return false;
6435}
6436
6437static
6438SDValue getMOVDDup(SDValue &Op, DebugLoc &dl, SDValue V1, SelectionDAG &DAG) {
6439  EVT VT = Op.getValueType();
6440
6441  // Canonizalize to v2f64.
6442  V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
6443  return DAG.getNode(ISD::BITCAST, dl, VT,
6444                     getTargetShuffleNode(X86ISD::MOVDDUP, dl, MVT::v2f64,
6445                                          V1, DAG));
6446}
6447
6448static
6449SDValue getMOVLowToHigh(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG,
6450                        bool HasSSE2) {
6451  SDValue V1 = Op.getOperand(0);
6452  SDValue V2 = Op.getOperand(1);
6453  EVT VT = Op.getValueType();
6454
6455  assert(VT != MVT::v2i64 && "unsupported shuffle type");
6456
6457  if (HasSSE2 && VT == MVT::v2f64)
6458    return getTargetShuffleNode(X86ISD::MOVLHPD, dl, VT, V1, V2, DAG);
6459
6460  // v4f32 or v4i32: canonizalized to v4f32 (which is legal for SSE1)
6461  return DAG.getNode(ISD::BITCAST, dl, VT,
6462                     getTargetShuffleNode(X86ISD::MOVLHPS, dl, MVT::v4f32,
6463                           DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V1),
6464                           DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V2), DAG));
6465}
6466
6467static
6468SDValue getMOVHighToLow(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG) {
6469  SDValue V1 = Op.getOperand(0);
6470  SDValue V2 = Op.getOperand(1);
6471  EVT VT = Op.getValueType();
6472
6473  assert((VT == MVT::v4i32 || VT == MVT::v4f32) &&
6474         "unsupported shuffle type");
6475
6476  if (V2.getOpcode() == ISD::UNDEF)
6477    V2 = V1;
6478
6479  // v4i32 or v4f32
6480  return getTargetShuffleNode(X86ISD::MOVHLPS, dl, VT, V1, V2, DAG);
6481}
6482
6483static
6484SDValue getMOVLP(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG, bool HasSSE2) {
6485  SDValue V1 = Op.getOperand(0);
6486  SDValue V2 = Op.getOperand(1);
6487  EVT VT = Op.getValueType();
6488  unsigned NumElems = VT.getVectorNumElements();
6489
6490  // Use MOVLPS and MOVLPD in case V1 or V2 are loads. During isel, the second
6491  // operand of these instructions is only memory, so check if there's a
6492  // potencial load folding here, otherwise use SHUFPS or MOVSD to match the
6493  // same masks.
6494  bool CanFoldLoad = false;
6495
6496  // Trivial case, when V2 comes from a load.
6497  if (MayFoldVectorLoad(V2))
6498    CanFoldLoad = true;
6499
6500  // When V1 is a load, it can be folded later into a store in isel, example:
6501  //  (store (v4f32 (X86Movlps (load addr:$src1), VR128:$src2)), addr:$src1)
6502  //    turns into:
6503  //  (MOVLPSmr addr:$src1, VR128:$src2)
6504  // So, recognize this potential and also use MOVLPS or MOVLPD
6505  else if (MayFoldVectorLoad(V1) && MayFoldIntoStore(Op))
6506    CanFoldLoad = true;
6507
6508  ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6509  if (CanFoldLoad) {
6510    if (HasSSE2 && NumElems == 2)
6511      return getTargetShuffleNode(X86ISD::MOVLPD, dl, VT, V1, V2, DAG);
6512
6513    if (NumElems == 4)
6514      // If we don't care about the second element, proceed to use movss.
6515      if (SVOp->getMaskElt(1) != -1)
6516        return getTargetShuffleNode(X86ISD::MOVLPS, dl, VT, V1, V2, DAG);
6517  }
6518
6519  // movl and movlp will both match v2i64, but v2i64 is never matched by
6520  // movl earlier because we make it strict to avoid messing with the movlp load
6521  // folding logic (see the code above getMOVLP call). Match it here then,
6522  // this is horrible, but will stay like this until we move all shuffle
6523  // matching to x86 specific nodes. Note that for the 1st condition all
6524  // types are matched with movsd.
6525  if (HasSSE2) {
6526    // FIXME: isMOVLMask should be checked and matched before getMOVLP,
6527    // as to remove this logic from here, as much as possible
6528    if (NumElems == 2 || !isMOVLMask(SVOp->getMask(), VT))
6529      return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
6530    return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
6531  }
6532
6533  assert(VT != MVT::v4i32 && "unsupported shuffle type");
6534
6535  // Invert the operand order and use SHUFPS to match it.
6536  return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V2, V1,
6537                              getShuffleSHUFImmediate(SVOp), DAG);
6538}
6539
6540SDValue
6541X86TargetLowering::NormalizeVectorShuffle(SDValue Op, SelectionDAG &DAG) const {
6542  ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6543  EVT VT = Op.getValueType();
6544  DebugLoc dl = Op.getDebugLoc();
6545  SDValue V1 = Op.getOperand(0);
6546  SDValue V2 = Op.getOperand(1);
6547
6548  if (isZeroShuffle(SVOp))
6549    return getZeroVector(VT, Subtarget, DAG, dl);
6550
6551  // Handle splat operations
6552  if (SVOp->isSplat()) {
6553    unsigned NumElem = VT.getVectorNumElements();
6554    int Size = VT.getSizeInBits();
6555
6556    // Use vbroadcast whenever the splat comes from a foldable load
6557    SDValue Broadcast = LowerVectorBroadcast(Op, DAG);
6558    if (Broadcast.getNode())
6559      return Broadcast;
6560
6561    // Handle splats by matching through known shuffle masks
6562    if ((Size == 128 && NumElem <= 4) ||
6563        (Size == 256 && NumElem < 8))
6564      return SDValue();
6565
6566    // All remaning splats are promoted to target supported vector shuffles.
6567    return PromoteSplat(SVOp, DAG);
6568  }
6569
6570  // If the shuffle can be profitably rewritten as a narrower shuffle, then
6571  // do it!
6572  if (VT == MVT::v8i16  || VT == MVT::v16i8 ||
6573      VT == MVT::v16i16 || VT == MVT::v32i8) {
6574    SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
6575    if (NewOp.getNode())
6576      return DAG.getNode(ISD::BITCAST, dl, VT, NewOp);
6577  } else if ((VT == MVT::v4i32 ||
6578             (VT == MVT::v4f32 && Subtarget->hasSSE2()))) {
6579    // FIXME: Figure out a cleaner way to do this.
6580    // Try to make use of movq to zero out the top part.
6581    if (ISD::isBuildVectorAllZeros(V2.getNode())) {
6582      SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
6583      if (NewOp.getNode()) {
6584        EVT NewVT = NewOp.getValueType();
6585        if (isCommutedMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(),
6586                               NewVT, true, false))
6587          return getVZextMovL(VT, NewVT, NewOp.getOperand(0),
6588                              DAG, Subtarget, dl);
6589      }
6590    } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
6591      SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
6592      if (NewOp.getNode()) {
6593        EVT NewVT = NewOp.getValueType();
6594        if (isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(), NewVT))
6595          return getVZextMovL(VT, NewVT, NewOp.getOperand(1),
6596                              DAG, Subtarget, dl);
6597      }
6598    }
6599  }
6600  return SDValue();
6601}
6602
6603SDValue
6604X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) const {
6605  ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6606  SDValue V1 = Op.getOperand(0);
6607  SDValue V2 = Op.getOperand(1);
6608  EVT VT = Op.getValueType();
6609  DebugLoc dl = Op.getDebugLoc();
6610  unsigned NumElems = VT.getVectorNumElements();
6611  bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
6612  bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
6613  bool V1IsSplat = false;
6614  bool V2IsSplat = false;
6615  bool HasSSE2 = Subtarget->hasSSE2();
6616  bool HasAVX    = Subtarget->hasAVX();
6617  bool HasAVX2   = Subtarget->hasAVX2();
6618  MachineFunction &MF = DAG.getMachineFunction();
6619  bool OptForSize = MF.getFunction()->hasFnAttr(Attribute::OptimizeForSize);
6620
6621  assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
6622
6623  if (V1IsUndef && V2IsUndef)
6624    return DAG.getUNDEF(VT);
6625
6626  assert(!V1IsUndef && "Op 1 of shuffle should not be undef");
6627
6628  // Vector shuffle lowering takes 3 steps:
6629  //
6630  // 1) Normalize the input vectors. Here splats, zeroed vectors, profitable
6631  //    narrowing and commutation of operands should be handled.
6632  // 2) Matching of shuffles with known shuffle masks to x86 target specific
6633  //    shuffle nodes.
6634  // 3) Rewriting of unmatched masks into new generic shuffle operations,
6635  //    so the shuffle can be broken into other shuffles and the legalizer can
6636  //    try the lowering again.
6637  //
6638  // The general idea is that no vector_shuffle operation should be left to
6639  // be matched during isel, all of them must be converted to a target specific
6640  // node here.
6641
6642  // Normalize the input vectors. Here splats, zeroed vectors, profitable
6643  // narrowing and commutation of operands should be handled. The actual code
6644  // doesn't include all of those, work in progress...
6645  SDValue NewOp = NormalizeVectorShuffle(Op, DAG);
6646  if (NewOp.getNode())
6647    return NewOp;
6648
6649  SmallVector<int, 8> M(SVOp->getMask().begin(), SVOp->getMask().end());
6650
6651  // NOTE: isPSHUFDMask can also match both masks below (unpckl_undef and
6652  // unpckh_undef). Only use pshufd if speed is more important than size.
6653  if (OptForSize && isUNPCKL_v_undef_Mask(M, VT, HasAVX2))
6654    return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
6655  if (OptForSize && isUNPCKH_v_undef_Mask(M, VT, HasAVX2))
6656    return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
6657
6658  if (isMOVDDUPMask(M, VT) && Subtarget->hasSSE3() &&
6659      V2IsUndef && RelaxedMayFoldVectorLoad(V1))
6660    return getMOVDDup(Op, dl, V1, DAG);
6661
6662  if (isMOVHLPS_v_undef_Mask(M, VT))
6663    return getMOVHighToLow(Op, dl, DAG);
6664
6665  // Use to match splats
6666  if (HasSSE2 && isUNPCKHMask(M, VT, HasAVX2) && V2IsUndef &&
6667      (VT == MVT::v2f64 || VT == MVT::v2i64))
6668    return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
6669
6670  if (isPSHUFDMask(M, VT)) {
6671    // The actual implementation will match the mask in the if above and then
6672    // during isel it can match several different instructions, not only pshufd
6673    // as its name says, sad but true, emulate the behavior for now...
6674    if (isMOVDDUPMask(M, VT) && ((VT == MVT::v4f32 || VT == MVT::v2i64)))
6675      return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V1, DAG);
6676
6677    unsigned TargetMask = getShuffleSHUFImmediate(SVOp);
6678
6679    if (HasAVX && (VT == MVT::v4f32 || VT == MVT::v2f64))
6680      return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1, TargetMask, DAG);
6681
6682    if (HasSSE2 && (VT == MVT::v4f32 || VT == MVT::v4i32))
6683      return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1, TargetMask, DAG);
6684
6685    return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V1,
6686                                TargetMask, DAG);
6687  }
6688
6689  // Check if this can be converted into a logical shift.
6690  bool isLeft = false;
6691  unsigned ShAmt = 0;
6692  SDValue ShVal;
6693  bool isShift = HasSSE2 && isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
6694  if (isShift && ShVal.hasOneUse()) {
6695    // If the shifted value has multiple uses, it may be cheaper to use
6696    // v_set0 + movlhps or movhlps, etc.
6697    EVT EltVT = VT.getVectorElementType();
6698    ShAmt *= EltVT.getSizeInBits();
6699    return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
6700  }
6701
6702  if (isMOVLMask(M, VT)) {
6703    if (ISD::isBuildVectorAllZeros(V1.getNode()))
6704      return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
6705    if (!isMOVLPMask(M, VT)) {
6706      if (HasSSE2 && (VT == MVT::v2i64 || VT == MVT::v2f64))
6707        return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
6708
6709      if (VT == MVT::v4i32 || VT == MVT::v4f32)
6710        return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
6711    }
6712  }
6713
6714  // FIXME: fold these into legal mask.
6715  if (isMOVLHPSMask(M, VT) && !isUNPCKLMask(M, VT, HasAVX2))
6716    return getMOVLowToHigh(Op, dl, DAG, HasSSE2);
6717
6718  if (isMOVHLPSMask(M, VT))
6719    return getMOVHighToLow(Op, dl, DAG);
6720
6721  if (V2IsUndef && isMOVSHDUPMask(M, VT, Subtarget))
6722    return getTargetShuffleNode(X86ISD::MOVSHDUP, dl, VT, V1, DAG);
6723
6724  if (V2IsUndef && isMOVSLDUPMask(M, VT, Subtarget))
6725    return getTargetShuffleNode(X86ISD::MOVSLDUP, dl, VT, V1, DAG);
6726
6727  if (isMOVLPMask(M, VT))
6728    return getMOVLP(Op, dl, DAG, HasSSE2);
6729
6730  if (ShouldXformToMOVHLPS(M, VT) ||
6731      ShouldXformToMOVLP(V1.getNode(), V2.getNode(), M, VT))
6732    return CommuteVectorShuffle(SVOp, DAG);
6733
6734  if (isShift) {
6735    // No better options. Use a vshldq / vsrldq.
6736    EVT EltVT = VT.getVectorElementType();
6737    ShAmt *= EltVT.getSizeInBits();
6738    return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
6739  }
6740
6741  bool Commuted = false;
6742  // FIXME: This should also accept a bitcast of a splat?  Be careful, not
6743  // 1,1,1,1 -> v8i16 though.
6744  V1IsSplat = isSplatVector(V1.getNode());
6745  V2IsSplat = isSplatVector(V2.getNode());
6746
6747  // Canonicalize the splat or undef, if present, to be on the RHS.
6748  if (!V2IsUndef && V1IsSplat && !V2IsSplat) {
6749    CommuteVectorShuffleMask(M, NumElems);
6750    std::swap(V1, V2);
6751    std::swap(V1IsSplat, V2IsSplat);
6752    Commuted = true;
6753  }
6754
6755  if (isCommutedMOVLMask(M, VT, V2IsSplat, V2IsUndef)) {
6756    // Shuffling low element of v1 into undef, just return v1.
6757    if (V2IsUndef)
6758      return V1;
6759    // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
6760    // the instruction selector will not match, so get a canonical MOVL with
6761    // swapped operands to undo the commute.
6762    return getMOVL(DAG, dl, VT, V2, V1);
6763  }
6764
6765  if (isUNPCKLMask(M, VT, HasAVX2))
6766    return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
6767
6768  if (isUNPCKHMask(M, VT, HasAVX2))
6769    return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
6770
6771  if (V2IsSplat) {
6772    // Normalize mask so all entries that point to V2 points to its first
6773    // element then try to match unpck{h|l} again. If match, return a
6774    // new vector_shuffle with the corrected mask.p
6775    SmallVector<int, 8> NewMask(M.begin(), M.end());
6776    NormalizeMask(NewMask, NumElems);
6777    if (isUNPCKLMask(NewMask, VT, HasAVX2, true))
6778      return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
6779    if (isUNPCKHMask(NewMask, VT, HasAVX2, true))
6780      return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
6781  }
6782
6783  if (Commuted) {
6784    // Commute is back and try unpck* again.
6785    // FIXME: this seems wrong.
6786    CommuteVectorShuffleMask(M, NumElems);
6787    std::swap(V1, V2);
6788    std::swap(V1IsSplat, V2IsSplat);
6789    Commuted = false;
6790
6791    if (isUNPCKLMask(M, VT, HasAVX2))
6792      return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
6793
6794    if (isUNPCKHMask(M, VT, HasAVX2))
6795      return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
6796  }
6797
6798  // Normalize the node to match x86 shuffle ops if needed
6799  if (!V2IsUndef && (isSHUFPMask(M, VT, HasAVX, /* Commuted */ true)))
6800    return CommuteVectorShuffle(SVOp, DAG);
6801
6802  // The checks below are all present in isShuffleMaskLegal, but they are
6803  // inlined here right now to enable us to directly emit target specific
6804  // nodes, and remove one by one until they don't return Op anymore.
6805
6806  if (isPALIGNRMask(M, VT, Subtarget))
6807    return getTargetShuffleNode(X86ISD::PALIGN, dl, VT, V1, V2,
6808                                getShufflePALIGNRImmediate(SVOp),
6809                                DAG);
6810
6811  if (ShuffleVectorSDNode::isSplatMask(&M[0], VT) &&
6812      SVOp->getSplatIndex() == 0 && V2IsUndef) {
6813    if (VT == MVT::v2f64 || VT == MVT::v2i64)
6814      return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
6815  }
6816
6817  if (isPSHUFHWMask(M, VT, HasAVX2))
6818    return getTargetShuffleNode(X86ISD::PSHUFHW, dl, VT, V1,
6819                                getShufflePSHUFHWImmediate(SVOp),
6820                                DAG);
6821
6822  if (isPSHUFLWMask(M, VT, HasAVX2))
6823    return getTargetShuffleNode(X86ISD::PSHUFLW, dl, VT, V1,
6824                                getShufflePSHUFLWImmediate(SVOp),
6825                                DAG);
6826
6827  if (isSHUFPMask(M, VT, HasAVX))
6828    return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V2,
6829                                getShuffleSHUFImmediate(SVOp), DAG);
6830
6831  if (isUNPCKL_v_undef_Mask(M, VT, HasAVX2))
6832    return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
6833  if (isUNPCKH_v_undef_Mask(M, VT, HasAVX2))
6834    return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
6835
6836  //===--------------------------------------------------------------------===//
6837  // Generate target specific nodes for 128 or 256-bit shuffles only
6838  // supported in the AVX instruction set.
6839  //
6840
6841  // Handle VMOVDDUPY permutations
6842  if (V2IsUndef && isMOVDDUPYMask(M, VT, HasAVX))
6843    return getTargetShuffleNode(X86ISD::MOVDDUP, dl, VT, V1, DAG);
6844
6845  // Handle VPERMILPS/D* permutations
6846  if (isVPERMILPMask(M, VT, HasAVX)) {
6847    if (HasAVX2 && VT == MVT::v8i32)
6848      return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1,
6849                                  getShuffleSHUFImmediate(SVOp), DAG);
6850    return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1,
6851                                getShuffleSHUFImmediate(SVOp), DAG);
6852  }
6853
6854  // Handle VPERM2F128/VPERM2I128 permutations
6855  if (isVPERM2X128Mask(M, VT, HasAVX))
6856    return getTargetShuffleNode(X86ISD::VPERM2X128, dl, VT, V1,
6857                                V2, getShuffleVPERM2X128Immediate(SVOp), DAG);
6858
6859  SDValue BlendOp = LowerVECTOR_SHUFFLEtoBlend(SVOp, Subtarget, DAG);
6860  if (BlendOp.getNode())
6861    return BlendOp;
6862
6863  if (V2IsUndef && HasAVX2 && (VT == MVT::v8i32 || VT == MVT::v8f32)) {
6864    SmallVector<SDValue, 8> permclMask;
6865    for (unsigned i = 0; i != 8; ++i) {
6866      permclMask.push_back(DAG.getConstant((M[i]>=0) ? M[i] : 0, MVT::i32));
6867    }
6868    SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32,
6869                               &permclMask[0], 8);
6870    // Bitcast is for VPERMPS since mask is v8i32 but node takes v8f32
6871    return DAG.getNode(X86ISD::VPERMV, dl, VT,
6872                       DAG.getNode(ISD::BITCAST, dl, VT, Mask), V1);
6873  }
6874
6875  if (V2IsUndef && HasAVX2 && (VT == MVT::v4i64 || VT == MVT::v4f64))
6876    return getTargetShuffleNode(X86ISD::VPERMI, dl, VT, V1,
6877                                getShuffleCLImmediate(SVOp), DAG);
6878
6879
6880  //===--------------------------------------------------------------------===//
6881  // Since no target specific shuffle was selected for this generic one,
6882  // lower it into other known shuffles. FIXME: this isn't true yet, but
6883  // this is the plan.
6884  //
6885
6886  // Handle v8i16 specifically since SSE can do byte extraction and insertion.
6887  if (VT == MVT::v8i16) {
6888    SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(Op, DAG);
6889    if (NewOp.getNode())
6890      return NewOp;
6891  }
6892
6893  if (VT == MVT::v16i8) {
6894    SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, DAG, *this);
6895    if (NewOp.getNode())
6896      return NewOp;
6897  }
6898
6899  if (VT == MVT::v32i8) {
6900    SDValue NewOp = LowerVECTOR_SHUFFLEv32i8(SVOp, DAG, *this);
6901    if (NewOp.getNode())
6902      return NewOp;
6903  }
6904
6905  // Handle all 128-bit wide vectors with 4 elements, and match them with
6906  // several different shuffle types.
6907  if (NumElems == 4 && VT.is128BitVector())
6908    return LowerVECTOR_SHUFFLE_128v4(SVOp, DAG);
6909
6910  // Handle general 256-bit shuffles
6911  if (VT.is256BitVector())
6912    return LowerVECTOR_SHUFFLE_256(SVOp, DAG);
6913
6914  return SDValue();
6915}
6916
6917SDValue
6918X86TargetLowering::LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op,
6919                                                SelectionDAG &DAG) const {
6920  EVT VT = Op.getValueType();
6921  DebugLoc dl = Op.getDebugLoc();
6922
6923  if (!Op.getOperand(0).getValueType().is128BitVector())
6924    return SDValue();
6925
6926  if (VT.getSizeInBits() == 8) {
6927    SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
6928                                    Op.getOperand(0), Op.getOperand(1));
6929    SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
6930                                    DAG.getValueType(VT));
6931    return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
6932  }
6933
6934  if (VT.getSizeInBits() == 16) {
6935    unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6936    // If Idx is 0, it's cheaper to do a move instead of a pextrw.
6937    if (Idx == 0)
6938      return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
6939                         DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
6940                                     DAG.getNode(ISD::BITCAST, dl,
6941                                                 MVT::v4i32,
6942                                                 Op.getOperand(0)),
6943                                     Op.getOperand(1)));
6944    SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
6945                                    Op.getOperand(0), Op.getOperand(1));
6946    SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
6947                                    DAG.getValueType(VT));
6948    return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
6949  }
6950
6951  if (VT == MVT::f32) {
6952    // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
6953    // the result back to FR32 register. It's only worth matching if the
6954    // result has a single use which is a store or a bitcast to i32.  And in
6955    // the case of a store, it's not worth it if the index is a constant 0,
6956    // because a MOVSSmr can be used instead, which is smaller and faster.
6957    if (!Op.hasOneUse())
6958      return SDValue();
6959    SDNode *User = *Op.getNode()->use_begin();
6960    if ((User->getOpcode() != ISD::STORE ||
6961         (isa<ConstantSDNode>(Op.getOperand(1)) &&
6962          cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
6963        (User->getOpcode() != ISD::BITCAST ||
6964         User->getValueType(0) != MVT::i32))
6965      return SDValue();
6966    SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
6967                                  DAG.getNode(ISD::BITCAST, dl, MVT::v4i32,
6968                                              Op.getOperand(0)),
6969                                              Op.getOperand(1));
6970    return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Extract);
6971  }
6972
6973  if (VT == MVT::i32 || VT == MVT::i64) {
6974    // ExtractPS/pextrq works with constant index.
6975    if (isa<ConstantSDNode>(Op.getOperand(1)))
6976      return Op;
6977  }
6978  return SDValue();
6979}
6980
6981
6982SDValue
6983X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
6984                                           SelectionDAG &DAG) const {
6985  if (!isa<ConstantSDNode>(Op.getOperand(1)))
6986    return SDValue();
6987
6988  SDValue Vec = Op.getOperand(0);
6989  EVT VecVT = Vec.getValueType();
6990
6991  // If this is a 256-bit vector result, first extract the 128-bit vector and
6992  // then extract the element from the 128-bit vector.
6993  if (VecVT.is256BitVector()) {
6994    DebugLoc dl = Op.getNode()->getDebugLoc();
6995    unsigned NumElems = VecVT.getVectorNumElements();
6996    SDValue Idx = Op.getOperand(1);
6997    unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
6998
6999    // Get the 128-bit vector.
7000    Vec = Extract128BitVector(Vec, IdxVal, DAG, dl);
7001
7002    if (IdxVal >= NumElems/2)
7003      IdxVal -= NumElems/2;
7004    return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
7005                       DAG.getConstant(IdxVal, MVT::i32));
7006  }
7007
7008  assert(VecVT.is128BitVector() && "Unexpected vector length");
7009
7010  if (Subtarget->hasSSE41()) {
7011    SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
7012    if (Res.getNode())
7013      return Res;
7014  }
7015
7016  EVT VT = Op.getValueType();
7017  DebugLoc dl = Op.getDebugLoc();
7018  // TODO: handle v16i8.
7019  if (VT.getSizeInBits() == 16) {
7020    SDValue Vec = Op.getOperand(0);
7021    unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7022    if (Idx == 0)
7023      return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
7024                         DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
7025                                     DAG.getNode(ISD::BITCAST, dl,
7026                                                 MVT::v4i32, Vec),
7027                                     Op.getOperand(1)));
7028    // Transform it so it match pextrw which produces a 32-bit result.
7029    EVT EltVT = MVT::i32;
7030    SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
7031                                    Op.getOperand(0), Op.getOperand(1));
7032    SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
7033                                    DAG.getValueType(VT));
7034    return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
7035  }
7036
7037  if (VT.getSizeInBits() == 32) {
7038    unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7039    if (Idx == 0)
7040      return Op;
7041
7042    // SHUFPS the element to the lowest double word, then movss.
7043    int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
7044    EVT VVT = Op.getOperand(0).getValueType();
7045    SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
7046                                       DAG.getUNDEF(VVT), Mask);
7047    return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
7048                       DAG.getIntPtrConstant(0));
7049  }
7050
7051  if (VT.getSizeInBits() == 64) {
7052    // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
7053    // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
7054    //        to match extract_elt for f64.
7055    unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7056    if (Idx == 0)
7057      return Op;
7058
7059    // UNPCKHPD the element to the lowest double word, then movsd.
7060    // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
7061    // to a f64mem, the whole operation is folded into a single MOVHPDmr.
7062    int Mask[2] = { 1, -1 };
7063    EVT VVT = Op.getOperand(0).getValueType();
7064    SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
7065                                       DAG.getUNDEF(VVT), Mask);
7066    return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
7067                       DAG.getIntPtrConstant(0));
7068  }
7069
7070  return SDValue();
7071}
7072
7073SDValue
7074X86TargetLowering::LowerINSERT_VECTOR_ELT_SSE4(SDValue Op,
7075                                               SelectionDAG &DAG) const {
7076  EVT VT = Op.getValueType();
7077  EVT EltVT = VT.getVectorElementType();
7078  DebugLoc dl = Op.getDebugLoc();
7079
7080  SDValue N0 = Op.getOperand(0);
7081  SDValue N1 = Op.getOperand(1);
7082  SDValue N2 = Op.getOperand(2);
7083
7084  if (!VT.is128BitVector())
7085    return SDValue();
7086
7087  if ((EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) &&
7088      isa<ConstantSDNode>(N2)) {
7089    unsigned Opc;
7090    if (VT == MVT::v8i16)
7091      Opc = X86ISD::PINSRW;
7092    else if (VT == MVT::v16i8)
7093      Opc = X86ISD::PINSRB;
7094    else
7095      Opc = X86ISD::PINSRB;
7096
7097    // Transform it so it match pinsr{b,w} which expects a GR32 as its second
7098    // argument.
7099    if (N1.getValueType() != MVT::i32)
7100      N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
7101    if (N2.getValueType() != MVT::i32)
7102      N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
7103    return DAG.getNode(Opc, dl, VT, N0, N1, N2);
7104  }
7105
7106  if (EltVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
7107    // Bits [7:6] of the constant are the source select.  This will always be
7108    //  zero here.  The DAG Combiner may combine an extract_elt index into these
7109    //  bits.  For example (insert (extract, 3), 2) could be matched by putting
7110    //  the '3' into bits [7:6] of X86ISD::INSERTPS.
7111    // Bits [5:4] of the constant are the destination select.  This is the
7112    //  value of the incoming immediate.
7113    // Bits [3:0] of the constant are the zero mask.  The DAG Combiner may
7114    //   combine either bitwise AND or insert of float 0.0 to set these bits.
7115    N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
7116    // Create this as a scalar to vector..
7117    N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
7118    return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
7119  }
7120
7121  if ((EltVT == MVT::i32 || EltVT == MVT::i64) && isa<ConstantSDNode>(N2)) {
7122    // PINSR* works with constant index.
7123    return Op;
7124  }
7125  return SDValue();
7126}
7127
7128SDValue
7129X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) const {
7130  EVT VT = Op.getValueType();
7131  EVT EltVT = VT.getVectorElementType();
7132
7133  DebugLoc dl = Op.getDebugLoc();
7134  SDValue N0 = Op.getOperand(0);
7135  SDValue N1 = Op.getOperand(1);
7136  SDValue N2 = Op.getOperand(2);
7137
7138  // If this is a 256-bit vector result, first extract the 128-bit vector,
7139  // insert the element into the extracted half and then place it back.
7140  if (VT.is256BitVector()) {
7141    if (!isa<ConstantSDNode>(N2))
7142      return SDValue();
7143
7144    // Get the desired 128-bit vector half.
7145    unsigned NumElems = VT.getVectorNumElements();
7146    unsigned IdxVal = cast<ConstantSDNode>(N2)->getZExtValue();
7147    SDValue V = Extract128BitVector(N0, IdxVal, DAG, dl);
7148
7149    // Insert the element into the desired half.
7150    bool Upper = IdxVal >= NumElems/2;
7151    V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V, N1,
7152                 DAG.getConstant(Upper ? IdxVal-NumElems/2 : IdxVal, MVT::i32));
7153
7154    // Insert the changed part back to the 256-bit vector
7155    return Insert128BitVector(N0, V, IdxVal, DAG, dl);
7156  }
7157
7158  if (Subtarget->hasSSE41())
7159    return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
7160
7161  if (EltVT == MVT::i8)
7162    return SDValue();
7163
7164  if (EltVT.getSizeInBits() == 16 && isa<ConstantSDNode>(N2)) {
7165    // Transform it so it match pinsrw which expects a 16-bit value in a GR32
7166    // as its second argument.
7167    if (N1.getValueType() != MVT::i32)
7168      N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
7169    if (N2.getValueType() != MVT::i32)
7170      N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
7171    return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
7172  }
7173  return SDValue();
7174}
7175
7176SDValue
7177X86TargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) const {
7178  LLVMContext *Context = DAG.getContext();
7179  DebugLoc dl = Op.getDebugLoc();
7180  EVT OpVT = Op.getValueType();
7181
7182  // If this is a 256-bit vector result, first insert into a 128-bit
7183  // vector and then insert into the 256-bit vector.
7184  if (!OpVT.is128BitVector()) {
7185    // Insert into a 128-bit vector.
7186    EVT VT128 = EVT::getVectorVT(*Context,
7187                                 OpVT.getVectorElementType(),
7188                                 OpVT.getVectorNumElements() / 2);
7189
7190    Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
7191
7192    // Insert the 128-bit vector.
7193    return Insert128BitVector(DAG.getUNDEF(OpVT), Op, 0, DAG, dl);
7194  }
7195
7196  if (OpVT == MVT::v1i64 &&
7197      Op.getOperand(0).getValueType() == MVT::i64)
7198    return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
7199
7200  SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
7201  assert(OpVT.is128BitVector() && "Expected an SSE type!");
7202  return DAG.getNode(ISD::BITCAST, dl, OpVT,
7203                     DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,AnyExt));
7204}
7205
7206// Lower a node with an EXTRACT_SUBVECTOR opcode.  This may result in
7207// a simple subregister reference or explicit instructions to grab
7208// upper bits of a vector.
7209SDValue
7210X86TargetLowering::LowerEXTRACT_SUBVECTOR(SDValue Op, SelectionDAG &DAG) const {
7211  if (Subtarget->hasAVX()) {
7212    DebugLoc dl = Op.getNode()->getDebugLoc();
7213    SDValue Vec = Op.getNode()->getOperand(0);
7214    SDValue Idx = Op.getNode()->getOperand(1);
7215
7216    if (Op.getNode()->getValueType(0).is128BitVector() &&
7217        Vec.getNode()->getValueType(0).is256BitVector() &&
7218        isa<ConstantSDNode>(Idx)) {
7219      unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
7220      return Extract128BitVector(Vec, IdxVal, DAG, dl);
7221    }
7222  }
7223  return SDValue();
7224}
7225
7226// Lower a node with an INSERT_SUBVECTOR opcode.  This may result in a
7227// simple superregister reference or explicit instructions to insert
7228// the upper bits of a vector.
7229SDValue
7230X86TargetLowering::LowerINSERT_SUBVECTOR(SDValue Op, SelectionDAG &DAG) const {
7231  if (Subtarget->hasAVX()) {
7232    DebugLoc dl = Op.getNode()->getDebugLoc();
7233    SDValue Vec = Op.getNode()->getOperand(0);
7234    SDValue SubVec = Op.getNode()->getOperand(1);
7235    SDValue Idx = Op.getNode()->getOperand(2);
7236
7237    if (Op.getNode()->getValueType(0).is256BitVector() &&
7238        SubVec.getNode()->getValueType(0).is128BitVector() &&
7239        isa<ConstantSDNode>(Idx)) {
7240      unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
7241      return Insert128BitVector(Vec, SubVec, IdxVal, DAG, dl);
7242    }
7243  }
7244  return SDValue();
7245}
7246
7247// ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
7248// their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
7249// one of the above mentioned nodes. It has to be wrapped because otherwise
7250// Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
7251// be used to form addressing mode. These wrapped nodes will be selected
7252// into MOV32ri.
7253SDValue
7254X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
7255  ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
7256
7257  // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7258  // global base reg.
7259  unsigned char OpFlag = 0;
7260  unsigned WrapperKind = X86ISD::Wrapper;
7261  CodeModel::Model M = getTargetMachine().getCodeModel();
7262
7263  if (Subtarget->isPICStyleRIPRel() &&
7264      (M == CodeModel::Small || M == CodeModel::Kernel))
7265    WrapperKind = X86ISD::WrapperRIP;
7266  else if (Subtarget->isPICStyleGOT())
7267    OpFlag = X86II::MO_GOTOFF;
7268  else if (Subtarget->isPICStyleStubPIC())
7269    OpFlag = X86II::MO_PIC_BASE_OFFSET;
7270
7271  SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
7272                                             CP->getAlignment(),
7273                                             CP->getOffset(), OpFlag);
7274  DebugLoc DL = CP->getDebugLoc();
7275  Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7276  // With PIC, the address is actually $g + Offset.
7277  if (OpFlag) {
7278    Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7279                         DAG.getNode(X86ISD::GlobalBaseReg,
7280                                     DebugLoc(), getPointerTy()),
7281                         Result);
7282  }
7283
7284  return Result;
7285}
7286
7287SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
7288  JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
7289
7290  // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7291  // global base reg.
7292  unsigned char OpFlag = 0;
7293  unsigned WrapperKind = X86ISD::Wrapper;
7294  CodeModel::Model M = getTargetMachine().getCodeModel();
7295
7296  if (Subtarget->isPICStyleRIPRel() &&
7297      (M == CodeModel::Small || M == CodeModel::Kernel))
7298    WrapperKind = X86ISD::WrapperRIP;
7299  else if (Subtarget->isPICStyleGOT())
7300    OpFlag = X86II::MO_GOTOFF;
7301  else if (Subtarget->isPICStyleStubPIC())
7302    OpFlag = X86II::MO_PIC_BASE_OFFSET;
7303
7304  SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
7305                                          OpFlag);
7306  DebugLoc DL = JT->getDebugLoc();
7307  Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7308
7309  // With PIC, the address is actually $g + Offset.
7310  if (OpFlag)
7311    Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7312                         DAG.getNode(X86ISD::GlobalBaseReg,
7313                                     DebugLoc(), getPointerTy()),
7314                         Result);
7315
7316  return Result;
7317}
7318
7319SDValue
7320X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
7321  const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
7322
7323  // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7324  // global base reg.
7325  unsigned char OpFlag = 0;
7326  unsigned WrapperKind = X86ISD::Wrapper;
7327  CodeModel::Model M = getTargetMachine().getCodeModel();
7328
7329  if (Subtarget->isPICStyleRIPRel() &&
7330      (M == CodeModel::Small || M == CodeModel::Kernel)) {
7331    if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
7332      OpFlag = X86II::MO_GOTPCREL;
7333    WrapperKind = X86ISD::WrapperRIP;
7334  } else if (Subtarget->isPICStyleGOT()) {
7335    OpFlag = X86II::MO_GOT;
7336  } else if (Subtarget->isPICStyleStubPIC()) {
7337    OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
7338  } else if (Subtarget->isPICStyleStubNoDynamic()) {
7339    OpFlag = X86II::MO_DARWIN_NONLAZY;
7340  }
7341
7342  SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
7343
7344  DebugLoc DL = Op.getDebugLoc();
7345  Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7346
7347
7348  // With PIC, the address is actually $g + Offset.
7349  if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
7350      !Subtarget->is64Bit()) {
7351    Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7352                         DAG.getNode(X86ISD::GlobalBaseReg,
7353                                     DebugLoc(), getPointerTy()),
7354                         Result);
7355  }
7356
7357  // For symbols that require a load from a stub to get the address, emit the
7358  // load.
7359  if (isGlobalStubReference(OpFlag))
7360    Result = DAG.getLoad(getPointerTy(), DL, DAG.getEntryNode(), Result,
7361                         MachinePointerInfo::getGOT(), false, false, false, 0);
7362
7363  return Result;
7364}
7365
7366SDValue
7367X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
7368  // Create the TargetBlockAddressAddress node.
7369  unsigned char OpFlags =
7370    Subtarget->ClassifyBlockAddressReference();
7371  CodeModel::Model M = getTargetMachine().getCodeModel();
7372  const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
7373  DebugLoc dl = Op.getDebugLoc();
7374  SDValue Result = DAG.getBlockAddress(BA, getPointerTy(),
7375                                       /*isTarget=*/true, OpFlags);
7376
7377  if (Subtarget->isPICStyleRIPRel() &&
7378      (M == CodeModel::Small || M == CodeModel::Kernel))
7379    Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
7380  else
7381    Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
7382
7383  // With PIC, the address is actually $g + Offset.
7384  if (isGlobalRelativeToPICBase(OpFlags)) {
7385    Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
7386                         DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
7387                         Result);
7388  }
7389
7390  return Result;
7391}
7392
7393SDValue
7394X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, DebugLoc dl,
7395                                      int64_t Offset,
7396                                      SelectionDAG &DAG) const {
7397  // Create the TargetGlobalAddress node, folding in the constant
7398  // offset if it is legal.
7399  unsigned char OpFlags =
7400    Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
7401  CodeModel::Model M = getTargetMachine().getCodeModel();
7402  SDValue Result;
7403  if (OpFlags == X86II::MO_NO_FLAG &&
7404      X86::isOffsetSuitableForCodeModel(Offset, M)) {
7405    // A direct static reference to a global.
7406    Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
7407    Offset = 0;
7408  } else {
7409    Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
7410  }
7411
7412  if (Subtarget->isPICStyleRIPRel() &&
7413      (M == CodeModel::Small || M == CodeModel::Kernel))
7414    Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
7415  else
7416    Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
7417
7418  // With PIC, the address is actually $g + Offset.
7419  if (isGlobalRelativeToPICBase(OpFlags)) {
7420    Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
7421                         DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
7422                         Result);
7423  }
7424
7425  // For globals that require a load from a stub to get the address, emit the
7426  // load.
7427  if (isGlobalStubReference(OpFlags))
7428    Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
7429                         MachinePointerInfo::getGOT(), false, false, false, 0);
7430
7431  // If there was a non-zero offset that we didn't fold, create an explicit
7432  // addition for it.
7433  if (Offset != 0)
7434    Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
7435                         DAG.getConstant(Offset, getPointerTy()));
7436
7437  return Result;
7438}
7439
7440SDValue
7441X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
7442  const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
7443  int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
7444  return LowerGlobalAddress(GV, Op.getDebugLoc(), Offset, DAG);
7445}
7446
7447static SDValue
7448GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
7449           SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
7450           unsigned char OperandFlags, bool LocalDynamic = false) {
7451  MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7452  SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7453  DebugLoc dl = GA->getDebugLoc();
7454  SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7455                                           GA->getValueType(0),
7456                                           GA->getOffset(),
7457                                           OperandFlags);
7458
7459  X86ISD::NodeType CallType = LocalDynamic ? X86ISD::TLSBASEADDR
7460                                           : X86ISD::TLSADDR;
7461
7462  if (InFlag) {
7463    SDValue Ops[] = { Chain,  TGA, *InFlag };
7464    Chain = DAG.getNode(CallType, dl, NodeTys, Ops, 3);
7465  } else {
7466    SDValue Ops[]  = { Chain, TGA };
7467    Chain = DAG.getNode(CallType, dl, NodeTys, Ops, 2);
7468  }
7469
7470  // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
7471  MFI->setAdjustsStack(true);
7472
7473  SDValue Flag = Chain.getValue(1);
7474  return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
7475}
7476
7477// Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
7478static SDValue
7479LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7480                                const EVT PtrVT) {
7481  SDValue InFlag;
7482  DebugLoc dl = GA->getDebugLoc();  // ? function entry point might be better
7483  SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
7484                                     DAG.getNode(X86ISD::GlobalBaseReg,
7485                                                 DebugLoc(), PtrVT), InFlag);
7486  InFlag = Chain.getValue(1);
7487
7488  return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
7489}
7490
7491// Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
7492static SDValue
7493LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7494                                const EVT PtrVT) {
7495  return GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT,
7496                    X86::RAX, X86II::MO_TLSGD);
7497}
7498
7499static SDValue LowerToTLSLocalDynamicModel(GlobalAddressSDNode *GA,
7500                                           SelectionDAG &DAG,
7501                                           const EVT PtrVT,
7502                                           bool is64Bit) {
7503  DebugLoc dl = GA->getDebugLoc();
7504
7505  // Get the start address of the TLS block for this module.
7506  X86MachineFunctionInfo* MFI = DAG.getMachineFunction()
7507      .getInfo<X86MachineFunctionInfo>();
7508  MFI->incNumLocalDynamicTLSAccesses();
7509
7510  SDValue Base;
7511  if (is64Bit) {
7512    Base = GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT, X86::RAX,
7513                      X86II::MO_TLSLD, /*LocalDynamic=*/true);
7514  } else {
7515    SDValue InFlag;
7516    SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
7517        DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), PtrVT), InFlag);
7518    InFlag = Chain.getValue(1);
7519    Base = GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX,
7520                      X86II::MO_TLSLDM, /*LocalDynamic=*/true);
7521  }
7522
7523  // Note: the CleanupLocalDynamicTLSPass will remove redundant computations
7524  // of Base.
7525
7526  // Build x@dtpoff.
7527  unsigned char OperandFlags = X86II::MO_DTPOFF;
7528  unsigned WrapperKind = X86ISD::Wrapper;
7529  SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7530                                           GA->getValueType(0),
7531                                           GA->getOffset(), OperandFlags);
7532  SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
7533
7534  // Add x@dtpoff with the base.
7535  return DAG.getNode(ISD::ADD, dl, PtrVT, Offset, Base);
7536}
7537
7538// Lower ISD::GlobalTLSAddress using the "initial exec" or "local exec" model.
7539static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7540                                   const EVT PtrVT, TLSModel::Model model,
7541                                   bool is64Bit, bool isPIC) {
7542  DebugLoc dl = GA->getDebugLoc();
7543
7544  // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
7545  Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
7546                                                         is64Bit ? 257 : 256));
7547
7548  SDValue ThreadPointer = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
7549                                      DAG.getIntPtrConstant(0),
7550                                      MachinePointerInfo(Ptr),
7551                                      false, false, false, 0);
7552
7553  unsigned char OperandFlags = 0;
7554  // Most TLS accesses are not RIP relative, even on x86-64.  One exception is
7555  // initialexec.
7556  unsigned WrapperKind = X86ISD::Wrapper;
7557  if (model == TLSModel::LocalExec) {
7558    OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
7559  } else if (model == TLSModel::InitialExec) {
7560    if (is64Bit) {
7561      OperandFlags = X86II::MO_GOTTPOFF;
7562      WrapperKind = X86ISD::WrapperRIP;
7563    } else {
7564      OperandFlags = isPIC ? X86II::MO_GOTNTPOFF : X86II::MO_INDNTPOFF;
7565    }
7566  } else {
7567    llvm_unreachable("Unexpected model");
7568  }
7569
7570  // emit "addl x@ntpoff,%eax" (local exec)
7571  // or "addl x@indntpoff,%eax" (initial exec)
7572  // or "addl x@gotntpoff(%ebx) ,%eax" (initial exec, 32-bit pic)
7573  SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7574                                           GA->getValueType(0),
7575                                           GA->getOffset(), OperandFlags);
7576  SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
7577
7578  if (model == TLSModel::InitialExec) {
7579    if (isPIC && !is64Bit) {
7580      Offset = DAG.getNode(ISD::ADD, dl, PtrVT,
7581                          DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), PtrVT),
7582                           Offset);
7583    }
7584
7585    Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
7586                         MachinePointerInfo::getGOT(), false, false, false,
7587                         0);
7588  }
7589
7590  // The address of the thread local variable is the add of the thread
7591  // pointer with the offset of the variable.
7592  return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
7593}
7594
7595SDValue
7596X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
7597
7598  GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
7599  const GlobalValue *GV = GA->getGlobal();
7600
7601  if (Subtarget->isTargetELF()) {
7602    TLSModel::Model model = getTargetMachine().getTLSModel(GV);
7603
7604    switch (model) {
7605      case TLSModel::GeneralDynamic:
7606        if (Subtarget->is64Bit())
7607          return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
7608        return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
7609      case TLSModel::LocalDynamic:
7610        return LowerToTLSLocalDynamicModel(GA, DAG, getPointerTy(),
7611                                           Subtarget->is64Bit());
7612      case TLSModel::InitialExec:
7613      case TLSModel::LocalExec:
7614        return LowerToTLSExecModel(GA, DAG, getPointerTy(), model,
7615                                   Subtarget->is64Bit(),
7616                         getTargetMachine().getRelocationModel() == Reloc::PIC_);
7617    }
7618    llvm_unreachable("Unknown TLS model.");
7619  }
7620
7621  if (Subtarget->isTargetDarwin()) {
7622    // Darwin only has one model of TLS.  Lower to that.
7623    unsigned char OpFlag = 0;
7624    unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
7625                           X86ISD::WrapperRIP : X86ISD::Wrapper;
7626
7627    // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7628    // global base reg.
7629    bool PIC32 = (getTargetMachine().getRelocationModel() == Reloc::PIC_) &&
7630                  !Subtarget->is64Bit();
7631    if (PIC32)
7632      OpFlag = X86II::MO_TLVP_PIC_BASE;
7633    else
7634      OpFlag = X86II::MO_TLVP;
7635    DebugLoc DL = Op.getDebugLoc();
7636    SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
7637                                                GA->getValueType(0),
7638                                                GA->getOffset(), OpFlag);
7639    SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7640
7641    // With PIC32, the address is actually $g + Offset.
7642    if (PIC32)
7643      Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7644                           DAG.getNode(X86ISD::GlobalBaseReg,
7645                                       DebugLoc(), getPointerTy()),
7646                           Offset);
7647
7648    // Lowering the machine isd will make sure everything is in the right
7649    // location.
7650    SDValue Chain = DAG.getEntryNode();
7651    SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7652    SDValue Args[] = { Chain, Offset };
7653    Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args, 2);
7654
7655    // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
7656    MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7657    MFI->setAdjustsStack(true);
7658
7659    // And our return value (tls address) is in the standard call return value
7660    // location.
7661    unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
7662    return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy(),
7663                              Chain.getValue(1));
7664  }
7665
7666  if (Subtarget->isTargetWindows()) {
7667    // Just use the implicit TLS architecture
7668    // Need to generate someting similar to:
7669    //   mov     rdx, qword [gs:abs 58H]; Load pointer to ThreadLocalStorage
7670    //                                  ; from TEB
7671    //   mov     ecx, dword [rel _tls_index]: Load index (from C runtime)
7672    //   mov     rcx, qword [rdx+rcx*8]
7673    //   mov     eax, .tls$:tlsvar
7674    //   [rax+rcx] contains the address
7675    // Windows 64bit: gs:0x58
7676    // Windows 32bit: fs:__tls_array
7677
7678    // If GV is an alias then use the aliasee for determining
7679    // thread-localness.
7680    if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
7681      GV = GA->resolveAliasedGlobal(false);
7682    DebugLoc dl = GA->getDebugLoc();
7683    SDValue Chain = DAG.getEntryNode();
7684
7685    // Get the Thread Pointer, which is %fs:__tls_array (32-bit) or
7686    // %gs:0x58 (64-bit).
7687    Value *Ptr = Constant::getNullValue(Subtarget->is64Bit()
7688                                        ? Type::getInt8PtrTy(*DAG.getContext(),
7689                                                             256)
7690                                        : Type::getInt32PtrTy(*DAG.getContext(),
7691                                                              257));
7692
7693    SDValue ThreadPointer = DAG.getLoad(getPointerTy(), dl, Chain,
7694                                        Subtarget->is64Bit()
7695                                        ? DAG.getIntPtrConstant(0x58)
7696                                        : DAG.getExternalSymbol("_tls_array",
7697                                                                getPointerTy()),
7698                                        MachinePointerInfo(Ptr),
7699                                        false, false, false, 0);
7700
7701    // Load the _tls_index variable
7702    SDValue IDX = DAG.getExternalSymbol("_tls_index", getPointerTy());
7703    if (Subtarget->is64Bit())
7704      IDX = DAG.getExtLoad(ISD::ZEXTLOAD, dl, getPointerTy(), Chain,
7705                           IDX, MachinePointerInfo(), MVT::i32,
7706                           false, false, 0);
7707    else
7708      IDX = DAG.getLoad(getPointerTy(), dl, Chain, IDX, MachinePointerInfo(),
7709                        false, false, false, 0);
7710
7711    SDValue Scale = DAG.getConstant(Log2_64_Ceil(TD->getPointerSize()),
7712                                    getPointerTy());
7713    IDX = DAG.getNode(ISD::SHL, dl, getPointerTy(), IDX, Scale);
7714
7715    SDValue res = DAG.getNode(ISD::ADD, dl, getPointerTy(), ThreadPointer, IDX);
7716    res = DAG.getLoad(getPointerTy(), dl, Chain, res, MachinePointerInfo(),
7717                      false, false, false, 0);
7718
7719    // Get the offset of start of .tls section
7720    SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7721                                             GA->getValueType(0),
7722                                             GA->getOffset(), X86II::MO_SECREL);
7723    SDValue Offset = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), TGA);
7724
7725    // The address of the thread local variable is the add of the thread
7726    // pointer with the offset of the variable.
7727    return DAG.getNode(ISD::ADD, dl, getPointerTy(), res, Offset);
7728  }
7729
7730  llvm_unreachable("TLS not implemented for this target.");
7731}
7732
7733
7734/// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values
7735/// and take a 2 x i32 value to shift plus a shift amount.
7736SDValue X86TargetLowering::LowerShiftParts(SDValue Op, SelectionDAG &DAG) const{
7737  assert(Op.getNumOperands() == 3 && "Not a double-shift!");
7738  EVT VT = Op.getValueType();
7739  unsigned VTBits = VT.getSizeInBits();
7740  DebugLoc dl = Op.getDebugLoc();
7741  bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
7742  SDValue ShOpLo = Op.getOperand(0);
7743  SDValue ShOpHi = Op.getOperand(1);
7744  SDValue ShAmt  = Op.getOperand(2);
7745  SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
7746                                     DAG.getConstant(VTBits - 1, MVT::i8))
7747                       : DAG.getConstant(0, VT);
7748
7749  SDValue Tmp2, Tmp3;
7750  if (Op.getOpcode() == ISD::SHL_PARTS) {
7751    Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
7752    Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
7753  } else {
7754    Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
7755    Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, ShAmt);
7756  }
7757
7758  SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
7759                                DAG.getConstant(VTBits, MVT::i8));
7760  SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
7761                             AndNode, DAG.getConstant(0, MVT::i8));
7762
7763  SDValue Hi, Lo;
7764  SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
7765  SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
7766  SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
7767
7768  if (Op.getOpcode() == ISD::SHL_PARTS) {
7769    Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
7770    Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
7771  } else {
7772    Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
7773    Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
7774  }
7775
7776  SDValue Ops[2] = { Lo, Hi };
7777  return DAG.getMergeValues(Ops, 2, dl);
7778}
7779
7780SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
7781                                           SelectionDAG &DAG) const {
7782  EVT SrcVT = Op.getOperand(0).getValueType();
7783
7784  if (SrcVT.isVector())
7785    return SDValue();
7786
7787  assert(SrcVT.getSimpleVT() <= MVT::i64 && SrcVT.getSimpleVT() >= MVT::i16 &&
7788         "Unknown SINT_TO_FP to lower!");
7789
7790  // These are really Legal; return the operand so the caller accepts it as
7791  // Legal.
7792  if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
7793    return Op;
7794  if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
7795      Subtarget->is64Bit()) {
7796    return Op;
7797  }
7798
7799  DebugLoc dl = Op.getDebugLoc();
7800  unsigned Size = SrcVT.getSizeInBits()/8;
7801  MachineFunction &MF = DAG.getMachineFunction();
7802  int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
7803  SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7804  SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
7805                               StackSlot,
7806                               MachinePointerInfo::getFixedStack(SSFI),
7807                               false, false, 0);
7808  return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
7809}
7810
7811SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
7812                                     SDValue StackSlot,
7813                                     SelectionDAG &DAG) const {
7814  // Build the FILD
7815  DebugLoc DL = Op.getDebugLoc();
7816  SDVTList Tys;
7817  bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
7818  if (useSSE)
7819    Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
7820  else
7821    Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
7822
7823  unsigned ByteSize = SrcVT.getSizeInBits()/8;
7824
7825  FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
7826  MachineMemOperand *MMO;
7827  if (FI) {
7828    int SSFI = FI->getIndex();
7829    MMO =
7830      DAG.getMachineFunction()
7831      .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7832                            MachineMemOperand::MOLoad, ByteSize, ByteSize);
7833  } else {
7834    MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
7835    StackSlot = StackSlot.getOperand(1);
7836  }
7837  SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
7838  SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
7839                                           X86ISD::FILD, DL,
7840                                           Tys, Ops, array_lengthof(Ops),
7841                                           SrcVT, MMO);
7842
7843  if (useSSE) {
7844    Chain = Result.getValue(1);
7845    SDValue InFlag = Result.getValue(2);
7846
7847    // FIXME: Currently the FST is flagged to the FILD_FLAG. This
7848    // shouldn't be necessary except that RFP cannot be live across
7849    // multiple blocks. When stackifier is fixed, they can be uncoupled.
7850    MachineFunction &MF = DAG.getMachineFunction();
7851    unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
7852    int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
7853    SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7854    Tys = DAG.getVTList(MVT::Other);
7855    SDValue Ops[] = {
7856      Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
7857    };
7858    MachineMemOperand *MMO =
7859      DAG.getMachineFunction()
7860      .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7861                            MachineMemOperand::MOStore, SSFISize, SSFISize);
7862
7863    Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
7864                                    Ops, array_lengthof(Ops),
7865                                    Op.getValueType(), MMO);
7866    Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
7867                         MachinePointerInfo::getFixedStack(SSFI),
7868                         false, false, false, 0);
7869  }
7870
7871  return Result;
7872}
7873
7874// LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
7875SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
7876                                               SelectionDAG &DAG) const {
7877  // This algorithm is not obvious. Here it is what we're trying to output:
7878  /*
7879     movq       %rax,  %xmm0
7880     punpckldq  (c0),  %xmm0  // c0: (uint4){ 0x43300000U, 0x45300000U, 0U, 0U }
7881     subpd      (c1),  %xmm0  // c1: (double2){ 0x1.0p52, 0x1.0p52 * 0x1.0p32 }
7882     #ifdef __SSE3__
7883       haddpd   %xmm0, %xmm0
7884     #else
7885       pshufd   $0x4e, %xmm0, %xmm1
7886       addpd    %xmm1, %xmm0
7887     #endif
7888  */
7889
7890  DebugLoc dl = Op.getDebugLoc();
7891  LLVMContext *Context = DAG.getContext();
7892
7893  // Build some magic constants.
7894  const uint32_t CV0[] = { 0x43300000, 0x45300000, 0, 0 };
7895  Constant *C0 = ConstantDataVector::get(*Context, CV0);
7896  SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
7897
7898  SmallVector<Constant*,2> CV1;
7899  CV1.push_back(
7900        ConstantFP::get(*Context, APFloat(APInt(64, 0x4330000000000000ULL))));
7901  CV1.push_back(
7902        ConstantFP::get(*Context, APFloat(APInt(64, 0x4530000000000000ULL))));
7903  Constant *C1 = ConstantVector::get(CV1);
7904  SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
7905
7906  // Load the 64-bit value into an XMM register.
7907  SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
7908                            Op.getOperand(0));
7909  SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
7910                              MachinePointerInfo::getConstantPool(),
7911                              false, false, false, 16);
7912  SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32,
7913                              DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, XR1),
7914                              CLod0);
7915
7916  SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
7917                              MachinePointerInfo::getConstantPool(),
7918                              false, false, false, 16);
7919  SDValue XR2F = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Unpck1);
7920  SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
7921  SDValue Result;
7922
7923  if (Subtarget->hasSSE3()) {
7924    // FIXME: The 'haddpd' instruction may be slower than 'movhlps + addsd'.
7925    Result = DAG.getNode(X86ISD::FHADD, dl, MVT::v2f64, Sub, Sub);
7926  } else {
7927    SDValue S2F = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Sub);
7928    SDValue Shuffle = getTargetShuffleNode(X86ISD::PSHUFD, dl, MVT::v4i32,
7929                                           S2F, 0x4E, DAG);
7930    Result = DAG.getNode(ISD::FADD, dl, MVT::v2f64,
7931                         DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Shuffle),
7932                         Sub);
7933  }
7934
7935  return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Result,
7936                     DAG.getIntPtrConstant(0));
7937}
7938
7939// LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
7940SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
7941                                               SelectionDAG &DAG) const {
7942  DebugLoc dl = Op.getDebugLoc();
7943  // FP constant to bias correct the final result.
7944  SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
7945                                   MVT::f64);
7946
7947  // Load the 32-bit value into an XMM register.
7948  SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
7949                             Op.getOperand(0));
7950
7951  // Zero out the upper parts of the register.
7952  Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget, DAG);
7953
7954  Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
7955                     DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Load),
7956                     DAG.getIntPtrConstant(0));
7957
7958  // Or the load with the bias.
7959  SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
7960                           DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
7961                                       DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
7962                                                   MVT::v2f64, Load)),
7963                           DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
7964                                       DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
7965                                                   MVT::v2f64, Bias)));
7966  Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
7967                   DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or),
7968                   DAG.getIntPtrConstant(0));
7969
7970  // Subtract the bias.
7971  SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
7972
7973  // Handle final rounding.
7974  EVT DestVT = Op.getValueType();
7975
7976  if (DestVT.bitsLT(MVT::f64))
7977    return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
7978                       DAG.getIntPtrConstant(0));
7979  if (DestVT.bitsGT(MVT::f64))
7980    return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
7981
7982  // Handle final rounding.
7983  return Sub;
7984}
7985
7986SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
7987                                           SelectionDAG &DAG) const {
7988  SDValue N0 = Op.getOperand(0);
7989  DebugLoc dl = Op.getDebugLoc();
7990
7991  // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
7992  // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
7993  // the optimization here.
7994  if (DAG.SignBitIsZero(N0))
7995    return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
7996
7997  EVT SrcVT = N0.getValueType();
7998  EVT DstVT = Op.getValueType();
7999  if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
8000    return LowerUINT_TO_FP_i64(Op, DAG);
8001  if (SrcVT == MVT::i32 && X86ScalarSSEf64)
8002    return LowerUINT_TO_FP_i32(Op, DAG);
8003  if (Subtarget->is64Bit() && SrcVT == MVT::i64 && DstVT == MVT::f32)
8004    return SDValue();
8005
8006  // Make a 64-bit buffer, and use it to build an FILD.
8007  SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
8008  if (SrcVT == MVT::i32) {
8009    SDValue WordOff = DAG.getConstant(4, getPointerTy());
8010    SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
8011                                     getPointerTy(), StackSlot, WordOff);
8012    SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
8013                                  StackSlot, MachinePointerInfo(),
8014                                  false, false, 0);
8015    SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
8016                                  OffsetSlot, MachinePointerInfo(),
8017                                  false, false, 0);
8018    SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
8019    return Fild;
8020  }
8021
8022  assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
8023  SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
8024                               StackSlot, MachinePointerInfo(),
8025                               false, false, 0);
8026  // For i64 source, we need to add the appropriate power of 2 if the input
8027  // was negative.  This is the same as the optimization in
8028  // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
8029  // we must be careful to do the computation in x87 extended precision, not
8030  // in SSE. (The generic code can't know it's OK to do this, or how to.)
8031  int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
8032  MachineMemOperand *MMO =
8033    DAG.getMachineFunction()
8034    .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8035                          MachineMemOperand::MOLoad, 8, 8);
8036
8037  SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
8038  SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
8039  SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops, 3,
8040                                         MVT::i64, MMO);
8041
8042  APInt FF(32, 0x5F800000ULL);
8043
8044  // Check whether the sign bit is set.
8045  SDValue SignSet = DAG.getSetCC(dl, getSetCCResultType(MVT::i64),
8046                                 Op.getOperand(0), DAG.getConstant(0, MVT::i64),
8047                                 ISD::SETLT);
8048
8049  // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
8050  SDValue FudgePtr = DAG.getConstantPool(
8051                             ConstantInt::get(*DAG.getContext(), FF.zext(64)),
8052                                         getPointerTy());
8053
8054  // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
8055  SDValue Zero = DAG.getIntPtrConstant(0);
8056  SDValue Four = DAG.getIntPtrConstant(4);
8057  SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
8058                               Zero, Four);
8059  FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
8060
8061  // Load the value out, extending it from f32 to f80.
8062  // FIXME: Avoid the extend by constructing the right constant pool?
8063  SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(),
8064                                 FudgePtr, MachinePointerInfo::getConstantPool(),
8065                                 MVT::f32, false, false, 4);
8066  // Extend everything to 80 bits to force it to be done on x87.
8067  SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
8068  return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add, DAG.getIntPtrConstant(0));
8069}
8070
8071std::pair<SDValue,SDValue> X86TargetLowering::
8072FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG, bool IsSigned, bool IsReplace) const {
8073  DebugLoc DL = Op.getDebugLoc();
8074
8075  EVT DstTy = Op.getValueType();
8076
8077  if (!IsSigned && !isIntegerTypeFTOL(DstTy)) {
8078    assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
8079    DstTy = MVT::i64;
8080  }
8081
8082  assert(DstTy.getSimpleVT() <= MVT::i64 &&
8083         DstTy.getSimpleVT() >= MVT::i16 &&
8084         "Unknown FP_TO_INT to lower!");
8085
8086  // These are really Legal.
8087  if (DstTy == MVT::i32 &&
8088      isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
8089    return std::make_pair(SDValue(), SDValue());
8090  if (Subtarget->is64Bit() &&
8091      DstTy == MVT::i64 &&
8092      isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
8093    return std::make_pair(SDValue(), SDValue());
8094
8095  // We lower FP->int64 either into FISTP64 followed by a load from a temporary
8096  // stack slot, or into the FTOL runtime function.
8097  MachineFunction &MF = DAG.getMachineFunction();
8098  unsigned MemSize = DstTy.getSizeInBits()/8;
8099  int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
8100  SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8101
8102  unsigned Opc;
8103  if (!IsSigned && isIntegerTypeFTOL(DstTy))
8104    Opc = X86ISD::WIN_FTOL;
8105  else
8106    switch (DstTy.getSimpleVT().SimpleTy) {
8107    default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
8108    case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
8109    case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
8110    case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
8111    }
8112
8113  SDValue Chain = DAG.getEntryNode();
8114  SDValue Value = Op.getOperand(0);
8115  EVT TheVT = Op.getOperand(0).getValueType();
8116  // FIXME This causes a redundant load/store if the SSE-class value is already
8117  // in memory, such as if it is on the callstack.
8118  if (isScalarFPTypeInSSEReg(TheVT)) {
8119    assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
8120    Chain = DAG.getStore(Chain, DL, Value, StackSlot,
8121                         MachinePointerInfo::getFixedStack(SSFI),
8122                         false, false, 0);
8123    SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
8124    SDValue Ops[] = {
8125      Chain, StackSlot, DAG.getValueType(TheVT)
8126    };
8127
8128    MachineMemOperand *MMO =
8129      MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8130                              MachineMemOperand::MOLoad, MemSize, MemSize);
8131    Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, 3,
8132                                    DstTy, MMO);
8133    Chain = Value.getValue(1);
8134    SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
8135    StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8136  }
8137
8138  MachineMemOperand *MMO =
8139    MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8140                            MachineMemOperand::MOStore, MemSize, MemSize);
8141
8142  if (Opc != X86ISD::WIN_FTOL) {
8143    // Build the FP_TO_INT*_IN_MEM
8144    SDValue Ops[] = { Chain, Value, StackSlot };
8145    SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
8146                                           Ops, 3, DstTy, MMO);
8147    return std::make_pair(FIST, StackSlot);
8148  } else {
8149    SDValue ftol = DAG.getNode(X86ISD::WIN_FTOL, DL,
8150      DAG.getVTList(MVT::Other, MVT::Glue),
8151      Chain, Value);
8152    SDValue eax = DAG.getCopyFromReg(ftol, DL, X86::EAX,
8153      MVT::i32, ftol.getValue(1));
8154    SDValue edx = DAG.getCopyFromReg(eax.getValue(1), DL, X86::EDX,
8155      MVT::i32, eax.getValue(2));
8156    SDValue Ops[] = { eax, edx };
8157    SDValue pair = IsReplace
8158      ? DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops, 2)
8159      : DAG.getMergeValues(Ops, 2, DL);
8160    return std::make_pair(pair, SDValue());
8161  }
8162}
8163
8164SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
8165                                           SelectionDAG &DAG) const {
8166  if (Op.getValueType().isVector())
8167    return SDValue();
8168
8169  std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
8170    /*IsSigned=*/ true, /*IsReplace=*/ false);
8171  SDValue FIST = Vals.first, StackSlot = Vals.second;
8172  // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
8173  if (FIST.getNode() == 0) return Op;
8174
8175  if (StackSlot.getNode())
8176    // Load the result.
8177    return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
8178                       FIST, StackSlot, MachinePointerInfo(),
8179                       false, false, false, 0);
8180
8181  // The node is the result.
8182  return FIST;
8183}
8184
8185SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
8186                                           SelectionDAG &DAG) const {
8187  std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
8188    /*IsSigned=*/ false, /*IsReplace=*/ false);
8189  SDValue FIST = Vals.first, StackSlot = Vals.second;
8190  assert(FIST.getNode() && "Unexpected failure");
8191
8192  if (StackSlot.getNode())
8193    // Load the result.
8194    return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
8195                       FIST, StackSlot, MachinePointerInfo(),
8196                       false, false, false, 0);
8197
8198  // The node is the result.
8199  return FIST;
8200}
8201
8202SDValue X86TargetLowering::LowerFABS(SDValue Op, SelectionDAG &DAG) const {
8203  LLVMContext *Context = DAG.getContext();
8204  DebugLoc dl = Op.getDebugLoc();
8205  EVT VT = Op.getValueType();
8206  EVT EltVT = VT;
8207  unsigned NumElts = VT == MVT::f64 ? 2 : 4;
8208  if (VT.isVector()) {
8209    EltVT = VT.getVectorElementType();
8210    NumElts = VT.getVectorNumElements();
8211  }
8212  Constant *C;
8213  if (EltVT == MVT::f64)
8214    C = ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63))));
8215  else
8216    C = ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31))));
8217  C = ConstantVector::getSplat(NumElts, C);
8218  SDValue CPIdx = DAG.getConstantPool(C, getPointerTy());
8219  unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
8220  SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8221                             MachinePointerInfo::getConstantPool(),
8222                             false, false, false, Alignment);
8223  if (VT.isVector()) {
8224    MVT ANDVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
8225    return DAG.getNode(ISD::BITCAST, dl, VT,
8226                       DAG.getNode(ISD::AND, dl, ANDVT,
8227                                   DAG.getNode(ISD::BITCAST, dl, ANDVT,
8228                                               Op.getOperand(0)),
8229                                   DAG.getNode(ISD::BITCAST, dl, ANDVT, Mask)));
8230  }
8231  return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
8232}
8233
8234SDValue X86TargetLowering::LowerFNEG(SDValue Op, SelectionDAG &DAG) const {
8235  LLVMContext *Context = DAG.getContext();
8236  DebugLoc dl = Op.getDebugLoc();
8237  EVT VT = Op.getValueType();
8238  EVT EltVT = VT;
8239  unsigned NumElts = VT == MVT::f64 ? 2 : 4;
8240  if (VT.isVector()) {
8241    EltVT = VT.getVectorElementType();
8242    NumElts = VT.getVectorNumElements();
8243  }
8244  Constant *C;
8245  if (EltVT == MVT::f64)
8246    C = ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63)));
8247  else
8248    C = ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31)));
8249  C = ConstantVector::getSplat(NumElts, C);
8250  SDValue CPIdx = DAG.getConstantPool(C, getPointerTy());
8251  unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
8252  SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8253                             MachinePointerInfo::getConstantPool(),
8254                             false, false, false, Alignment);
8255  if (VT.isVector()) {
8256    MVT XORVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
8257    return DAG.getNode(ISD::BITCAST, dl, VT,
8258                       DAG.getNode(ISD::XOR, dl, XORVT,
8259                                   DAG.getNode(ISD::BITCAST, dl, XORVT,
8260                                               Op.getOperand(0)),
8261                                   DAG.getNode(ISD::BITCAST, dl, XORVT, Mask)));
8262  }
8263
8264  return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
8265}
8266
8267SDValue X86TargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
8268  LLVMContext *Context = DAG.getContext();
8269  SDValue Op0 = Op.getOperand(0);
8270  SDValue Op1 = Op.getOperand(1);
8271  DebugLoc dl = Op.getDebugLoc();
8272  EVT VT = Op.getValueType();
8273  EVT SrcVT = Op1.getValueType();
8274
8275  // If second operand is smaller, extend it first.
8276  if (SrcVT.bitsLT(VT)) {
8277    Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
8278    SrcVT = VT;
8279  }
8280  // And if it is bigger, shrink it first.
8281  if (SrcVT.bitsGT(VT)) {
8282    Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
8283    SrcVT = VT;
8284  }
8285
8286  // At this point the operands and the result should have the same
8287  // type, and that won't be f80 since that is not custom lowered.
8288
8289  // First get the sign bit of second operand.
8290  SmallVector<Constant*,4> CV;
8291  if (SrcVT == MVT::f64) {
8292    CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63))));
8293    CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
8294  } else {
8295    CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31))));
8296    CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8297    CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8298    CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8299  }
8300  Constant *C = ConstantVector::get(CV);
8301  SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8302  SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
8303                              MachinePointerInfo::getConstantPool(),
8304                              false, false, false, 16);
8305  SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
8306
8307  // Shift sign bit right or left if the two operands have different types.
8308  if (SrcVT.bitsGT(VT)) {
8309    // Op0 is MVT::f32, Op1 is MVT::f64.
8310    SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
8311    SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
8312                          DAG.getConstant(32, MVT::i32));
8313    SignBit = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, SignBit);
8314    SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
8315                          DAG.getIntPtrConstant(0));
8316  }
8317
8318  // Clear first operand sign bit.
8319  CV.clear();
8320  if (VT == MVT::f64) {
8321    CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63)))));
8322    CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
8323  } else {
8324    CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31)))));
8325    CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8326    CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8327    CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8328  }
8329  C = ConstantVector::get(CV);
8330  CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8331  SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8332                              MachinePointerInfo::getConstantPool(),
8333                              false, false, false, 16);
8334  SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
8335
8336  // Or the value with the sign bit.
8337  return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
8338}
8339
8340SDValue X86TargetLowering::LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) const {
8341  SDValue N0 = Op.getOperand(0);
8342  DebugLoc dl = Op.getDebugLoc();
8343  EVT VT = Op.getValueType();
8344
8345  // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
8346  SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
8347                                  DAG.getConstant(1, VT));
8348  return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, VT));
8349}
8350
8351/// Emit nodes that will be selected as "test Op0,Op0", or something
8352/// equivalent.
8353SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC,
8354                                    SelectionDAG &DAG) const {
8355  DebugLoc dl = Op.getDebugLoc();
8356
8357  // CF and OF aren't always set the way we want. Determine which
8358  // of these we need.
8359  bool NeedCF = false;
8360  bool NeedOF = false;
8361  switch (X86CC) {
8362  default: break;
8363  case X86::COND_A: case X86::COND_AE:
8364  case X86::COND_B: case X86::COND_BE:
8365    NeedCF = true;
8366    break;
8367  case X86::COND_G: case X86::COND_GE:
8368  case X86::COND_L: case X86::COND_LE:
8369  case X86::COND_O: case X86::COND_NO:
8370    NeedOF = true;
8371    break;
8372  }
8373
8374  // See if we can use the EFLAGS value from the operand instead of
8375  // doing a separate TEST. TEST always sets OF and CF to 0, so unless
8376  // we prove that the arithmetic won't overflow, we can't use OF or CF.
8377  if (Op.getResNo() != 0 || NeedOF || NeedCF)
8378    // Emit a CMP with 0, which is the TEST pattern.
8379    return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
8380                       DAG.getConstant(0, Op.getValueType()));
8381
8382  unsigned Opcode = 0;
8383  unsigned NumOperands = 0;
8384
8385  // Truncate operations may prevent the merge of the SETCC instruction
8386  // and the arithmetic intruction before it. Attempt to truncate the operands
8387  // of the arithmetic instruction and use a reduced bit-width instruction.
8388  bool NeedTruncation = false;
8389  SDValue ArithOp = Op;
8390  if (Op->getOpcode() == ISD::TRUNCATE && Op->hasOneUse()) {
8391    SDValue Arith = Op->getOperand(0);
8392    // Both the trunc and the arithmetic op need to have one user each.
8393    if (Arith->hasOneUse())
8394      switch (Arith.getOpcode()) {
8395        default: break;
8396        case ISD::ADD:
8397        case ISD::SUB:
8398        case ISD::AND:
8399        case ISD::OR:
8400        case ISD::XOR: {
8401          NeedTruncation = true;
8402          ArithOp = Arith;
8403        }
8404      }
8405  }
8406
8407  // NOTICE: In the code below we use ArithOp to hold the arithmetic operation
8408  // which may be the result of a CAST.  We use the variable 'Op', which is the
8409  // non-casted variable when we check for possible users.
8410  switch (ArithOp.getOpcode()) {
8411  case ISD::ADD:
8412    // Due to an isel shortcoming, be conservative if this add is likely to be
8413    // selected as part of a load-modify-store instruction. When the root node
8414    // in a match is a store, isel doesn't know how to remap non-chain non-flag
8415    // uses of other nodes in the match, such as the ADD in this case. This
8416    // leads to the ADD being left around and reselected, with the result being
8417    // two adds in the output.  Alas, even if none our users are stores, that
8418    // doesn't prove we're O.K.  Ergo, if we have any parents that aren't
8419    // CopyToReg or SETCC, eschew INC/DEC.  A better fix seems to require
8420    // climbing the DAG back to the root, and it doesn't seem to be worth the
8421    // effort.
8422    for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
8423         UE = Op.getNode()->use_end(); UI != UE; ++UI)
8424      if (UI->getOpcode() != ISD::CopyToReg &&
8425          UI->getOpcode() != ISD::SETCC &&
8426          UI->getOpcode() != ISD::STORE)
8427        goto default_case;
8428
8429    if (ConstantSDNode *C =
8430        dyn_cast<ConstantSDNode>(ArithOp.getNode()->getOperand(1))) {
8431      // An add of one will be selected as an INC.
8432      if (C->getAPIntValue() == 1) {
8433        Opcode = X86ISD::INC;
8434        NumOperands = 1;
8435        break;
8436      }
8437
8438      // An add of negative one (subtract of one) will be selected as a DEC.
8439      if (C->getAPIntValue().isAllOnesValue()) {
8440        Opcode = X86ISD::DEC;
8441        NumOperands = 1;
8442        break;
8443      }
8444    }
8445
8446    // Otherwise use a regular EFLAGS-setting add.
8447    Opcode = X86ISD::ADD;
8448    NumOperands = 2;
8449    break;
8450  case ISD::AND: {
8451    // If the primary and result isn't used, don't bother using X86ISD::AND,
8452    // because a TEST instruction will be better.
8453    bool NonFlagUse = false;
8454    for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
8455           UE = Op.getNode()->use_end(); UI != UE; ++UI) {
8456      SDNode *User = *UI;
8457      unsigned UOpNo = UI.getOperandNo();
8458      if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
8459        // Look pass truncate.
8460        UOpNo = User->use_begin().getOperandNo();
8461        User = *User->use_begin();
8462      }
8463
8464      if (User->getOpcode() != ISD::BRCOND &&
8465          User->getOpcode() != ISD::SETCC &&
8466          !(User->getOpcode() == ISD::SELECT && UOpNo == 0)) {
8467        NonFlagUse = true;
8468        break;
8469      }
8470    }
8471
8472    if (!NonFlagUse)
8473      break;
8474  }
8475    // FALL THROUGH
8476  case ISD::SUB:
8477  case ISD::OR:
8478  case ISD::XOR:
8479    // Due to the ISEL shortcoming noted above, be conservative if this op is
8480    // likely to be selected as part of a load-modify-store instruction.
8481    for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
8482           UE = Op.getNode()->use_end(); UI != UE; ++UI)
8483      if (UI->getOpcode() == ISD::STORE)
8484        goto default_case;
8485
8486    // Otherwise use a regular EFLAGS-setting instruction.
8487    switch (ArithOp.getOpcode()) {
8488    default: llvm_unreachable("unexpected operator!");
8489    case ISD::SUB: Opcode = X86ISD::SUB; break;
8490    case ISD::OR:  Opcode = X86ISD::OR;  break;
8491    case ISD::XOR: Opcode = X86ISD::XOR; break;
8492    case ISD::AND: Opcode = X86ISD::AND; break;
8493    }
8494
8495    NumOperands = 2;
8496    break;
8497  case X86ISD::ADD:
8498  case X86ISD::SUB:
8499  case X86ISD::INC:
8500  case X86ISD::DEC:
8501  case X86ISD::OR:
8502  case X86ISD::XOR:
8503  case X86ISD::AND:
8504    return SDValue(Op.getNode(), 1);
8505  default:
8506  default_case:
8507    break;
8508  }
8509
8510  // If we found that truncation is beneficial, perform the truncation and
8511  // update 'Op'.
8512  if (NeedTruncation) {
8513    EVT VT = Op.getValueType();
8514    SDValue WideVal = Op->getOperand(0);
8515    EVT WideVT = WideVal.getValueType();
8516    unsigned ConvertedOp = 0;
8517    // Use a target machine opcode to prevent further DAGCombine
8518    // optimizations that may separate the arithmetic operations
8519    // from the setcc node.
8520    switch (WideVal.getOpcode()) {
8521      default: break;
8522      case ISD::ADD: ConvertedOp = X86ISD::ADD; break;
8523      case ISD::SUB: ConvertedOp = X86ISD::SUB; break;
8524      case ISD::AND: ConvertedOp = X86ISD::AND; break;
8525      case ISD::OR:  ConvertedOp = X86ISD::OR;  break;
8526      case ISD::XOR: ConvertedOp = X86ISD::XOR; break;
8527    }
8528
8529    if (ConvertedOp) {
8530      const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8531      if (TLI.isOperationLegal(WideVal.getOpcode(), WideVT)) {
8532        SDValue V0 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(0));
8533        SDValue V1 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(1));
8534        Op = DAG.getNode(ConvertedOp, dl, VT, V0, V1);
8535      }
8536    }
8537  }
8538
8539  if (Opcode == 0)
8540    // Emit a CMP with 0, which is the TEST pattern.
8541    return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
8542                       DAG.getConstant(0, Op.getValueType()));
8543
8544  SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
8545  SmallVector<SDValue, 4> Ops;
8546  for (unsigned i = 0; i != NumOperands; ++i)
8547    Ops.push_back(Op.getOperand(i));
8548
8549  SDValue New = DAG.getNode(Opcode, dl, VTs, &Ops[0], NumOperands);
8550  DAG.ReplaceAllUsesWith(Op, New);
8551  return SDValue(New.getNode(), 1);
8552}
8553
8554/// Emit nodes that will be selected as "cmp Op0,Op1", or something
8555/// equivalent.
8556SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
8557                                   SelectionDAG &DAG) const {
8558  if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1))
8559    if (C->getAPIntValue() == 0)
8560      return EmitTest(Op0, X86CC, DAG);
8561
8562  DebugLoc dl = Op0.getDebugLoc();
8563  if ((Op0.getValueType() == MVT::i8 || Op0.getValueType() == MVT::i16 ||
8564       Op0.getValueType() == MVT::i32 || Op0.getValueType() == MVT::i64)) {
8565    // Use SUB instead of CMP to enable CSE between SUB and CMP.
8566    SDVTList VTs = DAG.getVTList(Op0.getValueType(), MVT::i32);
8567    SDValue Sub = DAG.getNode(X86ISD::SUB, dl, VTs,
8568                              Op0, Op1);
8569    return SDValue(Sub.getNode(), 1);
8570  }
8571  return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
8572}
8573
8574/// Convert a comparison if required by the subtarget.
8575SDValue X86TargetLowering::ConvertCmpIfNecessary(SDValue Cmp,
8576                                                 SelectionDAG &DAG) const {
8577  // If the subtarget does not support the FUCOMI instruction, floating-point
8578  // comparisons have to be converted.
8579  if (Subtarget->hasCMov() ||
8580      Cmp.getOpcode() != X86ISD::CMP ||
8581      !Cmp.getOperand(0).getValueType().isFloatingPoint() ||
8582      !Cmp.getOperand(1).getValueType().isFloatingPoint())
8583    return Cmp;
8584
8585  // The instruction selector will select an FUCOM instruction instead of
8586  // FUCOMI, which writes the comparison result to FPSW instead of EFLAGS. Hence
8587  // build an SDNode sequence that transfers the result from FPSW into EFLAGS:
8588  // (X86sahf (trunc (srl (X86fp_stsw (trunc (X86cmp ...)), 8))))
8589  DebugLoc dl = Cmp.getDebugLoc();
8590  SDValue TruncFPSW = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, Cmp);
8591  SDValue FNStSW = DAG.getNode(X86ISD::FNSTSW16r, dl, MVT::i16, TruncFPSW);
8592  SDValue Srl = DAG.getNode(ISD::SRL, dl, MVT::i16, FNStSW,
8593                            DAG.getConstant(8, MVT::i8));
8594  SDValue TruncSrl = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Srl);
8595  return DAG.getNode(X86ISD::SAHF, dl, MVT::i32, TruncSrl);
8596}
8597
8598/// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
8599/// if it's possible.
8600SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
8601                                     DebugLoc dl, SelectionDAG &DAG) const {
8602  SDValue Op0 = And.getOperand(0);
8603  SDValue Op1 = And.getOperand(1);
8604  if (Op0.getOpcode() == ISD::TRUNCATE)
8605    Op0 = Op0.getOperand(0);
8606  if (Op1.getOpcode() == ISD::TRUNCATE)
8607    Op1 = Op1.getOperand(0);
8608
8609  SDValue LHS, RHS;
8610  if (Op1.getOpcode() == ISD::SHL)
8611    std::swap(Op0, Op1);
8612  if (Op0.getOpcode() == ISD::SHL) {
8613    if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
8614      if (And00C->getZExtValue() == 1) {
8615        // If we looked past a truncate, check that it's only truncating away
8616        // known zeros.
8617        unsigned BitWidth = Op0.getValueSizeInBits();
8618        unsigned AndBitWidth = And.getValueSizeInBits();
8619        if (BitWidth > AndBitWidth) {
8620          APInt Zeros, Ones;
8621          DAG.ComputeMaskedBits(Op0, Zeros, Ones);
8622          if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
8623            return SDValue();
8624        }
8625        LHS = Op1;
8626        RHS = Op0.getOperand(1);
8627      }
8628  } else if (Op1.getOpcode() == ISD::Constant) {
8629    ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
8630    uint64_t AndRHSVal = AndRHS->getZExtValue();
8631    SDValue AndLHS = Op0;
8632
8633    if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) {
8634      LHS = AndLHS.getOperand(0);
8635      RHS = AndLHS.getOperand(1);
8636    }
8637
8638    // Use BT if the immediate can't be encoded in a TEST instruction.
8639    if (!isUInt<32>(AndRHSVal) && isPowerOf2_64(AndRHSVal)) {
8640      LHS = AndLHS;
8641      RHS = DAG.getConstant(Log2_64_Ceil(AndRHSVal), LHS.getValueType());
8642    }
8643  }
8644
8645  if (LHS.getNode()) {
8646    // If LHS is i8, promote it to i32 with any_extend.  There is no i8 BT
8647    // instruction.  Since the shift amount is in-range-or-undefined, we know
8648    // that doing a bittest on the i32 value is ok.  We extend to i32 because
8649    // the encoding for the i16 version is larger than the i32 version.
8650    // Also promote i16 to i32 for performance / code size reason.
8651    if (LHS.getValueType() == MVT::i8 ||
8652        LHS.getValueType() == MVT::i16)
8653      LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
8654
8655    // If the operand types disagree, extend the shift amount to match.  Since
8656    // BT ignores high bits (like shifts) we can use anyextend.
8657    if (LHS.getValueType() != RHS.getValueType())
8658      RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
8659
8660    SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
8661    unsigned Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
8662    return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
8663                       DAG.getConstant(Cond, MVT::i8), BT);
8664  }
8665
8666  return SDValue();
8667}
8668
8669SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
8670
8671  if (Op.getValueType().isVector()) return LowerVSETCC(Op, DAG);
8672
8673  assert(Op.getValueType() == MVT::i8 && "SetCC type must be 8-bit integer");
8674  SDValue Op0 = Op.getOperand(0);
8675  SDValue Op1 = Op.getOperand(1);
8676  DebugLoc dl = Op.getDebugLoc();
8677  ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
8678
8679  // Optimize to BT if possible.
8680  // Lower (X & (1 << N)) == 0 to BT(X, N).
8681  // Lower ((X >>u N) & 1) != 0 to BT(X, N).
8682  // Lower ((X >>s N) & 1) != 0 to BT(X, N).
8683  if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
8684      Op1.getOpcode() == ISD::Constant &&
8685      cast<ConstantSDNode>(Op1)->isNullValue() &&
8686      (CC == ISD::SETEQ || CC == ISD::SETNE)) {
8687    SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
8688    if (NewSetCC.getNode())
8689      return NewSetCC;
8690  }
8691
8692  // Look for X == 0, X == 1, X != 0, or X != 1.  We can simplify some forms of
8693  // these.
8694  if (Op1.getOpcode() == ISD::Constant &&
8695      (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
8696       cast<ConstantSDNode>(Op1)->isNullValue()) &&
8697      (CC == ISD::SETEQ || CC == ISD::SETNE)) {
8698
8699    // If the input is a setcc, then reuse the input setcc or use a new one with
8700    // the inverted condition.
8701    if (Op0.getOpcode() == X86ISD::SETCC) {
8702      X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
8703      bool Invert = (CC == ISD::SETNE) ^
8704        cast<ConstantSDNode>(Op1)->isNullValue();
8705      if (!Invert) return Op0;
8706
8707      CCode = X86::GetOppositeBranchCondition(CCode);
8708      return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
8709                         DAG.getConstant(CCode, MVT::i8), Op0.getOperand(1));
8710    }
8711  }
8712
8713  bool isFP = Op1.getValueType().isFloatingPoint();
8714  unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
8715  if (X86CC == X86::COND_INVALID)
8716    return SDValue();
8717
8718  SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, DAG);
8719  EFLAGS = ConvertCmpIfNecessary(EFLAGS, DAG);
8720  return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
8721                     DAG.getConstant(X86CC, MVT::i8), EFLAGS);
8722}
8723
8724// Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
8725// ones, and then concatenate the result back.
8726static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
8727  EVT VT = Op.getValueType();
8728
8729  assert(VT.is256BitVector() && Op.getOpcode() == ISD::SETCC &&
8730         "Unsupported value type for operation");
8731
8732  unsigned NumElems = VT.getVectorNumElements();
8733  DebugLoc dl = Op.getDebugLoc();
8734  SDValue CC = Op.getOperand(2);
8735
8736  // Extract the LHS vectors
8737  SDValue LHS = Op.getOperand(0);
8738  SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
8739  SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
8740
8741  // Extract the RHS vectors
8742  SDValue RHS = Op.getOperand(1);
8743  SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
8744  SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
8745
8746  // Issue the operation on the smaller types and concatenate the result back
8747  MVT EltVT = VT.getVectorElementType().getSimpleVT();
8748  EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
8749  return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
8750                     DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
8751                     DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
8752}
8753
8754
8755SDValue X86TargetLowering::LowerVSETCC(SDValue Op, SelectionDAG &DAG) const {
8756  SDValue Cond;
8757  SDValue Op0 = Op.getOperand(0);
8758  SDValue Op1 = Op.getOperand(1);
8759  SDValue CC = Op.getOperand(2);
8760  EVT VT = Op.getValueType();
8761  ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
8762  bool isFP = Op.getOperand(1).getValueType().isFloatingPoint();
8763  DebugLoc dl = Op.getDebugLoc();
8764
8765  if (isFP) {
8766#ifndef NDEBUG
8767    EVT EltVT = Op0.getValueType().getVectorElementType();
8768    assert(EltVT == MVT::f32 || EltVT == MVT::f64);
8769#endif
8770
8771    unsigned SSECC;
8772    bool Swap = false;
8773
8774    // SSE Condition code mapping:
8775    //  0 - EQ
8776    //  1 - LT
8777    //  2 - LE
8778    //  3 - UNORD
8779    //  4 - NEQ
8780    //  5 - NLT
8781    //  6 - NLE
8782    //  7 - ORD
8783    switch (SetCCOpcode) {
8784    default: llvm_unreachable("Unexpected SETCC condition");
8785    case ISD::SETOEQ:
8786    case ISD::SETEQ:  SSECC = 0; break;
8787    case ISD::SETOGT:
8788    case ISD::SETGT: Swap = true; // Fallthrough
8789    case ISD::SETLT:
8790    case ISD::SETOLT: SSECC = 1; break;
8791    case ISD::SETOGE:
8792    case ISD::SETGE: Swap = true; // Fallthrough
8793    case ISD::SETLE:
8794    case ISD::SETOLE: SSECC = 2; break;
8795    case ISD::SETUO:  SSECC = 3; break;
8796    case ISD::SETUNE:
8797    case ISD::SETNE:  SSECC = 4; break;
8798    case ISD::SETULE: Swap = true; // Fallthrough
8799    case ISD::SETUGE: SSECC = 5; break;
8800    case ISD::SETULT: Swap = true; // Fallthrough
8801    case ISD::SETUGT: SSECC = 6; break;
8802    case ISD::SETO:   SSECC = 7; break;
8803    case ISD::SETUEQ:
8804    case ISD::SETONE: SSECC = 8; break;
8805    }
8806    if (Swap)
8807      std::swap(Op0, Op1);
8808
8809    // In the two special cases we can't handle, emit two comparisons.
8810    if (SSECC == 8) {
8811      unsigned CC0, CC1;
8812      unsigned CombineOpc;
8813      if (SetCCOpcode == ISD::SETUEQ) {
8814        CC0 = 3; CC1 = 0; CombineOpc = ISD::OR;
8815      } else {
8816        assert(SetCCOpcode == ISD::SETONE);
8817        CC0 = 7; CC1 = 4; CombineOpc = ISD::AND;
8818      }
8819
8820      SDValue Cmp0 = DAG.getNode(X86ISD::CMPP, dl, VT, Op0, Op1,
8821                                 DAG.getConstant(CC0, MVT::i8));
8822      SDValue Cmp1 = DAG.getNode(X86ISD::CMPP, dl, VT, Op0, Op1,
8823                                 DAG.getConstant(CC1, MVT::i8));
8824      return DAG.getNode(CombineOpc, dl, VT, Cmp0, Cmp1);
8825    }
8826    // Handle all other FP comparisons here.
8827    return DAG.getNode(X86ISD::CMPP, dl, VT, Op0, Op1,
8828                       DAG.getConstant(SSECC, MVT::i8));
8829  }
8830
8831  // Break 256-bit integer vector compare into smaller ones.
8832  if (VT.is256BitVector() && !Subtarget->hasAVX2())
8833    return Lower256IntVSETCC(Op, DAG);
8834
8835  // We are handling one of the integer comparisons here.  Since SSE only has
8836  // GT and EQ comparisons for integer, swapping operands and multiple
8837  // operations may be required for some comparisons.
8838  unsigned Opc;
8839  bool Swap = false, Invert = false, FlipSigns = false;
8840
8841  switch (SetCCOpcode) {
8842  default: llvm_unreachable("Unexpected SETCC condition");
8843  case ISD::SETNE:  Invert = true;
8844  case ISD::SETEQ:  Opc = X86ISD::PCMPEQ; break;
8845  case ISD::SETLT:  Swap = true;
8846  case ISD::SETGT:  Opc = X86ISD::PCMPGT; break;
8847  case ISD::SETGE:  Swap = true;
8848  case ISD::SETLE:  Opc = X86ISD::PCMPGT; Invert = true; break;
8849  case ISD::SETULT: Swap = true;
8850  case ISD::SETUGT: Opc = X86ISD::PCMPGT; FlipSigns = true; break;
8851  case ISD::SETUGE: Swap = true;
8852  case ISD::SETULE: Opc = X86ISD::PCMPGT; FlipSigns = true; Invert = true; break;
8853  }
8854  if (Swap)
8855    std::swap(Op0, Op1);
8856
8857  // Check that the operation in question is available (most are plain SSE2,
8858  // but PCMPGTQ and PCMPEQQ have different requirements).
8859  if (VT == MVT::v2i64) {
8860    if (Opc == X86ISD::PCMPGT && !Subtarget->hasSSE42())
8861      return SDValue();
8862    if (Opc == X86ISD::PCMPEQ && !Subtarget->hasSSE41())
8863      return SDValue();
8864  }
8865
8866  // Since SSE has no unsigned integer comparisons, we need to flip  the sign
8867  // bits of the inputs before performing those operations.
8868  if (FlipSigns) {
8869    EVT EltVT = VT.getVectorElementType();
8870    SDValue SignBit = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()),
8871                                      EltVT);
8872    std::vector<SDValue> SignBits(VT.getVectorNumElements(), SignBit);
8873    SDValue SignVec = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &SignBits[0],
8874                                    SignBits.size());
8875    Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SignVec);
8876    Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SignVec);
8877  }
8878
8879  SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
8880
8881  // If the logical-not of the result is required, perform that now.
8882  if (Invert)
8883    Result = DAG.getNOT(dl, Result, VT);
8884
8885  return Result;
8886}
8887
8888// isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
8889static bool isX86LogicalCmp(SDValue Op) {
8890  unsigned Opc = Op.getNode()->getOpcode();
8891  if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI ||
8892      Opc == X86ISD::SAHF)
8893    return true;
8894  if (Op.getResNo() == 1 &&
8895      (Opc == X86ISD::ADD ||
8896       Opc == X86ISD::SUB ||
8897       Opc == X86ISD::ADC ||
8898       Opc == X86ISD::SBB ||
8899       Opc == X86ISD::SMUL ||
8900       Opc == X86ISD::UMUL ||
8901       Opc == X86ISD::INC ||
8902       Opc == X86ISD::DEC ||
8903       Opc == X86ISD::OR ||
8904       Opc == X86ISD::XOR ||
8905       Opc == X86ISD::AND))
8906    return true;
8907
8908  if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
8909    return true;
8910
8911  return false;
8912}
8913
8914static bool isZero(SDValue V) {
8915  ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
8916  return C && C->isNullValue();
8917}
8918
8919static bool isAllOnes(SDValue V) {
8920  ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
8921  return C && C->isAllOnesValue();
8922}
8923
8924static bool isTruncWithZeroHighBitsInput(SDValue V, SelectionDAG &DAG) {
8925  if (V.getOpcode() != ISD::TRUNCATE)
8926    return false;
8927
8928  SDValue VOp0 = V.getOperand(0);
8929  unsigned InBits = VOp0.getValueSizeInBits();
8930  unsigned Bits = V.getValueSizeInBits();
8931  return DAG.MaskedValueIsZero(VOp0, APInt::getHighBitsSet(InBits,InBits-Bits));
8932}
8933
8934SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
8935  bool addTest = true;
8936  SDValue Cond  = Op.getOperand(0);
8937  SDValue Op1 = Op.getOperand(1);
8938  SDValue Op2 = Op.getOperand(2);
8939  DebugLoc DL = Op.getDebugLoc();
8940  SDValue CC;
8941
8942  if (Cond.getOpcode() == ISD::SETCC) {
8943    SDValue NewCond = LowerSETCC(Cond, DAG);
8944    if (NewCond.getNode())
8945      Cond = NewCond;
8946  }
8947
8948  // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
8949  // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
8950  // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
8951  // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
8952  if (Cond.getOpcode() == X86ISD::SETCC &&
8953      Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
8954      isZero(Cond.getOperand(1).getOperand(1))) {
8955    SDValue Cmp = Cond.getOperand(1);
8956
8957    unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
8958
8959    if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
8960        (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
8961      SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
8962
8963      SDValue CmpOp0 = Cmp.getOperand(0);
8964      // Apply further optimizations for special cases
8965      // (select (x != 0), -1, 0) -> neg & sbb
8966      // (select (x == 0), 0, -1) -> neg & sbb
8967      if (ConstantSDNode *YC = dyn_cast<ConstantSDNode>(Y))
8968        if (YC->isNullValue() &&
8969            (isAllOnes(Op1) == (CondCode == X86::COND_NE))) {
8970          SDVTList VTs = DAG.getVTList(CmpOp0.getValueType(), MVT::i32);
8971          SDValue Neg = DAG.getNode(X86ISD::SUB, DL, VTs,
8972                                    DAG.getConstant(0, CmpOp0.getValueType()),
8973                                    CmpOp0);
8974          SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
8975                                    DAG.getConstant(X86::COND_B, MVT::i8),
8976                                    SDValue(Neg.getNode(), 1));
8977          return Res;
8978        }
8979
8980      Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
8981                        CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
8982      Cmp = ConvertCmpIfNecessary(Cmp, DAG);
8983
8984      SDValue Res =   // Res = 0 or -1.
8985        DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
8986                    DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
8987
8988      if (isAllOnes(Op1) != (CondCode == X86::COND_E))
8989        Res = DAG.getNOT(DL, Res, Res.getValueType());
8990
8991      ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
8992      if (N2C == 0 || !N2C->isNullValue())
8993        Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
8994      return Res;
8995    }
8996  }
8997
8998  // Look past (and (setcc_carry (cmp ...)), 1).
8999  if (Cond.getOpcode() == ISD::AND &&
9000      Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
9001    ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
9002    if (C && C->getAPIntValue() == 1)
9003      Cond = Cond.getOperand(0);
9004  }
9005
9006  // If condition flag is set by a X86ISD::CMP, then use it as the condition
9007  // setting operand in place of the X86ISD::SETCC.
9008  unsigned CondOpcode = Cond.getOpcode();
9009  if (CondOpcode == X86ISD::SETCC ||
9010      CondOpcode == X86ISD::SETCC_CARRY) {
9011    CC = Cond.getOperand(0);
9012
9013    SDValue Cmp = Cond.getOperand(1);
9014    unsigned Opc = Cmp.getOpcode();
9015    EVT VT = Op.getValueType();
9016
9017    bool IllegalFPCMov = false;
9018    if (VT.isFloatingPoint() && !VT.isVector() &&
9019        !isScalarFPTypeInSSEReg(VT))  // FPStack?
9020      IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
9021
9022    if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
9023        Opc == X86ISD::BT) { // FIXME
9024      Cond = Cmp;
9025      addTest = false;
9026    }
9027  } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
9028             CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
9029             ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
9030              Cond.getOperand(0).getValueType() != MVT::i8)) {
9031    SDValue LHS = Cond.getOperand(0);
9032    SDValue RHS = Cond.getOperand(1);
9033    unsigned X86Opcode;
9034    unsigned X86Cond;
9035    SDVTList VTs;
9036    switch (CondOpcode) {
9037    case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
9038    case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
9039    case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
9040    case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
9041    case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
9042    case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
9043    default: llvm_unreachable("unexpected overflowing operator");
9044    }
9045    if (CondOpcode == ISD::UMULO)
9046      VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
9047                          MVT::i32);
9048    else
9049      VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
9050
9051    SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS);
9052
9053    if (CondOpcode == ISD::UMULO)
9054      Cond = X86Op.getValue(2);
9055    else
9056      Cond = X86Op.getValue(1);
9057
9058    CC = DAG.getConstant(X86Cond, MVT::i8);
9059    addTest = false;
9060  }
9061
9062  if (addTest) {
9063    // Look pass the truncate if the high bits are known zero.
9064    if (isTruncWithZeroHighBitsInput(Cond, DAG))
9065        Cond = Cond.getOperand(0);
9066
9067    // We know the result of AND is compared against zero. Try to match
9068    // it to BT.
9069    if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
9070      SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
9071      if (NewSetCC.getNode()) {
9072        CC = NewSetCC.getOperand(0);
9073        Cond = NewSetCC.getOperand(1);
9074        addTest = false;
9075      }
9076    }
9077  }
9078
9079  if (addTest) {
9080    CC = DAG.getConstant(X86::COND_NE, MVT::i8);
9081    Cond = EmitTest(Cond, X86::COND_NE, DAG);
9082  }
9083
9084  // a <  b ? -1 :  0 -> RES = ~setcc_carry
9085  // a <  b ?  0 : -1 -> RES = setcc_carry
9086  // a >= b ? -1 :  0 -> RES = setcc_carry
9087  // a >= b ?  0 : -1 -> RES = ~setcc_carry
9088  if (Cond.getOpcode() == X86ISD::SUB) {
9089    Cond = ConvertCmpIfNecessary(Cond, DAG);
9090    unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
9091
9092    if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
9093        (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
9094      SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
9095                                DAG.getConstant(X86::COND_B, MVT::i8), Cond);
9096      if (isAllOnes(Op1) != (CondCode == X86::COND_B))
9097        return DAG.getNOT(DL, Res, Res.getValueType());
9098      return Res;
9099    }
9100  }
9101
9102  // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
9103  // condition is true.
9104  SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
9105  SDValue Ops[] = { Op2, Op1, CC, Cond };
9106  return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops, array_lengthof(Ops));
9107}
9108
9109// isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
9110// ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
9111// from the AND / OR.
9112static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
9113  Opc = Op.getOpcode();
9114  if (Opc != ISD::OR && Opc != ISD::AND)
9115    return false;
9116  return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
9117          Op.getOperand(0).hasOneUse() &&
9118          Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
9119          Op.getOperand(1).hasOneUse());
9120}
9121
9122// isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
9123// 1 and that the SETCC node has a single use.
9124static bool isXor1OfSetCC(SDValue Op) {
9125  if (Op.getOpcode() != ISD::XOR)
9126    return false;
9127  ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
9128  if (N1C && N1C->getAPIntValue() == 1) {
9129    return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
9130      Op.getOperand(0).hasOneUse();
9131  }
9132  return false;
9133}
9134
9135SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
9136  bool addTest = true;
9137  SDValue Chain = Op.getOperand(0);
9138  SDValue Cond  = Op.getOperand(1);
9139  SDValue Dest  = Op.getOperand(2);
9140  DebugLoc dl = Op.getDebugLoc();
9141  SDValue CC;
9142  bool Inverted = false;
9143
9144  if (Cond.getOpcode() == ISD::SETCC) {
9145    // Check for setcc([su]{add,sub,mul}o == 0).
9146    if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
9147        isa<ConstantSDNode>(Cond.getOperand(1)) &&
9148        cast<ConstantSDNode>(Cond.getOperand(1))->isNullValue() &&
9149        Cond.getOperand(0).getResNo() == 1 &&
9150        (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
9151         Cond.getOperand(0).getOpcode() == ISD::UADDO ||
9152         Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
9153         Cond.getOperand(0).getOpcode() == ISD::USUBO ||
9154         Cond.getOperand(0).getOpcode() == ISD::SMULO ||
9155         Cond.getOperand(0).getOpcode() == ISD::UMULO)) {
9156      Inverted = true;
9157      Cond = Cond.getOperand(0);
9158    } else {
9159      SDValue NewCond = LowerSETCC(Cond, DAG);
9160      if (NewCond.getNode())
9161        Cond = NewCond;
9162    }
9163  }
9164#if 0
9165  // FIXME: LowerXALUO doesn't handle these!!
9166  else if (Cond.getOpcode() == X86ISD::ADD  ||
9167           Cond.getOpcode() == X86ISD::SUB  ||
9168           Cond.getOpcode() == X86ISD::SMUL ||
9169           Cond.getOpcode() == X86ISD::UMUL)
9170    Cond = LowerXALUO(Cond, DAG);
9171#endif
9172
9173  // Look pass (and (setcc_carry (cmp ...)), 1).
9174  if (Cond.getOpcode() == ISD::AND &&
9175      Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
9176    ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
9177    if (C && C->getAPIntValue() == 1)
9178      Cond = Cond.getOperand(0);
9179  }
9180
9181  // If condition flag is set by a X86ISD::CMP, then use it as the condition
9182  // setting operand in place of the X86ISD::SETCC.
9183  unsigned CondOpcode = Cond.getOpcode();
9184  if (CondOpcode == X86ISD::SETCC ||
9185      CondOpcode == X86ISD::SETCC_CARRY) {
9186    CC = Cond.getOperand(0);
9187
9188    SDValue Cmp = Cond.getOperand(1);
9189    unsigned Opc = Cmp.getOpcode();
9190    // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
9191    if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
9192      Cond = Cmp;
9193      addTest = false;
9194    } else {
9195      switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
9196      default: break;
9197      case X86::COND_O:
9198      case X86::COND_B:
9199        // These can only come from an arithmetic instruction with overflow,
9200        // e.g. SADDO, UADDO.
9201        Cond = Cond.getNode()->getOperand(1);
9202        addTest = false;
9203        break;
9204      }
9205    }
9206  }
9207  CondOpcode = Cond.getOpcode();
9208  if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
9209      CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
9210      ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
9211       Cond.getOperand(0).getValueType() != MVT::i8)) {
9212    SDValue LHS = Cond.getOperand(0);
9213    SDValue RHS = Cond.getOperand(1);
9214    unsigned X86Opcode;
9215    unsigned X86Cond;
9216    SDVTList VTs;
9217    switch (CondOpcode) {
9218    case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
9219    case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
9220    case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
9221    case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
9222    case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
9223    case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
9224    default: llvm_unreachable("unexpected overflowing operator");
9225    }
9226    if (Inverted)
9227      X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond);
9228    if (CondOpcode == ISD::UMULO)
9229      VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
9230                          MVT::i32);
9231    else
9232      VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
9233
9234    SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS);
9235
9236    if (CondOpcode == ISD::UMULO)
9237      Cond = X86Op.getValue(2);
9238    else
9239      Cond = X86Op.getValue(1);
9240
9241    CC = DAG.getConstant(X86Cond, MVT::i8);
9242    addTest = false;
9243  } else {
9244    unsigned CondOpc;
9245    if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
9246      SDValue Cmp = Cond.getOperand(0).getOperand(1);
9247      if (CondOpc == ISD::OR) {
9248        // Also, recognize the pattern generated by an FCMP_UNE. We can emit
9249        // two branches instead of an explicit OR instruction with a
9250        // separate test.
9251        if (Cmp == Cond.getOperand(1).getOperand(1) &&
9252            isX86LogicalCmp(Cmp)) {
9253          CC = Cond.getOperand(0).getOperand(0);
9254          Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9255                              Chain, Dest, CC, Cmp);
9256          CC = Cond.getOperand(1).getOperand(0);
9257          Cond = Cmp;
9258          addTest = false;
9259        }
9260      } else { // ISD::AND
9261        // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
9262        // two branches instead of an explicit AND instruction with a
9263        // separate test. However, we only do this if this block doesn't
9264        // have a fall-through edge, because this requires an explicit
9265        // jmp when the condition is false.
9266        if (Cmp == Cond.getOperand(1).getOperand(1) &&
9267            isX86LogicalCmp(Cmp) &&
9268            Op.getNode()->hasOneUse()) {
9269          X86::CondCode CCode =
9270            (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
9271          CCode = X86::GetOppositeBranchCondition(CCode);
9272          CC = DAG.getConstant(CCode, MVT::i8);
9273          SDNode *User = *Op.getNode()->use_begin();
9274          // Look for an unconditional branch following this conditional branch.
9275          // We need this because we need to reverse the successors in order
9276          // to implement FCMP_OEQ.
9277          if (User->getOpcode() == ISD::BR) {
9278            SDValue FalseBB = User->getOperand(1);
9279            SDNode *NewBR =
9280              DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
9281            assert(NewBR == User);
9282            (void)NewBR;
9283            Dest = FalseBB;
9284
9285            Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9286                                Chain, Dest, CC, Cmp);
9287            X86::CondCode CCode =
9288              (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
9289            CCode = X86::GetOppositeBranchCondition(CCode);
9290            CC = DAG.getConstant(CCode, MVT::i8);
9291            Cond = Cmp;
9292            addTest = false;
9293          }
9294        }
9295      }
9296    } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
9297      // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
9298      // It should be transformed during dag combiner except when the condition
9299      // is set by a arithmetics with overflow node.
9300      X86::CondCode CCode =
9301        (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
9302      CCode = X86::GetOppositeBranchCondition(CCode);
9303      CC = DAG.getConstant(CCode, MVT::i8);
9304      Cond = Cond.getOperand(0).getOperand(1);
9305      addTest = false;
9306    } else if (Cond.getOpcode() == ISD::SETCC &&
9307               cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) {
9308      // For FCMP_OEQ, we can emit
9309      // two branches instead of an explicit AND instruction with a
9310      // separate test. However, we only do this if this block doesn't
9311      // have a fall-through edge, because this requires an explicit
9312      // jmp when the condition is false.
9313      if (Op.getNode()->hasOneUse()) {
9314        SDNode *User = *Op.getNode()->use_begin();
9315        // Look for an unconditional branch following this conditional branch.
9316        // We need this because we need to reverse the successors in order
9317        // to implement FCMP_OEQ.
9318        if (User->getOpcode() == ISD::BR) {
9319          SDValue FalseBB = User->getOperand(1);
9320          SDNode *NewBR =
9321            DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
9322          assert(NewBR == User);
9323          (void)NewBR;
9324          Dest = FalseBB;
9325
9326          SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
9327                                    Cond.getOperand(0), Cond.getOperand(1));
9328          Cmp = ConvertCmpIfNecessary(Cmp, DAG);
9329          CC = DAG.getConstant(X86::COND_NE, MVT::i8);
9330          Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9331                              Chain, Dest, CC, Cmp);
9332          CC = DAG.getConstant(X86::COND_P, MVT::i8);
9333          Cond = Cmp;
9334          addTest = false;
9335        }
9336      }
9337    } else if (Cond.getOpcode() == ISD::SETCC &&
9338               cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) {
9339      // For FCMP_UNE, we can emit
9340      // two branches instead of an explicit AND instruction with a
9341      // separate test. However, we only do this if this block doesn't
9342      // have a fall-through edge, because this requires an explicit
9343      // jmp when the condition is false.
9344      if (Op.getNode()->hasOneUse()) {
9345        SDNode *User = *Op.getNode()->use_begin();
9346        // Look for an unconditional branch following this conditional branch.
9347        // We need this because we need to reverse the successors in order
9348        // to implement FCMP_UNE.
9349        if (User->getOpcode() == ISD::BR) {
9350          SDValue FalseBB = User->getOperand(1);
9351          SDNode *NewBR =
9352            DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
9353          assert(NewBR == User);
9354          (void)NewBR;
9355
9356          SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
9357                                    Cond.getOperand(0), Cond.getOperand(1));
9358          Cmp = ConvertCmpIfNecessary(Cmp, DAG);
9359          CC = DAG.getConstant(X86::COND_NE, MVT::i8);
9360          Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9361                              Chain, Dest, CC, Cmp);
9362          CC = DAG.getConstant(X86::COND_NP, MVT::i8);
9363          Cond = Cmp;
9364          addTest = false;
9365          Dest = FalseBB;
9366        }
9367      }
9368    }
9369  }
9370
9371  if (addTest) {
9372    // Look pass the truncate if the high bits are known zero.
9373    if (isTruncWithZeroHighBitsInput(Cond, DAG))
9374        Cond = Cond.getOperand(0);
9375
9376    // We know the result of AND is compared against zero. Try to match
9377    // it to BT.
9378    if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
9379      SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
9380      if (NewSetCC.getNode()) {
9381        CC = NewSetCC.getOperand(0);
9382        Cond = NewSetCC.getOperand(1);
9383        addTest = false;
9384      }
9385    }
9386  }
9387
9388  if (addTest) {
9389    CC = DAG.getConstant(X86::COND_NE, MVT::i8);
9390    Cond = EmitTest(Cond, X86::COND_NE, DAG);
9391  }
9392  Cond = ConvertCmpIfNecessary(Cond, DAG);
9393  return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9394                     Chain, Dest, CC, Cond);
9395}
9396
9397
9398// Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
9399// Calls to _alloca is needed to probe the stack when allocating more than 4k
9400// bytes in one go. Touching the stack at 4K increments is necessary to ensure
9401// that the guard pages used by the OS virtual memory manager are allocated in
9402// correct sequence.
9403SDValue
9404X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
9405                                           SelectionDAG &DAG) const {
9406  assert((Subtarget->isTargetCygMing() || Subtarget->isTargetWindows() ||
9407          getTargetMachine().Options.EnableSegmentedStacks) &&
9408         "This should be used only on Windows targets or when segmented stacks "
9409         "are being used");
9410  assert(!Subtarget->isTargetEnvMacho() && "Not implemented");
9411  DebugLoc dl = Op.getDebugLoc();
9412
9413  // Get the inputs.
9414  SDValue Chain = Op.getOperand(0);
9415  SDValue Size  = Op.getOperand(1);
9416  // FIXME: Ensure alignment here
9417
9418  bool Is64Bit = Subtarget->is64Bit();
9419  EVT SPTy = Is64Bit ? MVT::i64 : MVT::i32;
9420
9421  if (getTargetMachine().Options.EnableSegmentedStacks) {
9422    MachineFunction &MF = DAG.getMachineFunction();
9423    MachineRegisterInfo &MRI = MF.getRegInfo();
9424
9425    if (Is64Bit) {
9426      // The 64 bit implementation of segmented stacks needs to clobber both r10
9427      // r11. This makes it impossible to use it along with nested parameters.
9428      const Function *F = MF.getFunction();
9429
9430      for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
9431           I != E; ++I)
9432        if (I->hasNestAttr())
9433          report_fatal_error("Cannot use segmented stacks with functions that "
9434                             "have nested arguments.");
9435    }
9436
9437    const TargetRegisterClass *AddrRegClass =
9438      getRegClassFor(Subtarget->is64Bit() ? MVT::i64:MVT::i32);
9439    unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
9440    Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
9441    SDValue Value = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
9442                                DAG.getRegister(Vreg, SPTy));
9443    SDValue Ops1[2] = { Value, Chain };
9444    return DAG.getMergeValues(Ops1, 2, dl);
9445  } else {
9446    SDValue Flag;
9447    unsigned Reg = (Subtarget->is64Bit() ? X86::RAX : X86::EAX);
9448
9449    Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
9450    Flag = Chain.getValue(1);
9451    SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
9452
9453    Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
9454    Flag = Chain.getValue(1);
9455
9456    Chain = DAG.getCopyFromReg(Chain, dl, X86StackPtr, SPTy).getValue(1);
9457
9458    SDValue Ops1[2] = { Chain.getValue(0), Chain };
9459    return DAG.getMergeValues(Ops1, 2, dl);
9460  }
9461}
9462
9463SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
9464  MachineFunction &MF = DAG.getMachineFunction();
9465  X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
9466
9467  const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
9468  DebugLoc DL = Op.getDebugLoc();
9469
9470  if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
9471    // vastart just stores the address of the VarArgsFrameIndex slot into the
9472    // memory location argument.
9473    SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
9474                                   getPointerTy());
9475    return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
9476                        MachinePointerInfo(SV), false, false, 0);
9477  }
9478
9479  // __va_list_tag:
9480  //   gp_offset         (0 - 6 * 8)
9481  //   fp_offset         (48 - 48 + 8 * 16)
9482  //   overflow_arg_area (point to parameters coming in memory).
9483  //   reg_save_area
9484  SmallVector<SDValue, 8> MemOps;
9485  SDValue FIN = Op.getOperand(1);
9486  // Store gp_offset
9487  SDValue Store = DAG.getStore(Op.getOperand(0), DL,
9488                               DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
9489                                               MVT::i32),
9490                               FIN, MachinePointerInfo(SV), false, false, 0);
9491  MemOps.push_back(Store);
9492
9493  // Store fp_offset
9494  FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
9495                    FIN, DAG.getIntPtrConstant(4));
9496  Store = DAG.getStore(Op.getOperand(0), DL,
9497                       DAG.getConstant(FuncInfo->getVarArgsFPOffset(),
9498                                       MVT::i32),
9499                       FIN, MachinePointerInfo(SV, 4), false, false, 0);
9500  MemOps.push_back(Store);
9501
9502  // Store ptr to overflow_arg_area
9503  FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
9504                    FIN, DAG.getIntPtrConstant(4));
9505  SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
9506                                    getPointerTy());
9507  Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
9508                       MachinePointerInfo(SV, 8),
9509                       false, false, 0);
9510  MemOps.push_back(Store);
9511
9512  // Store ptr to reg_save_area.
9513  FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
9514                    FIN, DAG.getIntPtrConstant(8));
9515  SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
9516                                    getPointerTy());
9517  Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
9518                       MachinePointerInfo(SV, 16), false, false, 0);
9519  MemOps.push_back(Store);
9520  return DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
9521                     &MemOps[0], MemOps.size());
9522}
9523
9524SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
9525  assert(Subtarget->is64Bit() &&
9526         "LowerVAARG only handles 64-bit va_arg!");
9527  assert((Subtarget->isTargetLinux() ||
9528          Subtarget->isTargetDarwin()) &&
9529          "Unhandled target in LowerVAARG");
9530  assert(Op.getNode()->getNumOperands() == 4);
9531  SDValue Chain = Op.getOperand(0);
9532  SDValue SrcPtr = Op.getOperand(1);
9533  const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
9534  unsigned Align = Op.getConstantOperandVal(3);
9535  DebugLoc dl = Op.getDebugLoc();
9536
9537  EVT ArgVT = Op.getNode()->getValueType(0);
9538  Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
9539  uint32_t ArgSize = getTargetData()->getTypeAllocSize(ArgTy);
9540  uint8_t ArgMode;
9541
9542  // Decide which area this value should be read from.
9543  // TODO: Implement the AMD64 ABI in its entirety. This simple
9544  // selection mechanism works only for the basic types.
9545  if (ArgVT == MVT::f80) {
9546    llvm_unreachable("va_arg for f80 not yet implemented");
9547  } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
9548    ArgMode = 2;  // Argument passed in XMM register. Use fp_offset.
9549  } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
9550    ArgMode = 1;  // Argument passed in GPR64 register(s). Use gp_offset.
9551  } else {
9552    llvm_unreachable("Unhandled argument type in LowerVAARG");
9553  }
9554
9555  if (ArgMode == 2) {
9556    // Sanity Check: Make sure using fp_offset makes sense.
9557    assert(!getTargetMachine().Options.UseSoftFloat &&
9558           !(DAG.getMachineFunction()
9559                .getFunction()->hasFnAttr(Attribute::NoImplicitFloat)) &&
9560           Subtarget->hasSSE1());
9561  }
9562
9563  // Insert VAARG_64 node into the DAG
9564  // VAARG_64 returns two values: Variable Argument Address, Chain
9565  SmallVector<SDValue, 11> InstOps;
9566  InstOps.push_back(Chain);
9567  InstOps.push_back(SrcPtr);
9568  InstOps.push_back(DAG.getConstant(ArgSize, MVT::i32));
9569  InstOps.push_back(DAG.getConstant(ArgMode, MVT::i8));
9570  InstOps.push_back(DAG.getConstant(Align, MVT::i32));
9571  SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other);
9572  SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
9573                                          VTs, &InstOps[0], InstOps.size(),
9574                                          MVT::i64,
9575                                          MachinePointerInfo(SV),
9576                                          /*Align=*/0,
9577                                          /*Volatile=*/false,
9578                                          /*ReadMem=*/true,
9579                                          /*WriteMem=*/true);
9580  Chain = VAARG.getValue(1);
9581
9582  // Load the next argument and return it
9583  return DAG.getLoad(ArgVT, dl,
9584                     Chain,
9585                     VAARG,
9586                     MachinePointerInfo(),
9587                     false, false, false, 0);
9588}
9589
9590SDValue X86TargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) const {
9591  // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
9592  assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
9593  SDValue Chain = Op.getOperand(0);
9594  SDValue DstPtr = Op.getOperand(1);
9595  SDValue SrcPtr = Op.getOperand(2);
9596  const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
9597  const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
9598  DebugLoc DL = Op.getDebugLoc();
9599
9600  return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
9601                       DAG.getIntPtrConstant(24), 8, /*isVolatile*/false,
9602                       false,
9603                       MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
9604}
9605
9606// getTargetVShiftNOde - Handle vector element shifts where the shift amount
9607// may or may not be a constant. Takes immediate version of shift as input.
9608static SDValue getTargetVShiftNode(unsigned Opc, DebugLoc dl, EVT VT,
9609                                   SDValue SrcOp, SDValue ShAmt,
9610                                   SelectionDAG &DAG) {
9611  assert(ShAmt.getValueType() == MVT::i32 && "ShAmt is not i32");
9612
9613  if (isa<ConstantSDNode>(ShAmt)) {
9614    // Constant may be a TargetConstant. Use a regular constant.
9615    uint32_t ShiftAmt = cast<ConstantSDNode>(ShAmt)->getZExtValue();
9616    switch (Opc) {
9617      default: llvm_unreachable("Unknown target vector shift node");
9618      case X86ISD::VSHLI:
9619      case X86ISD::VSRLI:
9620      case X86ISD::VSRAI:
9621        return DAG.getNode(Opc, dl, VT, SrcOp,
9622                           DAG.getConstant(ShiftAmt, MVT::i32));
9623    }
9624  }
9625
9626  // Change opcode to non-immediate version
9627  switch (Opc) {
9628    default: llvm_unreachable("Unknown target vector shift node");
9629    case X86ISD::VSHLI: Opc = X86ISD::VSHL; break;
9630    case X86ISD::VSRLI: Opc = X86ISD::VSRL; break;
9631    case X86ISD::VSRAI: Opc = X86ISD::VSRA; break;
9632  }
9633
9634  // Need to build a vector containing shift amount
9635  // Shift amount is 32-bits, but SSE instructions read 64-bit, so fill with 0
9636  SDValue ShOps[4];
9637  ShOps[0] = ShAmt;
9638  ShOps[1] = DAG.getConstant(0, MVT::i32);
9639  ShOps[2] = ShOps[3] = DAG.getUNDEF(MVT::i32);
9640  ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, &ShOps[0], 4);
9641
9642  // The return type has to be a 128-bit type with the same element
9643  // type as the input type.
9644  MVT EltVT = VT.getVectorElementType().getSimpleVT();
9645  EVT ShVT = MVT::getVectorVT(EltVT, 128/EltVT.getSizeInBits());
9646
9647  ShAmt = DAG.getNode(ISD::BITCAST, dl, ShVT, ShAmt);
9648  return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
9649}
9650
9651SDValue
9652X86TargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) const {
9653  DebugLoc dl = Op.getDebugLoc();
9654  unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9655  switch (IntNo) {
9656  default: return SDValue();    // Don't custom lower most intrinsics.
9657  // Comparison intrinsics.
9658  case Intrinsic::x86_sse_comieq_ss:
9659  case Intrinsic::x86_sse_comilt_ss:
9660  case Intrinsic::x86_sse_comile_ss:
9661  case Intrinsic::x86_sse_comigt_ss:
9662  case Intrinsic::x86_sse_comige_ss:
9663  case Intrinsic::x86_sse_comineq_ss:
9664  case Intrinsic::x86_sse_ucomieq_ss:
9665  case Intrinsic::x86_sse_ucomilt_ss:
9666  case Intrinsic::x86_sse_ucomile_ss:
9667  case Intrinsic::x86_sse_ucomigt_ss:
9668  case Intrinsic::x86_sse_ucomige_ss:
9669  case Intrinsic::x86_sse_ucomineq_ss:
9670  case Intrinsic::x86_sse2_comieq_sd:
9671  case Intrinsic::x86_sse2_comilt_sd:
9672  case Intrinsic::x86_sse2_comile_sd:
9673  case Intrinsic::x86_sse2_comigt_sd:
9674  case Intrinsic::x86_sse2_comige_sd:
9675  case Intrinsic::x86_sse2_comineq_sd:
9676  case Intrinsic::x86_sse2_ucomieq_sd:
9677  case Intrinsic::x86_sse2_ucomilt_sd:
9678  case Intrinsic::x86_sse2_ucomile_sd:
9679  case Intrinsic::x86_sse2_ucomigt_sd:
9680  case Intrinsic::x86_sse2_ucomige_sd:
9681  case Intrinsic::x86_sse2_ucomineq_sd: {
9682    unsigned Opc;
9683    ISD::CondCode CC;
9684    switch (IntNo) {
9685    default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
9686    case Intrinsic::x86_sse_comieq_ss:
9687    case Intrinsic::x86_sse2_comieq_sd:
9688      Opc = X86ISD::COMI;
9689      CC = ISD::SETEQ;
9690      break;
9691    case Intrinsic::x86_sse_comilt_ss:
9692    case Intrinsic::x86_sse2_comilt_sd:
9693      Opc = X86ISD::COMI;
9694      CC = ISD::SETLT;
9695      break;
9696    case Intrinsic::x86_sse_comile_ss:
9697    case Intrinsic::x86_sse2_comile_sd:
9698      Opc = X86ISD::COMI;
9699      CC = ISD::SETLE;
9700      break;
9701    case Intrinsic::x86_sse_comigt_ss:
9702    case Intrinsic::x86_sse2_comigt_sd:
9703      Opc = X86ISD::COMI;
9704      CC = ISD::SETGT;
9705      break;
9706    case Intrinsic::x86_sse_comige_ss:
9707    case Intrinsic::x86_sse2_comige_sd:
9708      Opc = X86ISD::COMI;
9709      CC = ISD::SETGE;
9710      break;
9711    case Intrinsic::x86_sse_comineq_ss:
9712    case Intrinsic::x86_sse2_comineq_sd:
9713      Opc = X86ISD::COMI;
9714      CC = ISD::SETNE;
9715      break;
9716    case Intrinsic::x86_sse_ucomieq_ss:
9717    case Intrinsic::x86_sse2_ucomieq_sd:
9718      Opc = X86ISD::UCOMI;
9719      CC = ISD::SETEQ;
9720      break;
9721    case Intrinsic::x86_sse_ucomilt_ss:
9722    case Intrinsic::x86_sse2_ucomilt_sd:
9723      Opc = X86ISD::UCOMI;
9724      CC = ISD::SETLT;
9725      break;
9726    case Intrinsic::x86_sse_ucomile_ss:
9727    case Intrinsic::x86_sse2_ucomile_sd:
9728      Opc = X86ISD::UCOMI;
9729      CC = ISD::SETLE;
9730      break;
9731    case Intrinsic::x86_sse_ucomigt_ss:
9732    case Intrinsic::x86_sse2_ucomigt_sd:
9733      Opc = X86ISD::UCOMI;
9734      CC = ISD::SETGT;
9735      break;
9736    case Intrinsic::x86_sse_ucomige_ss:
9737    case Intrinsic::x86_sse2_ucomige_sd:
9738      Opc = X86ISD::UCOMI;
9739      CC = ISD::SETGE;
9740      break;
9741    case Intrinsic::x86_sse_ucomineq_ss:
9742    case Intrinsic::x86_sse2_ucomineq_sd:
9743      Opc = X86ISD::UCOMI;
9744      CC = ISD::SETNE;
9745      break;
9746    }
9747
9748    SDValue LHS = Op.getOperand(1);
9749    SDValue RHS = Op.getOperand(2);
9750    unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
9751    assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
9752    SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS);
9753    SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
9754                                DAG.getConstant(X86CC, MVT::i8), Cond);
9755    return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
9756  }
9757
9758  // Arithmetic intrinsics.
9759  case Intrinsic::x86_sse2_pmulu_dq:
9760  case Intrinsic::x86_avx2_pmulu_dq:
9761    return DAG.getNode(X86ISD::PMULUDQ, dl, Op.getValueType(),
9762                       Op.getOperand(1), Op.getOperand(2));
9763
9764  // SSE3/AVX horizontal add/sub intrinsics
9765  case Intrinsic::x86_sse3_hadd_ps:
9766  case Intrinsic::x86_sse3_hadd_pd:
9767  case Intrinsic::x86_avx_hadd_ps_256:
9768  case Intrinsic::x86_avx_hadd_pd_256:
9769  case Intrinsic::x86_sse3_hsub_ps:
9770  case Intrinsic::x86_sse3_hsub_pd:
9771  case Intrinsic::x86_avx_hsub_ps_256:
9772  case Intrinsic::x86_avx_hsub_pd_256:
9773  case Intrinsic::x86_ssse3_phadd_w_128:
9774  case Intrinsic::x86_ssse3_phadd_d_128:
9775  case Intrinsic::x86_avx2_phadd_w:
9776  case Intrinsic::x86_avx2_phadd_d:
9777  case Intrinsic::x86_ssse3_phsub_w_128:
9778  case Intrinsic::x86_ssse3_phsub_d_128:
9779  case Intrinsic::x86_avx2_phsub_w:
9780  case Intrinsic::x86_avx2_phsub_d: {
9781    unsigned Opcode;
9782    switch (IntNo) {
9783    default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
9784    case Intrinsic::x86_sse3_hadd_ps:
9785    case Intrinsic::x86_sse3_hadd_pd:
9786    case Intrinsic::x86_avx_hadd_ps_256:
9787    case Intrinsic::x86_avx_hadd_pd_256:
9788      Opcode = X86ISD::FHADD;
9789      break;
9790    case Intrinsic::x86_sse3_hsub_ps:
9791    case Intrinsic::x86_sse3_hsub_pd:
9792    case Intrinsic::x86_avx_hsub_ps_256:
9793    case Intrinsic::x86_avx_hsub_pd_256:
9794      Opcode = X86ISD::FHSUB;
9795      break;
9796    case Intrinsic::x86_ssse3_phadd_w_128:
9797    case Intrinsic::x86_ssse3_phadd_d_128:
9798    case Intrinsic::x86_avx2_phadd_w:
9799    case Intrinsic::x86_avx2_phadd_d:
9800      Opcode = X86ISD::HADD;
9801      break;
9802    case Intrinsic::x86_ssse3_phsub_w_128:
9803    case Intrinsic::x86_ssse3_phsub_d_128:
9804    case Intrinsic::x86_avx2_phsub_w:
9805    case Intrinsic::x86_avx2_phsub_d:
9806      Opcode = X86ISD::HSUB;
9807      break;
9808    }
9809    return DAG.getNode(Opcode, dl, Op.getValueType(),
9810                       Op.getOperand(1), Op.getOperand(2));
9811  }
9812
9813  // AVX2 variable shift intrinsics
9814  case Intrinsic::x86_avx2_psllv_d:
9815  case Intrinsic::x86_avx2_psllv_q:
9816  case Intrinsic::x86_avx2_psllv_d_256:
9817  case Intrinsic::x86_avx2_psllv_q_256:
9818  case Intrinsic::x86_avx2_psrlv_d:
9819  case Intrinsic::x86_avx2_psrlv_q:
9820  case Intrinsic::x86_avx2_psrlv_d_256:
9821  case Intrinsic::x86_avx2_psrlv_q_256:
9822  case Intrinsic::x86_avx2_psrav_d:
9823  case Intrinsic::x86_avx2_psrav_d_256: {
9824    unsigned Opcode;
9825    switch (IntNo) {
9826    default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
9827    case Intrinsic::x86_avx2_psllv_d:
9828    case Intrinsic::x86_avx2_psllv_q:
9829    case Intrinsic::x86_avx2_psllv_d_256:
9830    case Intrinsic::x86_avx2_psllv_q_256:
9831      Opcode = ISD::SHL;
9832      break;
9833    case Intrinsic::x86_avx2_psrlv_d:
9834    case Intrinsic::x86_avx2_psrlv_q:
9835    case Intrinsic::x86_avx2_psrlv_d_256:
9836    case Intrinsic::x86_avx2_psrlv_q_256:
9837      Opcode = ISD::SRL;
9838      break;
9839    case Intrinsic::x86_avx2_psrav_d:
9840    case Intrinsic::x86_avx2_psrav_d_256:
9841      Opcode = ISD::SRA;
9842      break;
9843    }
9844    return DAG.getNode(Opcode, dl, Op.getValueType(),
9845                       Op.getOperand(1), Op.getOperand(2));
9846  }
9847
9848  case Intrinsic::x86_ssse3_pshuf_b_128:
9849  case Intrinsic::x86_avx2_pshuf_b:
9850    return DAG.getNode(X86ISD::PSHUFB, dl, Op.getValueType(),
9851                       Op.getOperand(1), Op.getOperand(2));
9852
9853  case Intrinsic::x86_ssse3_psign_b_128:
9854  case Intrinsic::x86_ssse3_psign_w_128:
9855  case Intrinsic::x86_ssse3_psign_d_128:
9856  case Intrinsic::x86_avx2_psign_b:
9857  case Intrinsic::x86_avx2_psign_w:
9858  case Intrinsic::x86_avx2_psign_d:
9859    return DAG.getNode(X86ISD::PSIGN, dl, Op.getValueType(),
9860                       Op.getOperand(1), Op.getOperand(2));
9861
9862  case Intrinsic::x86_sse41_insertps:
9863    return DAG.getNode(X86ISD::INSERTPS, dl, Op.getValueType(),
9864                       Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
9865
9866  case Intrinsic::x86_avx_vperm2f128_ps_256:
9867  case Intrinsic::x86_avx_vperm2f128_pd_256:
9868  case Intrinsic::x86_avx_vperm2f128_si_256:
9869  case Intrinsic::x86_avx2_vperm2i128:
9870    return DAG.getNode(X86ISD::VPERM2X128, dl, Op.getValueType(),
9871                       Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
9872
9873  case Intrinsic::x86_avx2_permd:
9874  case Intrinsic::x86_avx2_permps:
9875    // Operands intentionally swapped. Mask is last operand to intrinsic,
9876    // but second operand for node/intruction.
9877    return DAG.getNode(X86ISD::VPERMV, dl, Op.getValueType(),
9878                       Op.getOperand(2), Op.getOperand(1));
9879
9880  // ptest and testp intrinsics. The intrinsic these come from are designed to
9881  // return an integer value, not just an instruction so lower it to the ptest
9882  // or testp pattern and a setcc for the result.
9883  case Intrinsic::x86_sse41_ptestz:
9884  case Intrinsic::x86_sse41_ptestc:
9885  case Intrinsic::x86_sse41_ptestnzc:
9886  case Intrinsic::x86_avx_ptestz_256:
9887  case Intrinsic::x86_avx_ptestc_256:
9888  case Intrinsic::x86_avx_ptestnzc_256:
9889  case Intrinsic::x86_avx_vtestz_ps:
9890  case Intrinsic::x86_avx_vtestc_ps:
9891  case Intrinsic::x86_avx_vtestnzc_ps:
9892  case Intrinsic::x86_avx_vtestz_pd:
9893  case Intrinsic::x86_avx_vtestc_pd:
9894  case Intrinsic::x86_avx_vtestnzc_pd:
9895  case Intrinsic::x86_avx_vtestz_ps_256:
9896  case Intrinsic::x86_avx_vtestc_ps_256:
9897  case Intrinsic::x86_avx_vtestnzc_ps_256:
9898  case Intrinsic::x86_avx_vtestz_pd_256:
9899  case Intrinsic::x86_avx_vtestc_pd_256:
9900  case Intrinsic::x86_avx_vtestnzc_pd_256: {
9901    bool IsTestPacked = false;
9902    unsigned X86CC;
9903    switch (IntNo) {
9904    default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
9905    case Intrinsic::x86_avx_vtestz_ps:
9906    case Intrinsic::x86_avx_vtestz_pd:
9907    case Intrinsic::x86_avx_vtestz_ps_256:
9908    case Intrinsic::x86_avx_vtestz_pd_256:
9909      IsTestPacked = true; // Fallthrough
9910    case Intrinsic::x86_sse41_ptestz:
9911    case Intrinsic::x86_avx_ptestz_256:
9912      // ZF = 1
9913      X86CC = X86::COND_E;
9914      break;
9915    case Intrinsic::x86_avx_vtestc_ps:
9916    case Intrinsic::x86_avx_vtestc_pd:
9917    case Intrinsic::x86_avx_vtestc_ps_256:
9918    case Intrinsic::x86_avx_vtestc_pd_256:
9919      IsTestPacked = true; // Fallthrough
9920    case Intrinsic::x86_sse41_ptestc:
9921    case Intrinsic::x86_avx_ptestc_256:
9922      // CF = 1
9923      X86CC = X86::COND_B;
9924      break;
9925    case Intrinsic::x86_avx_vtestnzc_ps:
9926    case Intrinsic::x86_avx_vtestnzc_pd:
9927    case Intrinsic::x86_avx_vtestnzc_ps_256:
9928    case Intrinsic::x86_avx_vtestnzc_pd_256:
9929      IsTestPacked = true; // Fallthrough
9930    case Intrinsic::x86_sse41_ptestnzc:
9931    case Intrinsic::x86_avx_ptestnzc_256:
9932      // ZF and CF = 0
9933      X86CC = X86::COND_A;
9934      break;
9935    }
9936
9937    SDValue LHS = Op.getOperand(1);
9938    SDValue RHS = Op.getOperand(2);
9939    unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
9940    SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
9941    SDValue CC = DAG.getConstant(X86CC, MVT::i8);
9942    SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
9943    return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
9944  }
9945
9946  // SSE/AVX shift intrinsics
9947  case Intrinsic::x86_sse2_psll_w:
9948  case Intrinsic::x86_sse2_psll_d:
9949  case Intrinsic::x86_sse2_psll_q:
9950  case Intrinsic::x86_avx2_psll_w:
9951  case Intrinsic::x86_avx2_psll_d:
9952  case Intrinsic::x86_avx2_psll_q:
9953  case Intrinsic::x86_sse2_psrl_w:
9954  case Intrinsic::x86_sse2_psrl_d:
9955  case Intrinsic::x86_sse2_psrl_q:
9956  case Intrinsic::x86_avx2_psrl_w:
9957  case Intrinsic::x86_avx2_psrl_d:
9958  case Intrinsic::x86_avx2_psrl_q:
9959  case Intrinsic::x86_sse2_psra_w:
9960  case Intrinsic::x86_sse2_psra_d:
9961  case Intrinsic::x86_avx2_psra_w:
9962  case Intrinsic::x86_avx2_psra_d: {
9963    unsigned Opcode;
9964    switch (IntNo) {
9965    default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
9966    case Intrinsic::x86_sse2_psll_w:
9967    case Intrinsic::x86_sse2_psll_d:
9968    case Intrinsic::x86_sse2_psll_q:
9969    case Intrinsic::x86_avx2_psll_w:
9970    case Intrinsic::x86_avx2_psll_d:
9971    case Intrinsic::x86_avx2_psll_q:
9972      Opcode = X86ISD::VSHL;
9973      break;
9974    case Intrinsic::x86_sse2_psrl_w:
9975    case Intrinsic::x86_sse2_psrl_d:
9976    case Intrinsic::x86_sse2_psrl_q:
9977    case Intrinsic::x86_avx2_psrl_w:
9978    case Intrinsic::x86_avx2_psrl_d:
9979    case Intrinsic::x86_avx2_psrl_q:
9980      Opcode = X86ISD::VSRL;
9981      break;
9982    case Intrinsic::x86_sse2_psra_w:
9983    case Intrinsic::x86_sse2_psra_d:
9984    case Intrinsic::x86_avx2_psra_w:
9985    case Intrinsic::x86_avx2_psra_d:
9986      Opcode = X86ISD::VSRA;
9987      break;
9988    }
9989    return DAG.getNode(Opcode, dl, Op.getValueType(),
9990                       Op.getOperand(1), Op.getOperand(2));
9991  }
9992
9993  // SSE/AVX immediate shift intrinsics
9994  case Intrinsic::x86_sse2_pslli_w:
9995  case Intrinsic::x86_sse2_pslli_d:
9996  case Intrinsic::x86_sse2_pslli_q:
9997  case Intrinsic::x86_avx2_pslli_w:
9998  case Intrinsic::x86_avx2_pslli_d:
9999  case Intrinsic::x86_avx2_pslli_q:
10000  case Intrinsic::x86_sse2_psrli_w:
10001  case Intrinsic::x86_sse2_psrli_d:
10002  case Intrinsic::x86_sse2_psrli_q:
10003  case Intrinsic::x86_avx2_psrli_w:
10004  case Intrinsic::x86_avx2_psrli_d:
10005  case Intrinsic::x86_avx2_psrli_q:
10006  case Intrinsic::x86_sse2_psrai_w:
10007  case Intrinsic::x86_sse2_psrai_d:
10008  case Intrinsic::x86_avx2_psrai_w:
10009  case Intrinsic::x86_avx2_psrai_d: {
10010    unsigned Opcode;
10011    switch (IntNo) {
10012    default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
10013    case Intrinsic::x86_sse2_pslli_w:
10014    case Intrinsic::x86_sse2_pslli_d:
10015    case Intrinsic::x86_sse2_pslli_q:
10016    case Intrinsic::x86_avx2_pslli_w:
10017    case Intrinsic::x86_avx2_pslli_d:
10018    case Intrinsic::x86_avx2_pslli_q:
10019      Opcode = X86ISD::VSHLI;
10020      break;
10021    case Intrinsic::x86_sse2_psrli_w:
10022    case Intrinsic::x86_sse2_psrli_d:
10023    case Intrinsic::x86_sse2_psrli_q:
10024    case Intrinsic::x86_avx2_psrli_w:
10025    case Intrinsic::x86_avx2_psrli_d:
10026    case Intrinsic::x86_avx2_psrli_q:
10027      Opcode = X86ISD::VSRLI;
10028      break;
10029    case Intrinsic::x86_sse2_psrai_w:
10030    case Intrinsic::x86_sse2_psrai_d:
10031    case Intrinsic::x86_avx2_psrai_w:
10032    case Intrinsic::x86_avx2_psrai_d:
10033      Opcode = X86ISD::VSRAI;
10034      break;
10035    }
10036    return getTargetVShiftNode(Opcode, dl, Op.getValueType(),
10037                               Op.getOperand(1), Op.getOperand(2), DAG);
10038  }
10039
10040  case Intrinsic::x86_sse42_pcmpistria128:
10041  case Intrinsic::x86_sse42_pcmpestria128:
10042  case Intrinsic::x86_sse42_pcmpistric128:
10043  case Intrinsic::x86_sse42_pcmpestric128:
10044  case Intrinsic::x86_sse42_pcmpistrio128:
10045  case Intrinsic::x86_sse42_pcmpestrio128:
10046  case Intrinsic::x86_sse42_pcmpistris128:
10047  case Intrinsic::x86_sse42_pcmpestris128:
10048  case Intrinsic::x86_sse42_pcmpistriz128:
10049  case Intrinsic::x86_sse42_pcmpestriz128: {
10050    unsigned Opcode;
10051    unsigned X86CC;
10052    switch (IntNo) {
10053    default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
10054    case Intrinsic::x86_sse42_pcmpistria128:
10055      Opcode = X86ISD::PCMPISTRI;
10056      X86CC = X86::COND_A;
10057      break;
10058    case Intrinsic::x86_sse42_pcmpestria128:
10059      Opcode = X86ISD::PCMPESTRI;
10060      X86CC = X86::COND_A;
10061      break;
10062    case Intrinsic::x86_sse42_pcmpistric128:
10063      Opcode = X86ISD::PCMPISTRI;
10064      X86CC = X86::COND_B;
10065      break;
10066    case Intrinsic::x86_sse42_pcmpestric128:
10067      Opcode = X86ISD::PCMPESTRI;
10068      X86CC = X86::COND_B;
10069      break;
10070    case Intrinsic::x86_sse42_pcmpistrio128:
10071      Opcode = X86ISD::PCMPISTRI;
10072      X86CC = X86::COND_O;
10073      break;
10074    case Intrinsic::x86_sse42_pcmpestrio128:
10075      Opcode = X86ISD::PCMPESTRI;
10076      X86CC = X86::COND_O;
10077      break;
10078    case Intrinsic::x86_sse42_pcmpistris128:
10079      Opcode = X86ISD::PCMPISTRI;
10080      X86CC = X86::COND_S;
10081      break;
10082    case Intrinsic::x86_sse42_pcmpestris128:
10083      Opcode = X86ISD::PCMPESTRI;
10084      X86CC = X86::COND_S;
10085      break;
10086    case Intrinsic::x86_sse42_pcmpistriz128:
10087      Opcode = X86ISD::PCMPISTRI;
10088      X86CC = X86::COND_E;
10089      break;
10090    case Intrinsic::x86_sse42_pcmpestriz128:
10091      Opcode = X86ISD::PCMPESTRI;
10092      X86CC = X86::COND_E;
10093      break;
10094    }
10095    SmallVector<SDValue, 5> NewOps;
10096    NewOps.append(Op->op_begin()+1, Op->op_end());
10097    SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
10098    SDValue PCMP = DAG.getNode(Opcode, dl, VTs, NewOps.data(), NewOps.size());
10099    SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
10100                                DAG.getConstant(X86CC, MVT::i8),
10101                                SDValue(PCMP.getNode(), 1));
10102    return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
10103  }
10104
10105  case Intrinsic::x86_sse42_pcmpistri128:
10106  case Intrinsic::x86_sse42_pcmpestri128: {
10107    unsigned Opcode;
10108    if (IntNo == Intrinsic::x86_sse42_pcmpistri128)
10109      Opcode = X86ISD::PCMPISTRI;
10110    else
10111      Opcode = X86ISD::PCMPESTRI;
10112
10113    SmallVector<SDValue, 5> NewOps;
10114    NewOps.append(Op->op_begin()+1, Op->op_end());
10115    SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
10116    return DAG.getNode(Opcode, dl, VTs, NewOps.data(), NewOps.size());
10117  }
10118  case Intrinsic::x86_fma_vfmadd_ps:
10119  case Intrinsic::x86_fma_vfmadd_pd:
10120  case Intrinsic::x86_fma_vfmsub_ps:
10121  case Intrinsic::x86_fma_vfmsub_pd:
10122  case Intrinsic::x86_fma_vfnmadd_ps:
10123  case Intrinsic::x86_fma_vfnmadd_pd:
10124  case Intrinsic::x86_fma_vfnmsub_ps:
10125  case Intrinsic::x86_fma_vfnmsub_pd:
10126  case Intrinsic::x86_fma_vfmaddsub_ps:
10127  case Intrinsic::x86_fma_vfmaddsub_pd:
10128  case Intrinsic::x86_fma_vfmsubadd_ps:
10129  case Intrinsic::x86_fma_vfmsubadd_pd:
10130  case Intrinsic::x86_fma_vfmadd_ps_256:
10131  case Intrinsic::x86_fma_vfmadd_pd_256:
10132  case Intrinsic::x86_fma_vfmsub_ps_256:
10133  case Intrinsic::x86_fma_vfmsub_pd_256:
10134  case Intrinsic::x86_fma_vfnmadd_ps_256:
10135  case Intrinsic::x86_fma_vfnmadd_pd_256:
10136  case Intrinsic::x86_fma_vfnmsub_ps_256:
10137  case Intrinsic::x86_fma_vfnmsub_pd_256:
10138  case Intrinsic::x86_fma_vfmaddsub_ps_256:
10139  case Intrinsic::x86_fma_vfmaddsub_pd_256:
10140  case Intrinsic::x86_fma_vfmsubadd_ps_256:
10141  case Intrinsic::x86_fma_vfmsubadd_pd_256: {
10142    unsigned Opc;
10143    switch (IntNo) {
10144    default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
10145    case Intrinsic::x86_fma_vfmadd_ps:
10146    case Intrinsic::x86_fma_vfmadd_pd:
10147    case Intrinsic::x86_fma_vfmadd_ps_256:
10148    case Intrinsic::x86_fma_vfmadd_pd_256:
10149      Opc = X86ISD::FMADD;
10150      break;
10151    case Intrinsic::x86_fma_vfmsub_ps:
10152    case Intrinsic::x86_fma_vfmsub_pd:
10153    case Intrinsic::x86_fma_vfmsub_ps_256:
10154    case Intrinsic::x86_fma_vfmsub_pd_256:
10155      Opc = X86ISD::FMSUB;
10156      break;
10157    case Intrinsic::x86_fma_vfnmadd_ps:
10158    case Intrinsic::x86_fma_vfnmadd_pd:
10159    case Intrinsic::x86_fma_vfnmadd_ps_256:
10160    case Intrinsic::x86_fma_vfnmadd_pd_256:
10161      Opc = X86ISD::FNMADD;
10162      break;
10163    case Intrinsic::x86_fma_vfnmsub_ps:
10164    case Intrinsic::x86_fma_vfnmsub_pd:
10165    case Intrinsic::x86_fma_vfnmsub_ps_256:
10166    case Intrinsic::x86_fma_vfnmsub_pd_256:
10167      Opc = X86ISD::FNMSUB;
10168      break;
10169    case Intrinsic::x86_fma_vfmaddsub_ps:
10170    case Intrinsic::x86_fma_vfmaddsub_pd:
10171    case Intrinsic::x86_fma_vfmaddsub_ps_256:
10172    case Intrinsic::x86_fma_vfmaddsub_pd_256:
10173      Opc = X86ISD::FMADDSUB;
10174      break;
10175    case Intrinsic::x86_fma_vfmsubadd_ps:
10176    case Intrinsic::x86_fma_vfmsubadd_pd:
10177    case Intrinsic::x86_fma_vfmsubadd_ps_256:
10178    case Intrinsic::x86_fma_vfmsubadd_pd_256:
10179      Opc = X86ISD::FMSUBADD;
10180      break;
10181    }
10182
10183    return DAG.getNode(Opc, dl, Op.getValueType(), Op.getOperand(1),
10184                       Op.getOperand(2), Op.getOperand(3));
10185  }
10186  }
10187}
10188
10189SDValue
10190X86TargetLowering::LowerINTRINSIC_W_CHAIN(SDValue Op, SelectionDAG &DAG) const {
10191  DebugLoc dl = Op.getDebugLoc();
10192  unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10193  switch (IntNo) {
10194  default: return SDValue();    // Don't custom lower most intrinsics.
10195
10196  // RDRAND intrinsics.
10197  case Intrinsic::x86_rdrand_16:
10198  case Intrinsic::x86_rdrand_32:
10199  case Intrinsic::x86_rdrand_64: {
10200    // Emit the node with the right value type.
10201    SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Glue, MVT::Other);
10202    SDValue Result = DAG.getNode(X86ISD::RDRAND, dl, VTs, Op.getOperand(0));
10203
10204    // If the value returned by RDRAND was valid (CF=1), return 1. Otherwise
10205    // return the value from Rand, which is always 0, casted to i32.
10206    SDValue Ops[] = { DAG.getZExtOrTrunc(Result, dl, Op->getValueType(1)),
10207                      DAG.getConstant(1, Op->getValueType(1)),
10208                      DAG.getConstant(X86::COND_B, MVT::i32),
10209                      SDValue(Result.getNode(), 1) };
10210    SDValue isValid = DAG.getNode(X86ISD::CMOV, dl,
10211                                  DAG.getVTList(Op->getValueType(1), MVT::Glue),
10212                                  Ops, 4);
10213
10214    // Return { result, isValid, chain }.
10215    return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), Result, isValid,
10216                       SDValue(Result.getNode(), 2));
10217  }
10218  }
10219}
10220
10221SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
10222                                           SelectionDAG &DAG) const {
10223  MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
10224  MFI->setReturnAddressIsTaken(true);
10225
10226  unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
10227  DebugLoc dl = Op.getDebugLoc();
10228
10229  if (Depth > 0) {
10230    SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
10231    SDValue Offset =
10232      DAG.getConstant(TD->getPointerSize(),
10233                      Subtarget->is64Bit() ? MVT::i64 : MVT::i32);
10234    return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
10235                       DAG.getNode(ISD::ADD, dl, getPointerTy(),
10236                                   FrameAddr, Offset),
10237                       MachinePointerInfo(), false, false, false, 0);
10238  }
10239
10240  // Just load the return address.
10241  SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
10242  return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
10243                     RetAddrFI, MachinePointerInfo(), false, false, false, 0);
10244}
10245
10246SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
10247  MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
10248  MFI->setFrameAddressIsTaken(true);
10249
10250  EVT VT = Op.getValueType();
10251  DebugLoc dl = Op.getDebugLoc();  // FIXME probably not meaningful
10252  unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
10253  unsigned FrameReg = Subtarget->is64Bit() ? X86::RBP : X86::EBP;
10254  SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
10255  while (Depth--)
10256    FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
10257                            MachinePointerInfo(),
10258                            false, false, false, 0);
10259  return FrameAddr;
10260}
10261
10262SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
10263                                                     SelectionDAG &DAG) const {
10264  return DAG.getIntPtrConstant(2*TD->getPointerSize());
10265}
10266
10267SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
10268  SDValue Chain     = Op.getOperand(0);
10269  SDValue Offset    = Op.getOperand(1);
10270  SDValue Handler   = Op.getOperand(2);
10271  DebugLoc dl       = Op.getDebugLoc();
10272
10273  SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl,
10274                                     Subtarget->is64Bit() ? X86::RBP : X86::EBP,
10275                                     getPointerTy());
10276  unsigned StoreAddrReg = (Subtarget->is64Bit() ? X86::RCX : X86::ECX);
10277
10278  SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), Frame,
10279                                  DAG.getIntPtrConstant(TD->getPointerSize()));
10280  StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), StoreAddr, Offset);
10281  Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
10282                       false, false, 0);
10283  Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
10284
10285  return DAG.getNode(X86ISD::EH_RETURN, dl,
10286                     MVT::Other,
10287                     Chain, DAG.getRegister(StoreAddrReg, getPointerTy()));
10288}
10289
10290SDValue X86TargetLowering::LowerADJUST_TRAMPOLINE(SDValue Op,
10291                                                  SelectionDAG &DAG) const {
10292  return Op.getOperand(0);
10293}
10294
10295SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
10296                                                SelectionDAG &DAG) const {
10297  SDValue Root = Op.getOperand(0);
10298  SDValue Trmp = Op.getOperand(1); // trampoline
10299  SDValue FPtr = Op.getOperand(2); // nested function
10300  SDValue Nest = Op.getOperand(3); // 'nest' parameter value
10301  DebugLoc dl  = Op.getDebugLoc();
10302
10303  const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
10304
10305  if (Subtarget->is64Bit()) {
10306    SDValue OutChains[6];
10307
10308    // Large code-model.
10309    const unsigned char JMP64r  = 0xFF; // 64-bit jmp through register opcode.
10310    const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
10311
10312    const unsigned char N86R10 = X86_MC::getX86RegNum(X86::R10);
10313    const unsigned char N86R11 = X86_MC::getX86RegNum(X86::R11);
10314
10315    const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
10316
10317    // Load the pointer to the nested function into R11.
10318    unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
10319    SDValue Addr = Trmp;
10320    OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
10321                                Addr, MachinePointerInfo(TrmpAddr),
10322                                false, false, 0);
10323
10324    Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
10325                       DAG.getConstant(2, MVT::i64));
10326    OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
10327                                MachinePointerInfo(TrmpAddr, 2),
10328                                false, false, 2);
10329
10330    // Load the 'nest' parameter value into R10.
10331    // R10 is specified in X86CallingConv.td
10332    OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
10333    Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
10334                       DAG.getConstant(10, MVT::i64));
10335    OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
10336                                Addr, MachinePointerInfo(TrmpAddr, 10),
10337                                false, false, 0);
10338
10339    Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
10340                       DAG.getConstant(12, MVT::i64));
10341    OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
10342                                MachinePointerInfo(TrmpAddr, 12),
10343                                false, false, 2);
10344
10345    // Jump to the nested function.
10346    OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
10347    Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
10348                       DAG.getConstant(20, MVT::i64));
10349    OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
10350                                Addr, MachinePointerInfo(TrmpAddr, 20),
10351                                false, false, 0);
10352
10353    unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
10354    Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
10355                       DAG.getConstant(22, MVT::i64));
10356    OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
10357                                MachinePointerInfo(TrmpAddr, 22),
10358                                false, false, 0);
10359
10360    return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 6);
10361  } else {
10362    const Function *Func =
10363      cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
10364    CallingConv::ID CC = Func->getCallingConv();
10365    unsigned NestReg;
10366
10367    switch (CC) {
10368    default:
10369      llvm_unreachable("Unsupported calling convention");
10370    case CallingConv::C:
10371    case CallingConv::X86_StdCall: {
10372      // Pass 'nest' parameter in ECX.
10373      // Must be kept in sync with X86CallingConv.td
10374      NestReg = X86::ECX;
10375
10376      // Check that ECX wasn't needed by an 'inreg' parameter.
10377      FunctionType *FTy = Func->getFunctionType();
10378      const AttrListPtr &Attrs = Func->getAttributes();
10379
10380      if (!Attrs.isEmpty() && !Func->isVarArg()) {
10381        unsigned InRegCount = 0;
10382        unsigned Idx = 1;
10383
10384        for (FunctionType::param_iterator I = FTy->param_begin(),
10385             E = FTy->param_end(); I != E; ++I, ++Idx)
10386          if (Attrs.paramHasAttr(Idx, Attribute::InReg))
10387            // FIXME: should only count parameters that are lowered to integers.
10388            InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
10389
10390        if (InRegCount > 2) {
10391          report_fatal_error("Nest register in use - reduce number of inreg"
10392                             " parameters!");
10393        }
10394      }
10395      break;
10396    }
10397    case CallingConv::X86_FastCall:
10398    case CallingConv::X86_ThisCall:
10399    case CallingConv::Fast:
10400      // Pass 'nest' parameter in EAX.
10401      // Must be kept in sync with X86CallingConv.td
10402      NestReg = X86::EAX;
10403      break;
10404    }
10405
10406    SDValue OutChains[4];
10407    SDValue Addr, Disp;
10408
10409    Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
10410                       DAG.getConstant(10, MVT::i32));
10411    Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
10412
10413    // This is storing the opcode for MOV32ri.
10414    const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
10415    const unsigned char N86Reg = X86_MC::getX86RegNum(NestReg);
10416    OutChains[0] = DAG.getStore(Root, dl,
10417                                DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
10418                                Trmp, MachinePointerInfo(TrmpAddr),
10419                                false, false, 0);
10420
10421    Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
10422                       DAG.getConstant(1, MVT::i32));
10423    OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
10424                                MachinePointerInfo(TrmpAddr, 1),
10425                                false, false, 1);
10426
10427    const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
10428    Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
10429                       DAG.getConstant(5, MVT::i32));
10430    OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
10431                                MachinePointerInfo(TrmpAddr, 5),
10432                                false, false, 1);
10433
10434    Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
10435                       DAG.getConstant(6, MVT::i32));
10436    OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
10437                                MachinePointerInfo(TrmpAddr, 6),
10438                                false, false, 1);
10439
10440    return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 4);
10441  }
10442}
10443
10444SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
10445                                            SelectionDAG &DAG) const {
10446  /*
10447   The rounding mode is in bits 11:10 of FPSR, and has the following
10448   settings:
10449     00 Round to nearest
10450     01 Round to -inf
10451     10 Round to +inf
10452     11 Round to 0
10453
10454  FLT_ROUNDS, on the other hand, expects the following:
10455    -1 Undefined
10456     0 Round to 0
10457     1 Round to nearest
10458     2 Round to +inf
10459     3 Round to -inf
10460
10461  To perform the conversion, we do:
10462    (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
10463  */
10464
10465  MachineFunction &MF = DAG.getMachineFunction();
10466  const TargetMachine &TM = MF.getTarget();
10467  const TargetFrameLowering &TFI = *TM.getFrameLowering();
10468  unsigned StackAlignment = TFI.getStackAlignment();
10469  EVT VT = Op.getValueType();
10470  DebugLoc DL = Op.getDebugLoc();
10471
10472  // Save FP Control Word to stack slot
10473  int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
10474  SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
10475
10476
10477  MachineMemOperand *MMO =
10478   MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
10479                           MachineMemOperand::MOStore, 2, 2);
10480
10481  SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
10482  SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
10483                                          DAG.getVTList(MVT::Other),
10484                                          Ops, 2, MVT::i16, MMO);
10485
10486  // Load FP Control Word from stack slot
10487  SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
10488                            MachinePointerInfo(), false, false, false, 0);
10489
10490  // Transform as necessary
10491  SDValue CWD1 =
10492    DAG.getNode(ISD::SRL, DL, MVT::i16,
10493                DAG.getNode(ISD::AND, DL, MVT::i16,
10494                            CWD, DAG.getConstant(0x800, MVT::i16)),
10495                DAG.getConstant(11, MVT::i8));
10496  SDValue CWD2 =
10497    DAG.getNode(ISD::SRL, DL, MVT::i16,
10498                DAG.getNode(ISD::AND, DL, MVT::i16,
10499                            CWD, DAG.getConstant(0x400, MVT::i16)),
10500                DAG.getConstant(9, MVT::i8));
10501
10502  SDValue RetVal =
10503    DAG.getNode(ISD::AND, DL, MVT::i16,
10504                DAG.getNode(ISD::ADD, DL, MVT::i16,
10505                            DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
10506                            DAG.getConstant(1, MVT::i16)),
10507                DAG.getConstant(3, MVT::i16));
10508
10509
10510  return DAG.getNode((VT.getSizeInBits() < 16 ?
10511                      ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
10512}
10513
10514SDValue X86TargetLowering::LowerCTLZ(SDValue Op, SelectionDAG &DAG) const {
10515  EVT VT = Op.getValueType();
10516  EVT OpVT = VT;
10517  unsigned NumBits = VT.getSizeInBits();
10518  DebugLoc dl = Op.getDebugLoc();
10519
10520  Op = Op.getOperand(0);
10521  if (VT == MVT::i8) {
10522    // Zero extend to i32 since there is not an i8 bsr.
10523    OpVT = MVT::i32;
10524    Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
10525  }
10526
10527  // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
10528  SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
10529  Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
10530
10531  // If src is zero (i.e. bsr sets ZF), returns NumBits.
10532  SDValue Ops[] = {
10533    Op,
10534    DAG.getConstant(NumBits+NumBits-1, OpVT),
10535    DAG.getConstant(X86::COND_E, MVT::i8),
10536    Op.getValue(1)
10537  };
10538  Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
10539
10540  // Finally xor with NumBits-1.
10541  Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
10542
10543  if (VT == MVT::i8)
10544    Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
10545  return Op;
10546}
10547
10548SDValue X86TargetLowering::LowerCTLZ_ZERO_UNDEF(SDValue Op,
10549                                                SelectionDAG &DAG) const {
10550  EVT VT = Op.getValueType();
10551  EVT OpVT = VT;
10552  unsigned NumBits = VT.getSizeInBits();
10553  DebugLoc dl = Op.getDebugLoc();
10554
10555  Op = Op.getOperand(0);
10556  if (VT == MVT::i8) {
10557    // Zero extend to i32 since there is not an i8 bsr.
10558    OpVT = MVT::i32;
10559    Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
10560  }
10561
10562  // Issue a bsr (scan bits in reverse).
10563  SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
10564  Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
10565
10566  // And xor with NumBits-1.
10567  Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
10568
10569  if (VT == MVT::i8)
10570    Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
10571  return Op;
10572}
10573
10574SDValue X86TargetLowering::LowerCTTZ(SDValue Op, SelectionDAG &DAG) const {
10575  EVT VT = Op.getValueType();
10576  unsigned NumBits = VT.getSizeInBits();
10577  DebugLoc dl = Op.getDebugLoc();
10578  Op = Op.getOperand(0);
10579
10580  // Issue a bsf (scan bits forward) which also sets EFLAGS.
10581  SDVTList VTs = DAG.getVTList(VT, MVT::i32);
10582  Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
10583
10584  // If src is zero (i.e. bsf sets ZF), returns NumBits.
10585  SDValue Ops[] = {
10586    Op,
10587    DAG.getConstant(NumBits, VT),
10588    DAG.getConstant(X86::COND_E, MVT::i8),
10589    Op.getValue(1)
10590  };
10591  return DAG.getNode(X86ISD::CMOV, dl, VT, Ops, array_lengthof(Ops));
10592}
10593
10594// Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
10595// ones, and then concatenate the result back.
10596static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
10597  EVT VT = Op.getValueType();
10598
10599  assert(VT.is256BitVector() && VT.isInteger() &&
10600         "Unsupported value type for operation");
10601
10602  unsigned NumElems = VT.getVectorNumElements();
10603  DebugLoc dl = Op.getDebugLoc();
10604
10605  // Extract the LHS vectors
10606  SDValue LHS = Op.getOperand(0);
10607  SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
10608  SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
10609
10610  // Extract the RHS vectors
10611  SDValue RHS = Op.getOperand(1);
10612  SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
10613  SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
10614
10615  MVT EltVT = VT.getVectorElementType().getSimpleVT();
10616  EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
10617
10618  return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
10619                     DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
10620                     DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
10621}
10622
10623SDValue X86TargetLowering::LowerADD(SDValue Op, SelectionDAG &DAG) const {
10624  assert(Op.getValueType().is256BitVector() &&
10625         Op.getValueType().isInteger() &&
10626         "Only handle AVX 256-bit vector integer operation");
10627  return Lower256IntArith(Op, DAG);
10628}
10629
10630SDValue X86TargetLowering::LowerSUB(SDValue Op, SelectionDAG &DAG) const {
10631  assert(Op.getValueType().is256BitVector() &&
10632         Op.getValueType().isInteger() &&
10633         "Only handle AVX 256-bit vector integer operation");
10634  return Lower256IntArith(Op, DAG);
10635}
10636
10637SDValue X86TargetLowering::LowerMUL(SDValue Op, SelectionDAG &DAG) const {
10638  EVT VT = Op.getValueType();
10639
10640  // Decompose 256-bit ops into smaller 128-bit ops.
10641  if (VT.is256BitVector() && !Subtarget->hasAVX2())
10642    return Lower256IntArith(Op, DAG);
10643
10644  assert((VT == MVT::v2i64 || VT == MVT::v4i64) &&
10645         "Only know how to lower V2I64/V4I64 multiply");
10646
10647  DebugLoc dl = Op.getDebugLoc();
10648
10649  //  Ahi = psrlqi(a, 32);
10650  //  Bhi = psrlqi(b, 32);
10651  //
10652  //  AloBlo = pmuludq(a, b);
10653  //  AloBhi = pmuludq(a, Bhi);
10654  //  AhiBlo = pmuludq(Ahi, b);
10655
10656  //  AloBhi = psllqi(AloBhi, 32);
10657  //  AhiBlo = psllqi(AhiBlo, 32);
10658  //  return AloBlo + AloBhi + AhiBlo;
10659
10660  SDValue A = Op.getOperand(0);
10661  SDValue B = Op.getOperand(1);
10662
10663  SDValue ShAmt = DAG.getConstant(32, MVT::i32);
10664
10665  SDValue Ahi = DAG.getNode(X86ISD::VSRLI, dl, VT, A, ShAmt);
10666  SDValue Bhi = DAG.getNode(X86ISD::VSRLI, dl, VT, B, ShAmt);
10667
10668  // Bit cast to 32-bit vectors for MULUDQ
10669  EVT MulVT = (VT == MVT::v2i64) ? MVT::v4i32 : MVT::v8i32;
10670  A = DAG.getNode(ISD::BITCAST, dl, MulVT, A);
10671  B = DAG.getNode(ISD::BITCAST, dl, MulVT, B);
10672  Ahi = DAG.getNode(ISD::BITCAST, dl, MulVT, Ahi);
10673  Bhi = DAG.getNode(ISD::BITCAST, dl, MulVT, Bhi);
10674
10675  SDValue AloBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, B);
10676  SDValue AloBhi = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, Bhi);
10677  SDValue AhiBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, Ahi, B);
10678
10679  AloBhi = DAG.getNode(X86ISD::VSHLI, dl, VT, AloBhi, ShAmt);
10680  AhiBlo = DAG.getNode(X86ISD::VSHLI, dl, VT, AhiBlo, ShAmt);
10681
10682  SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
10683  return DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
10684}
10685
10686SDValue X86TargetLowering::LowerShift(SDValue Op, SelectionDAG &DAG) const {
10687
10688  EVT VT = Op.getValueType();
10689  DebugLoc dl = Op.getDebugLoc();
10690  SDValue R = Op.getOperand(0);
10691  SDValue Amt = Op.getOperand(1);
10692  LLVMContext *Context = DAG.getContext();
10693
10694  if (!Subtarget->hasSSE2())
10695    return SDValue();
10696
10697  // Optimize shl/srl/sra with constant shift amount.
10698  if (isSplatVector(Amt.getNode())) {
10699    SDValue SclrAmt = Amt->getOperand(0);
10700    if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt)) {
10701      uint64_t ShiftAmt = C->getZExtValue();
10702
10703      if (VT == MVT::v2i64 || VT == MVT::v4i32 || VT == MVT::v8i16 ||
10704          (Subtarget->hasAVX2() &&
10705           (VT == MVT::v4i64 || VT == MVT::v8i32 || VT == MVT::v16i16))) {
10706        if (Op.getOpcode() == ISD::SHL)
10707          return DAG.getNode(X86ISD::VSHLI, dl, VT, R,
10708                             DAG.getConstant(ShiftAmt, MVT::i32));
10709        if (Op.getOpcode() == ISD::SRL)
10710          return DAG.getNode(X86ISD::VSRLI, dl, VT, R,
10711                             DAG.getConstant(ShiftAmt, MVT::i32));
10712        if (Op.getOpcode() == ISD::SRA && VT != MVT::v2i64 && VT != MVT::v4i64)
10713          return DAG.getNode(X86ISD::VSRAI, dl, VT, R,
10714                             DAG.getConstant(ShiftAmt, MVT::i32));
10715      }
10716
10717      if (VT == MVT::v16i8) {
10718        if (Op.getOpcode() == ISD::SHL) {
10719          // Make a large shift.
10720          SDValue SHL = DAG.getNode(X86ISD::VSHLI, dl, MVT::v8i16, R,
10721                                    DAG.getConstant(ShiftAmt, MVT::i32));
10722          SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
10723          // Zero out the rightmost bits.
10724          SmallVector<SDValue, 16> V(16,
10725                                     DAG.getConstant(uint8_t(-1U << ShiftAmt),
10726                                                     MVT::i8));
10727          return DAG.getNode(ISD::AND, dl, VT, SHL,
10728                             DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16));
10729        }
10730        if (Op.getOpcode() == ISD::SRL) {
10731          // Make a large shift.
10732          SDValue SRL = DAG.getNode(X86ISD::VSRLI, dl, MVT::v8i16, R,
10733                                    DAG.getConstant(ShiftAmt, MVT::i32));
10734          SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
10735          // Zero out the leftmost bits.
10736          SmallVector<SDValue, 16> V(16,
10737                                     DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
10738                                                     MVT::i8));
10739          return DAG.getNode(ISD::AND, dl, VT, SRL,
10740                             DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16));
10741        }
10742        if (Op.getOpcode() == ISD::SRA) {
10743          if (ShiftAmt == 7) {
10744            // R s>> 7  ===  R s< 0
10745            SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
10746            return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
10747          }
10748
10749          // R s>> a === ((R u>> a) ^ m) - m
10750          SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
10751          SmallVector<SDValue, 16> V(16, DAG.getConstant(128 >> ShiftAmt,
10752                                                         MVT::i8));
10753          SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16);
10754          Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
10755          Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
10756          return Res;
10757        }
10758        llvm_unreachable("Unknown shift opcode.");
10759      }
10760
10761      if (Subtarget->hasAVX2() && VT == MVT::v32i8) {
10762        if (Op.getOpcode() == ISD::SHL) {
10763          // Make a large shift.
10764          SDValue SHL = DAG.getNode(X86ISD::VSHLI, dl, MVT::v16i16, R,
10765                                    DAG.getConstant(ShiftAmt, MVT::i32));
10766          SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
10767          // Zero out the rightmost bits.
10768          SmallVector<SDValue, 32> V(32,
10769                                     DAG.getConstant(uint8_t(-1U << ShiftAmt),
10770                                                     MVT::i8));
10771          return DAG.getNode(ISD::AND, dl, VT, SHL,
10772                             DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32));
10773        }
10774        if (Op.getOpcode() == ISD::SRL) {
10775          // Make a large shift.
10776          SDValue SRL = DAG.getNode(X86ISD::VSRLI, dl, MVT::v16i16, R,
10777                                    DAG.getConstant(ShiftAmt, MVT::i32));
10778          SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
10779          // Zero out the leftmost bits.
10780          SmallVector<SDValue, 32> V(32,
10781                                     DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
10782                                                     MVT::i8));
10783          return DAG.getNode(ISD::AND, dl, VT, SRL,
10784                             DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32));
10785        }
10786        if (Op.getOpcode() == ISD::SRA) {
10787          if (ShiftAmt == 7) {
10788            // R s>> 7  ===  R s< 0
10789            SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
10790            return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
10791          }
10792
10793          // R s>> a === ((R u>> a) ^ m) - m
10794          SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
10795          SmallVector<SDValue, 32> V(32, DAG.getConstant(128 >> ShiftAmt,
10796                                                         MVT::i8));
10797          SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32);
10798          Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
10799          Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
10800          return Res;
10801        }
10802        llvm_unreachable("Unknown shift opcode.");
10803      }
10804    }
10805  }
10806
10807  // Lower SHL with variable shift amount.
10808  if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
10809    Op = DAG.getNode(X86ISD::VSHLI, dl, VT, Op.getOperand(1),
10810                     DAG.getConstant(23, MVT::i32));
10811
10812    const uint32_t CV[] = { 0x3f800000U, 0x3f800000U, 0x3f800000U, 0x3f800000U};
10813    Constant *C = ConstantDataVector::get(*Context, CV);
10814    SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
10815    SDValue Addend = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
10816                                 MachinePointerInfo::getConstantPool(),
10817                                 false, false, false, 16);
10818
10819    Op = DAG.getNode(ISD::ADD, dl, VT, Op, Addend);
10820    Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, Op);
10821    Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
10822    return DAG.getNode(ISD::MUL, dl, VT, Op, R);
10823  }
10824  if (VT == MVT::v16i8 && Op->getOpcode() == ISD::SHL) {
10825    assert(Subtarget->hasSSE2() && "Need SSE2 for pslli/pcmpeq.");
10826
10827    // a = a << 5;
10828    Op = DAG.getNode(X86ISD::VSHLI, dl, MVT::v8i16, Op.getOperand(1),
10829                     DAG.getConstant(5, MVT::i32));
10830    Op = DAG.getNode(ISD::BITCAST, dl, VT, Op);
10831
10832    // Turn 'a' into a mask suitable for VSELECT
10833    SDValue VSelM = DAG.getConstant(0x80, VT);
10834    SDValue OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
10835    OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
10836
10837    SDValue CM1 = DAG.getConstant(0x0f, VT);
10838    SDValue CM2 = DAG.getConstant(0x3f, VT);
10839
10840    // r = VSELECT(r, psllw(r & (char16)15, 4), a);
10841    SDValue M = DAG.getNode(ISD::AND, dl, VT, R, CM1);
10842    M = getTargetVShiftNode(X86ISD::VSHLI, dl, MVT::v8i16, M,
10843                            DAG.getConstant(4, MVT::i32), DAG);
10844    M = DAG.getNode(ISD::BITCAST, dl, VT, M);
10845    R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
10846
10847    // a += a
10848    Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
10849    OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
10850    OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
10851
10852    // r = VSELECT(r, psllw(r & (char16)63, 2), a);
10853    M = DAG.getNode(ISD::AND, dl, VT, R, CM2);
10854    M = getTargetVShiftNode(X86ISD::VSHLI, dl, MVT::v8i16, M,
10855                            DAG.getConstant(2, MVT::i32), DAG);
10856    M = DAG.getNode(ISD::BITCAST, dl, VT, M);
10857    R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
10858
10859    // a += a
10860    Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
10861    OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
10862    OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
10863
10864    // return VSELECT(r, r+r, a);
10865    R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel,
10866                    DAG.getNode(ISD::ADD, dl, VT, R, R), R);
10867    return R;
10868  }
10869
10870  // Decompose 256-bit shifts into smaller 128-bit shifts.
10871  if (VT.is256BitVector()) {
10872    unsigned NumElems = VT.getVectorNumElements();
10873    MVT EltVT = VT.getVectorElementType().getSimpleVT();
10874    EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
10875
10876    // Extract the two vectors
10877    SDValue V1 = Extract128BitVector(R, 0, DAG, dl);
10878    SDValue V2 = Extract128BitVector(R, NumElems/2, DAG, dl);
10879
10880    // Recreate the shift amount vectors
10881    SDValue Amt1, Amt2;
10882    if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
10883      // Constant shift amount
10884      SmallVector<SDValue, 4> Amt1Csts;
10885      SmallVector<SDValue, 4> Amt2Csts;
10886      for (unsigned i = 0; i != NumElems/2; ++i)
10887        Amt1Csts.push_back(Amt->getOperand(i));
10888      for (unsigned i = NumElems/2; i != NumElems; ++i)
10889        Amt2Csts.push_back(Amt->getOperand(i));
10890
10891      Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT,
10892                                 &Amt1Csts[0], NumElems/2);
10893      Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT,
10894                                 &Amt2Csts[0], NumElems/2);
10895    } else {
10896      // Variable shift amount
10897      Amt1 = Extract128BitVector(Amt, 0, DAG, dl);
10898      Amt2 = Extract128BitVector(Amt, NumElems/2, DAG, dl);
10899    }
10900
10901    // Issue new vector shifts for the smaller types
10902    V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
10903    V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
10904
10905    // Concatenate the result back
10906    return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
10907  }
10908
10909  return SDValue();
10910}
10911
10912SDValue X86TargetLowering::LowerXALUO(SDValue Op, SelectionDAG &DAG) const {
10913  // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
10914  // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
10915  // looks for this combo and may remove the "setcc" instruction if the "setcc"
10916  // has only one use.
10917  SDNode *N = Op.getNode();
10918  SDValue LHS = N->getOperand(0);
10919  SDValue RHS = N->getOperand(1);
10920  unsigned BaseOp = 0;
10921  unsigned Cond = 0;
10922  DebugLoc DL = Op.getDebugLoc();
10923  switch (Op.getOpcode()) {
10924  default: llvm_unreachable("Unknown ovf instruction!");
10925  case ISD::SADDO:
10926    // A subtract of one will be selected as a INC. Note that INC doesn't
10927    // set CF, so we can't do this for UADDO.
10928    if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
10929      if (C->isOne()) {
10930        BaseOp = X86ISD::INC;
10931        Cond = X86::COND_O;
10932        break;
10933      }
10934    BaseOp = X86ISD::ADD;
10935    Cond = X86::COND_O;
10936    break;
10937  case ISD::UADDO:
10938    BaseOp = X86ISD::ADD;
10939    Cond = X86::COND_B;
10940    break;
10941  case ISD::SSUBO:
10942    // A subtract of one will be selected as a DEC. Note that DEC doesn't
10943    // set CF, so we can't do this for USUBO.
10944    if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
10945      if (C->isOne()) {
10946        BaseOp = X86ISD::DEC;
10947        Cond = X86::COND_O;
10948        break;
10949      }
10950    BaseOp = X86ISD::SUB;
10951    Cond = X86::COND_O;
10952    break;
10953  case ISD::USUBO:
10954    BaseOp = X86ISD::SUB;
10955    Cond = X86::COND_B;
10956    break;
10957  case ISD::SMULO:
10958    BaseOp = X86ISD::SMUL;
10959    Cond = X86::COND_O;
10960    break;
10961  case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
10962    SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
10963                                 MVT::i32);
10964    SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
10965
10966    SDValue SetCC =
10967      DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
10968                  DAG.getConstant(X86::COND_O, MVT::i32),
10969                  SDValue(Sum.getNode(), 2));
10970
10971    return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
10972  }
10973  }
10974
10975  // Also sets EFLAGS.
10976  SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
10977  SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
10978
10979  SDValue SetCC =
10980    DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
10981                DAG.getConstant(Cond, MVT::i32),
10982                SDValue(Sum.getNode(), 1));
10983
10984  return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
10985}
10986
10987SDValue X86TargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op,
10988                                                  SelectionDAG &DAG) const {
10989  DebugLoc dl = Op.getDebugLoc();
10990  EVT ExtraVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
10991  EVT VT = Op.getValueType();
10992
10993  if (!Subtarget->hasSSE2() || !VT.isVector())
10994    return SDValue();
10995
10996  unsigned BitsDiff = VT.getScalarType().getSizeInBits() -
10997                      ExtraVT.getScalarType().getSizeInBits();
10998  SDValue ShAmt = DAG.getConstant(BitsDiff, MVT::i32);
10999
11000  switch (VT.getSimpleVT().SimpleTy) {
11001    default: return SDValue();
11002    case MVT::v8i32:
11003    case MVT::v16i16:
11004      if (!Subtarget->hasAVX())
11005        return SDValue();
11006      if (!Subtarget->hasAVX2()) {
11007        // needs to be split
11008        unsigned NumElems = VT.getVectorNumElements();
11009
11010        // Extract the LHS vectors
11011        SDValue LHS = Op.getOperand(0);
11012        SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
11013        SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
11014
11015        MVT EltVT = VT.getVectorElementType().getSimpleVT();
11016        EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
11017
11018        EVT ExtraEltVT = ExtraVT.getVectorElementType();
11019        unsigned ExtraNumElems = ExtraVT.getVectorNumElements();
11020        ExtraVT = EVT::getVectorVT(*DAG.getContext(), ExtraEltVT,
11021                                   ExtraNumElems/2);
11022        SDValue Extra = DAG.getValueType(ExtraVT);
11023
11024        LHS1 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, Extra);
11025        LHS2 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, Extra);
11026
11027        return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, LHS1, LHS2);
11028      }
11029      // fall through
11030    case MVT::v4i32:
11031    case MVT::v8i16: {
11032      SDValue Tmp1 = getTargetVShiftNode(X86ISD::VSHLI, dl, VT,
11033                                         Op.getOperand(0), ShAmt, DAG);
11034      return getTargetVShiftNode(X86ISD::VSRAI, dl, VT, Tmp1, ShAmt, DAG);
11035    }
11036  }
11037}
11038
11039
11040SDValue X86TargetLowering::LowerMEMBARRIER(SDValue Op, SelectionDAG &DAG) const{
11041  DebugLoc dl = Op.getDebugLoc();
11042
11043  // Go ahead and emit the fence on x86-64 even if we asked for no-sse2.
11044  // There isn't any reason to disable it if the target processor supports it.
11045  if (!Subtarget->hasSSE2() && !Subtarget->is64Bit()) {
11046    SDValue Chain = Op.getOperand(0);
11047    SDValue Zero = DAG.getConstant(0, MVT::i32);
11048    SDValue Ops[] = {
11049      DAG.getRegister(X86::ESP, MVT::i32), // Base
11050      DAG.getTargetConstant(1, MVT::i8),   // Scale
11051      DAG.getRegister(0, MVT::i32),        // Index
11052      DAG.getTargetConstant(0, MVT::i32),  // Disp
11053      DAG.getRegister(0, MVT::i32),        // Segment.
11054      Zero,
11055      Chain
11056    };
11057    SDNode *Res =
11058      DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops,
11059                          array_lengthof(Ops));
11060    return SDValue(Res, 0);
11061  }
11062
11063  unsigned isDev = cast<ConstantSDNode>(Op.getOperand(5))->getZExtValue();
11064  if (!isDev)
11065    return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
11066
11067  unsigned Op1 = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
11068  unsigned Op2 = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
11069  unsigned Op3 = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue();
11070  unsigned Op4 = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
11071
11072  // def : Pat<(membarrier (i8 0), (i8 0), (i8 0), (i8 1), (i8 1)), (SFENCE)>;
11073  if (!Op1 && !Op2 && !Op3 && Op4)
11074    return DAG.getNode(X86ISD::SFENCE, dl, MVT::Other, Op.getOperand(0));
11075
11076  // def : Pat<(membarrier (i8 1), (i8 0), (i8 0), (i8 0), (i8 1)), (LFENCE)>;
11077  if (Op1 && !Op2 && !Op3 && !Op4)
11078    return DAG.getNode(X86ISD::LFENCE, dl, MVT::Other, Op.getOperand(0));
11079
11080  // def : Pat<(membarrier (i8 imm), (i8 imm), (i8 imm), (i8 imm), (i8 1)),
11081  //           (MFENCE)>;
11082  return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
11083}
11084
11085SDValue X86TargetLowering::LowerATOMIC_FENCE(SDValue Op,
11086                                             SelectionDAG &DAG) const {
11087  DebugLoc dl = Op.getDebugLoc();
11088  AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
11089    cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
11090  SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
11091    cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
11092
11093  // The only fence that needs an instruction is a sequentially-consistent
11094  // cross-thread fence.
11095  if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
11096    // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
11097    // no-sse2). There isn't any reason to disable it if the target processor
11098    // supports it.
11099    if (Subtarget->hasSSE2() || Subtarget->is64Bit())
11100      return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
11101
11102    SDValue Chain = Op.getOperand(0);
11103    SDValue Zero = DAG.getConstant(0, MVT::i32);
11104    SDValue Ops[] = {
11105      DAG.getRegister(X86::ESP, MVT::i32), // Base
11106      DAG.getTargetConstant(1, MVT::i8),   // Scale
11107      DAG.getRegister(0, MVT::i32),        // Index
11108      DAG.getTargetConstant(0, MVT::i32),  // Disp
11109      DAG.getRegister(0, MVT::i32),        // Segment.
11110      Zero,
11111      Chain
11112    };
11113    SDNode *Res =
11114      DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops,
11115                         array_lengthof(Ops));
11116    return SDValue(Res, 0);
11117  }
11118
11119  // MEMBARRIER is a compiler barrier; it codegens to a no-op.
11120  return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
11121}
11122
11123
11124SDValue X86TargetLowering::LowerCMP_SWAP(SDValue Op, SelectionDAG &DAG) const {
11125  EVT T = Op.getValueType();
11126  DebugLoc DL = Op.getDebugLoc();
11127  unsigned Reg = 0;
11128  unsigned size = 0;
11129  switch(T.getSimpleVT().SimpleTy) {
11130  default: llvm_unreachable("Invalid value type!");
11131  case MVT::i8:  Reg = X86::AL;  size = 1; break;
11132  case MVT::i16: Reg = X86::AX;  size = 2; break;
11133  case MVT::i32: Reg = X86::EAX; size = 4; break;
11134  case MVT::i64:
11135    assert(Subtarget->is64Bit() && "Node not type legal!");
11136    Reg = X86::RAX; size = 8;
11137    break;
11138  }
11139  SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
11140                                    Op.getOperand(2), SDValue());
11141  SDValue Ops[] = { cpIn.getValue(0),
11142                    Op.getOperand(1),
11143                    Op.getOperand(3),
11144                    DAG.getTargetConstant(size, MVT::i8),
11145                    cpIn.getValue(1) };
11146  SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
11147  MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
11148  SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
11149                                           Ops, 5, T, MMO);
11150  SDValue cpOut =
11151    DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
11152  return cpOut;
11153}
11154
11155SDValue X86TargetLowering::LowerREADCYCLECOUNTER(SDValue Op,
11156                                                 SelectionDAG &DAG) const {
11157  assert(Subtarget->is64Bit() && "Result not type legalized?");
11158  SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
11159  SDValue TheChain = Op.getOperand(0);
11160  DebugLoc dl = Op.getDebugLoc();
11161  SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
11162  SDValue rax = DAG.getCopyFromReg(rd, dl, X86::RAX, MVT::i64, rd.getValue(1));
11163  SDValue rdx = DAG.getCopyFromReg(rax.getValue(1), dl, X86::RDX, MVT::i64,
11164                                   rax.getValue(2));
11165  SDValue Tmp = DAG.getNode(ISD::SHL, dl, MVT::i64, rdx,
11166                            DAG.getConstant(32, MVT::i8));
11167  SDValue Ops[] = {
11168    DAG.getNode(ISD::OR, dl, MVT::i64, rax, Tmp),
11169    rdx.getValue(1)
11170  };
11171  return DAG.getMergeValues(Ops, 2, dl);
11172}
11173
11174SDValue X86TargetLowering::LowerBITCAST(SDValue Op,
11175                                            SelectionDAG &DAG) const {
11176  EVT SrcVT = Op.getOperand(0).getValueType();
11177  EVT DstVT = Op.getValueType();
11178  assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
11179         Subtarget->hasMMX() && "Unexpected custom BITCAST");
11180  assert((DstVT == MVT::i64 ||
11181          (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
11182         "Unexpected custom BITCAST");
11183  // i64 <=> MMX conversions are Legal.
11184  if (SrcVT==MVT::i64 && DstVT.isVector())
11185    return Op;
11186  if (DstVT==MVT::i64 && SrcVT.isVector())
11187    return Op;
11188  // MMX <=> MMX conversions are Legal.
11189  if (SrcVT.isVector() && DstVT.isVector())
11190    return Op;
11191  // All other conversions need to be expanded.
11192  return SDValue();
11193}
11194
11195SDValue X86TargetLowering::LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) const {
11196  SDNode *Node = Op.getNode();
11197  DebugLoc dl = Node->getDebugLoc();
11198  EVT T = Node->getValueType(0);
11199  SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
11200                              DAG.getConstant(0, T), Node->getOperand(2));
11201  return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
11202                       cast<AtomicSDNode>(Node)->getMemoryVT(),
11203                       Node->getOperand(0),
11204                       Node->getOperand(1), negOp,
11205                       cast<AtomicSDNode>(Node)->getSrcValue(),
11206                       cast<AtomicSDNode>(Node)->getAlignment(),
11207                       cast<AtomicSDNode>(Node)->getOrdering(),
11208                       cast<AtomicSDNode>(Node)->getSynchScope());
11209}
11210
11211static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
11212  SDNode *Node = Op.getNode();
11213  DebugLoc dl = Node->getDebugLoc();
11214  EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
11215
11216  // Convert seq_cst store -> xchg
11217  // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
11218  // FIXME: On 32-bit, store -> fist or movq would be more efficient
11219  //        (The only way to get a 16-byte store is cmpxchg16b)
11220  // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
11221  if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
11222      !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
11223    SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
11224                                 cast<AtomicSDNode>(Node)->getMemoryVT(),
11225                                 Node->getOperand(0),
11226                                 Node->getOperand(1), Node->getOperand(2),
11227                                 cast<AtomicSDNode>(Node)->getMemOperand(),
11228                                 cast<AtomicSDNode>(Node)->getOrdering(),
11229                                 cast<AtomicSDNode>(Node)->getSynchScope());
11230    return Swap.getValue(1);
11231  }
11232  // Other atomic stores have a simple pattern.
11233  return Op;
11234}
11235
11236static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
11237  EVT VT = Op.getNode()->getValueType(0);
11238
11239  // Let legalize expand this if it isn't a legal type yet.
11240  if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
11241    return SDValue();
11242
11243  SDVTList VTs = DAG.getVTList(VT, MVT::i32);
11244
11245  unsigned Opc;
11246  bool ExtraOp = false;
11247  switch (Op.getOpcode()) {
11248  default: llvm_unreachable("Invalid code");
11249  case ISD::ADDC: Opc = X86ISD::ADD; break;
11250  case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
11251  case ISD::SUBC: Opc = X86ISD::SUB; break;
11252  case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
11253  }
11254
11255  if (!ExtraOp)
11256    return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
11257                       Op.getOperand(1));
11258  return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
11259                     Op.getOperand(1), Op.getOperand(2));
11260}
11261
11262/// LowerOperation - Provide custom lowering hooks for some operations.
11263///
11264SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
11265  switch (Op.getOpcode()) {
11266  default: llvm_unreachable("Should not custom lower this!");
11267  case ISD::SIGN_EXTEND_INREG:  return LowerSIGN_EXTEND_INREG(Op,DAG);
11268  case ISD::MEMBARRIER:         return LowerMEMBARRIER(Op,DAG);
11269  case ISD::ATOMIC_FENCE:       return LowerATOMIC_FENCE(Op,DAG);
11270  case ISD::ATOMIC_CMP_SWAP:    return LowerCMP_SWAP(Op,DAG);
11271  case ISD::ATOMIC_LOAD_SUB:    return LowerLOAD_SUB(Op,DAG);
11272  case ISD::ATOMIC_STORE:       return LowerATOMIC_STORE(Op,DAG);
11273  case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
11274  case ISD::CONCAT_VECTORS:     return LowerCONCAT_VECTORS(Op, DAG);
11275  case ISD::VECTOR_SHUFFLE:     return LowerVECTOR_SHUFFLE(Op, DAG);
11276  case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
11277  case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
11278  case ISD::EXTRACT_SUBVECTOR:  return LowerEXTRACT_SUBVECTOR(Op, DAG);
11279  case ISD::INSERT_SUBVECTOR:   return LowerINSERT_SUBVECTOR(Op, DAG);
11280  case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
11281  case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
11282  case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
11283  case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
11284  case ISD::ExternalSymbol:     return LowerExternalSymbol(Op, DAG);
11285  case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
11286  case ISD::SHL_PARTS:
11287  case ISD::SRA_PARTS:
11288  case ISD::SRL_PARTS:          return LowerShiftParts(Op, DAG);
11289  case ISD::SINT_TO_FP:         return LowerSINT_TO_FP(Op, DAG);
11290  case ISD::UINT_TO_FP:         return LowerUINT_TO_FP(Op, DAG);
11291  case ISD::FP_TO_SINT:         return LowerFP_TO_SINT(Op, DAG);
11292  case ISD::FP_TO_UINT:         return LowerFP_TO_UINT(Op, DAG);
11293  case ISD::FABS:               return LowerFABS(Op, DAG);
11294  case ISD::FNEG:               return LowerFNEG(Op, DAG);
11295  case ISD::FCOPYSIGN:          return LowerFCOPYSIGN(Op, DAG);
11296  case ISD::FGETSIGN:           return LowerFGETSIGN(Op, DAG);
11297  case ISD::SETCC:              return LowerSETCC(Op, DAG);
11298  case ISD::SELECT:             return LowerSELECT(Op, DAG);
11299  case ISD::BRCOND:             return LowerBRCOND(Op, DAG);
11300  case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
11301  case ISD::VASTART:            return LowerVASTART(Op, DAG);
11302  case ISD::VAARG:              return LowerVAARG(Op, DAG);
11303  case ISD::VACOPY:             return LowerVACOPY(Op, DAG);
11304  case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
11305  case ISD::INTRINSIC_W_CHAIN:  return LowerINTRINSIC_W_CHAIN(Op, DAG);
11306  case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
11307  case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
11308  case ISD::FRAME_TO_ARGS_OFFSET:
11309                                return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
11310  case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
11311  case ISD::EH_RETURN:          return LowerEH_RETURN(Op, DAG);
11312  case ISD::INIT_TRAMPOLINE:    return LowerINIT_TRAMPOLINE(Op, DAG);
11313  case ISD::ADJUST_TRAMPOLINE:  return LowerADJUST_TRAMPOLINE(Op, DAG);
11314  case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
11315  case ISD::CTLZ:               return LowerCTLZ(Op, DAG);
11316  case ISD::CTLZ_ZERO_UNDEF:    return LowerCTLZ_ZERO_UNDEF(Op, DAG);
11317  case ISD::CTTZ:               return LowerCTTZ(Op, DAG);
11318  case ISD::MUL:                return LowerMUL(Op, DAG);
11319  case ISD::SRA:
11320  case ISD::SRL:
11321  case ISD::SHL:                return LowerShift(Op, DAG);
11322  case ISD::SADDO:
11323  case ISD::UADDO:
11324  case ISD::SSUBO:
11325  case ISD::USUBO:
11326  case ISD::SMULO:
11327  case ISD::UMULO:              return LowerXALUO(Op, DAG);
11328  case ISD::READCYCLECOUNTER:   return LowerREADCYCLECOUNTER(Op, DAG);
11329  case ISD::BITCAST:            return LowerBITCAST(Op, DAG);
11330  case ISD::ADDC:
11331  case ISD::ADDE:
11332  case ISD::SUBC:
11333  case ISD::SUBE:               return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
11334  case ISD::ADD:                return LowerADD(Op, DAG);
11335  case ISD::SUB:                return LowerSUB(Op, DAG);
11336  }
11337}
11338
11339static void ReplaceATOMIC_LOAD(SDNode *Node,
11340                                  SmallVectorImpl<SDValue> &Results,
11341                                  SelectionDAG &DAG) {
11342  DebugLoc dl = Node->getDebugLoc();
11343  EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
11344
11345  // Convert wide load -> cmpxchg8b/cmpxchg16b
11346  // FIXME: On 32-bit, load -> fild or movq would be more efficient
11347  //        (The only way to get a 16-byte load is cmpxchg16b)
11348  // FIXME: 16-byte ATOMIC_CMP_SWAP isn't actually hooked up at the moment.
11349  SDValue Zero = DAG.getConstant(0, VT);
11350  SDValue Swap = DAG.getAtomic(ISD::ATOMIC_CMP_SWAP, dl, VT,
11351                               Node->getOperand(0),
11352                               Node->getOperand(1), Zero, Zero,
11353                               cast<AtomicSDNode>(Node)->getMemOperand(),
11354                               cast<AtomicSDNode>(Node)->getOrdering(),
11355                               cast<AtomicSDNode>(Node)->getSynchScope());
11356  Results.push_back(Swap.getValue(0));
11357  Results.push_back(Swap.getValue(1));
11358}
11359
11360static void
11361ReplaceATOMIC_BINARY_64(SDNode *Node, SmallVectorImpl<SDValue>&Results,
11362                        SelectionDAG &DAG, unsigned NewOp) {
11363  DebugLoc dl = Node->getDebugLoc();
11364  assert (Node->getValueType(0) == MVT::i64 &&
11365          "Only know how to expand i64 atomics");
11366
11367  SDValue Chain = Node->getOperand(0);
11368  SDValue In1 = Node->getOperand(1);
11369  SDValue In2L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
11370                             Node->getOperand(2), DAG.getIntPtrConstant(0));
11371  SDValue In2H = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
11372                             Node->getOperand(2), DAG.getIntPtrConstant(1));
11373  SDValue Ops[] = { Chain, In1, In2L, In2H };
11374  SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
11375  SDValue Result =
11376    DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops, 4, MVT::i64,
11377                            cast<MemSDNode>(Node)->getMemOperand());
11378  SDValue OpsF[] = { Result.getValue(0), Result.getValue(1)};
11379  Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
11380  Results.push_back(Result.getValue(2));
11381}
11382
11383/// ReplaceNodeResults - Replace a node with an illegal result type
11384/// with a new node built out of custom code.
11385void X86TargetLowering::ReplaceNodeResults(SDNode *N,
11386                                           SmallVectorImpl<SDValue>&Results,
11387                                           SelectionDAG &DAG) const {
11388  DebugLoc dl = N->getDebugLoc();
11389  switch (N->getOpcode()) {
11390  default:
11391    llvm_unreachable("Do not know how to custom type legalize this operation!");
11392  case ISD::SIGN_EXTEND_INREG:
11393  case ISD::ADDC:
11394  case ISD::ADDE:
11395  case ISD::SUBC:
11396  case ISD::SUBE:
11397    // We don't want to expand or promote these.
11398    return;
11399  case ISD::FP_TO_SINT:
11400  case ISD::FP_TO_UINT: {
11401    bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
11402
11403    if (!IsSigned && !isIntegerTypeFTOL(SDValue(N, 0).getValueType()))
11404      return;
11405
11406    std::pair<SDValue,SDValue> Vals =
11407        FP_TO_INTHelper(SDValue(N, 0), DAG, IsSigned, /*IsReplace=*/ true);
11408    SDValue FIST = Vals.first, StackSlot = Vals.second;
11409    if (FIST.getNode() != 0) {
11410      EVT VT = N->getValueType(0);
11411      // Return a load from the stack slot.
11412      if (StackSlot.getNode() != 0)
11413        Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
11414                                      MachinePointerInfo(),
11415                                      false, false, false, 0));
11416      else
11417        Results.push_back(FIST);
11418    }
11419    return;
11420  }
11421  case ISD::READCYCLECOUNTER: {
11422    SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
11423    SDValue TheChain = N->getOperand(0);
11424    SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
11425    SDValue eax = DAG.getCopyFromReg(rd, dl, X86::EAX, MVT::i32,
11426                                     rd.getValue(1));
11427    SDValue edx = DAG.getCopyFromReg(eax.getValue(1), dl, X86::EDX, MVT::i32,
11428                                     eax.getValue(2));
11429    // Use a buildpair to merge the two 32-bit values into a 64-bit one.
11430    SDValue Ops[] = { eax, edx };
11431    Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Ops, 2));
11432    Results.push_back(edx.getValue(1));
11433    return;
11434  }
11435  case ISD::ATOMIC_CMP_SWAP: {
11436    EVT T = N->getValueType(0);
11437    assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
11438    bool Regs64bit = T == MVT::i128;
11439    EVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
11440    SDValue cpInL, cpInH;
11441    cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
11442                        DAG.getConstant(0, HalfT));
11443    cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
11444                        DAG.getConstant(1, HalfT));
11445    cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
11446                             Regs64bit ? X86::RAX : X86::EAX,
11447                             cpInL, SDValue());
11448    cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
11449                             Regs64bit ? X86::RDX : X86::EDX,
11450                             cpInH, cpInL.getValue(1));
11451    SDValue swapInL, swapInH;
11452    swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
11453                          DAG.getConstant(0, HalfT));
11454    swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
11455                          DAG.getConstant(1, HalfT));
11456    swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
11457                               Regs64bit ? X86::RBX : X86::EBX,
11458                               swapInL, cpInH.getValue(1));
11459    swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
11460                               Regs64bit ? X86::RCX : X86::ECX,
11461                               swapInH, swapInL.getValue(1));
11462    SDValue Ops[] = { swapInH.getValue(0),
11463                      N->getOperand(1),
11464                      swapInH.getValue(1) };
11465    SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
11466    MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
11467    unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
11468                                  X86ISD::LCMPXCHG8_DAG;
11469    SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys,
11470                                             Ops, 3, T, MMO);
11471    SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
11472                                        Regs64bit ? X86::RAX : X86::EAX,
11473                                        HalfT, Result.getValue(1));
11474    SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
11475                                        Regs64bit ? X86::RDX : X86::EDX,
11476                                        HalfT, cpOutL.getValue(2));
11477    SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
11478    Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF, 2));
11479    Results.push_back(cpOutH.getValue(1));
11480    return;
11481  }
11482  case ISD::ATOMIC_LOAD_ADD:
11483  case ISD::ATOMIC_LOAD_AND:
11484  case ISD::ATOMIC_LOAD_NAND:
11485  case ISD::ATOMIC_LOAD_OR:
11486  case ISD::ATOMIC_LOAD_SUB:
11487  case ISD::ATOMIC_LOAD_XOR:
11488  case ISD::ATOMIC_SWAP: {
11489    unsigned Opc;
11490    switch (N->getOpcode()) {
11491    default: llvm_unreachable("Unexpected opcode");
11492    case ISD::ATOMIC_LOAD_ADD:
11493      Opc = X86ISD::ATOMADD64_DAG;
11494      break;
11495    case ISD::ATOMIC_LOAD_AND:
11496      Opc = X86ISD::ATOMAND64_DAG;
11497      break;
11498    case ISD::ATOMIC_LOAD_NAND:
11499      Opc = X86ISD::ATOMNAND64_DAG;
11500      break;
11501    case ISD::ATOMIC_LOAD_OR:
11502      Opc = X86ISD::ATOMOR64_DAG;
11503      break;
11504    case ISD::ATOMIC_LOAD_SUB:
11505      Opc = X86ISD::ATOMSUB64_DAG;
11506      break;
11507    case ISD::ATOMIC_LOAD_XOR:
11508      Opc = X86ISD::ATOMXOR64_DAG;
11509      break;
11510    case ISD::ATOMIC_SWAP:
11511      Opc = X86ISD::ATOMSWAP64_DAG;
11512      break;
11513    }
11514    ReplaceATOMIC_BINARY_64(N, Results, DAG, Opc);
11515    return;
11516  }
11517  case ISD::ATOMIC_LOAD:
11518    ReplaceATOMIC_LOAD(N, Results, DAG);
11519  }
11520}
11521
11522const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
11523  switch (Opcode) {
11524  default: return NULL;
11525  case X86ISD::BSF:                return "X86ISD::BSF";
11526  case X86ISD::BSR:                return "X86ISD::BSR";
11527  case X86ISD::SHLD:               return "X86ISD::SHLD";
11528  case X86ISD::SHRD:               return "X86ISD::SHRD";
11529  case X86ISD::FAND:               return "X86ISD::FAND";
11530  case X86ISD::FOR:                return "X86ISD::FOR";
11531  case X86ISD::FXOR:               return "X86ISD::FXOR";
11532  case X86ISD::FSRL:               return "X86ISD::FSRL";
11533  case X86ISD::FILD:               return "X86ISD::FILD";
11534  case X86ISD::FILD_FLAG:          return "X86ISD::FILD_FLAG";
11535  case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
11536  case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
11537  case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
11538  case X86ISD::FLD:                return "X86ISD::FLD";
11539  case X86ISD::FST:                return "X86ISD::FST";
11540  case X86ISD::CALL:               return "X86ISD::CALL";
11541  case X86ISD::RDTSC_DAG:          return "X86ISD::RDTSC_DAG";
11542  case X86ISD::BT:                 return "X86ISD::BT";
11543  case X86ISD::CMP:                return "X86ISD::CMP";
11544  case X86ISD::COMI:               return "X86ISD::COMI";
11545  case X86ISD::UCOMI:              return "X86ISD::UCOMI";
11546  case X86ISD::SETCC:              return "X86ISD::SETCC";
11547  case X86ISD::SETCC_CARRY:        return "X86ISD::SETCC_CARRY";
11548  case X86ISD::FSETCCsd:           return "X86ISD::FSETCCsd";
11549  case X86ISD::FSETCCss:           return "X86ISD::FSETCCss";
11550  case X86ISD::CMOV:               return "X86ISD::CMOV";
11551  case X86ISD::BRCOND:             return "X86ISD::BRCOND";
11552  case X86ISD::RET_FLAG:           return "X86ISD::RET_FLAG";
11553  case X86ISD::REP_STOS:           return "X86ISD::REP_STOS";
11554  case X86ISD::REP_MOVS:           return "X86ISD::REP_MOVS";
11555  case X86ISD::GlobalBaseReg:      return "X86ISD::GlobalBaseReg";
11556  case X86ISD::Wrapper:            return "X86ISD::Wrapper";
11557  case X86ISD::WrapperRIP:         return "X86ISD::WrapperRIP";
11558  case X86ISD::PEXTRB:             return "X86ISD::PEXTRB";
11559  case X86ISD::PEXTRW:             return "X86ISD::PEXTRW";
11560  case X86ISD::INSERTPS:           return "X86ISD::INSERTPS";
11561  case X86ISD::PINSRB:             return "X86ISD::PINSRB";
11562  case X86ISD::PINSRW:             return "X86ISD::PINSRW";
11563  case X86ISD::PSHUFB:             return "X86ISD::PSHUFB";
11564  case X86ISD::ANDNP:              return "X86ISD::ANDNP";
11565  case X86ISD::PSIGN:              return "X86ISD::PSIGN";
11566  case X86ISD::BLENDV:             return "X86ISD::BLENDV";
11567  case X86ISD::BLENDPW:            return "X86ISD::BLENDPW";
11568  case X86ISD::BLENDPS:            return "X86ISD::BLENDPS";
11569  case X86ISD::BLENDPD:            return "X86ISD::BLENDPD";
11570  case X86ISD::HADD:               return "X86ISD::HADD";
11571  case X86ISD::HSUB:               return "X86ISD::HSUB";
11572  case X86ISD::FHADD:              return "X86ISD::FHADD";
11573  case X86ISD::FHSUB:              return "X86ISD::FHSUB";
11574  case X86ISD::FMAX:               return "X86ISD::FMAX";
11575  case X86ISD::FMIN:               return "X86ISD::FMIN";
11576  case X86ISD::FMAXC:              return "X86ISD::FMAXC";
11577  case X86ISD::FMINC:              return "X86ISD::FMINC";
11578  case X86ISD::FRSQRT:             return "X86ISD::FRSQRT";
11579  case X86ISD::FRCP:               return "X86ISD::FRCP";
11580  case X86ISD::TLSADDR:            return "X86ISD::TLSADDR";
11581  case X86ISD::TLSBASEADDR:        return "X86ISD::TLSBASEADDR";
11582  case X86ISD::TLSCALL:            return "X86ISD::TLSCALL";
11583  case X86ISD::EH_RETURN:          return "X86ISD::EH_RETURN";
11584  case X86ISD::TC_RETURN:          return "X86ISD::TC_RETURN";
11585  case X86ISD::FNSTCW16m:          return "X86ISD::FNSTCW16m";
11586  case X86ISD::FNSTSW16r:          return "X86ISD::FNSTSW16r";
11587  case X86ISD::LCMPXCHG_DAG:       return "X86ISD::LCMPXCHG_DAG";
11588  case X86ISD::LCMPXCHG8_DAG:      return "X86ISD::LCMPXCHG8_DAG";
11589  case X86ISD::ATOMADD64_DAG:      return "X86ISD::ATOMADD64_DAG";
11590  case X86ISD::ATOMSUB64_DAG:      return "X86ISD::ATOMSUB64_DAG";
11591  case X86ISD::ATOMOR64_DAG:       return "X86ISD::ATOMOR64_DAG";
11592  case X86ISD::ATOMXOR64_DAG:      return "X86ISD::ATOMXOR64_DAG";
11593  case X86ISD::ATOMAND64_DAG:      return "X86ISD::ATOMAND64_DAG";
11594  case X86ISD::ATOMNAND64_DAG:     return "X86ISD::ATOMNAND64_DAG";
11595  case X86ISD::VZEXT_MOVL:         return "X86ISD::VZEXT_MOVL";
11596  case X86ISD::VSEXT_MOVL:         return "X86ISD::VSEXT_MOVL";
11597  case X86ISD::VZEXT_LOAD:         return "X86ISD::VZEXT_LOAD";
11598  case X86ISD::VFPEXT:             return "X86ISD::VFPEXT";
11599  case X86ISD::VSHLDQ:             return "X86ISD::VSHLDQ";
11600  case X86ISD::VSRLDQ:             return "X86ISD::VSRLDQ";
11601  case X86ISD::VSHL:               return "X86ISD::VSHL";
11602  case X86ISD::VSRL:               return "X86ISD::VSRL";
11603  case X86ISD::VSRA:               return "X86ISD::VSRA";
11604  case X86ISD::VSHLI:              return "X86ISD::VSHLI";
11605  case X86ISD::VSRLI:              return "X86ISD::VSRLI";
11606  case X86ISD::VSRAI:              return "X86ISD::VSRAI";
11607  case X86ISD::CMPP:               return "X86ISD::CMPP";
11608  case X86ISD::PCMPEQ:             return "X86ISD::PCMPEQ";
11609  case X86ISD::PCMPGT:             return "X86ISD::PCMPGT";
11610  case X86ISD::ADD:                return "X86ISD::ADD";
11611  case X86ISD::SUB:                return "X86ISD::SUB";
11612  case X86ISD::ADC:                return "X86ISD::ADC";
11613  case X86ISD::SBB:                return "X86ISD::SBB";
11614  case X86ISD::SMUL:               return "X86ISD::SMUL";
11615  case X86ISD::UMUL:               return "X86ISD::UMUL";
11616  case X86ISD::INC:                return "X86ISD::INC";
11617  case X86ISD::DEC:                return "X86ISD::DEC";
11618  case X86ISD::OR:                 return "X86ISD::OR";
11619  case X86ISD::XOR:                return "X86ISD::XOR";
11620  case X86ISD::AND:                return "X86ISD::AND";
11621  case X86ISD::ANDN:               return "X86ISD::ANDN";
11622  case X86ISD::BLSI:               return "X86ISD::BLSI";
11623  case X86ISD::BLSMSK:             return "X86ISD::BLSMSK";
11624  case X86ISD::BLSR:               return "X86ISD::BLSR";
11625  case X86ISD::MUL_IMM:            return "X86ISD::MUL_IMM";
11626  case X86ISD::PTEST:              return "X86ISD::PTEST";
11627  case X86ISD::TESTP:              return "X86ISD::TESTP";
11628  case X86ISD::PALIGN:             return "X86ISD::PALIGN";
11629  case X86ISD::PSHUFD:             return "X86ISD::PSHUFD";
11630  case X86ISD::PSHUFHW:            return "X86ISD::PSHUFHW";
11631  case X86ISD::PSHUFLW:            return "X86ISD::PSHUFLW";
11632  case X86ISD::SHUFP:              return "X86ISD::SHUFP";
11633  case X86ISD::MOVLHPS:            return "X86ISD::MOVLHPS";
11634  case X86ISD::MOVLHPD:            return "X86ISD::MOVLHPD";
11635  case X86ISD::MOVHLPS:            return "X86ISD::MOVHLPS";
11636  case X86ISD::MOVLPS:             return "X86ISD::MOVLPS";
11637  case X86ISD::MOVLPD:             return "X86ISD::MOVLPD";
11638  case X86ISD::MOVDDUP:            return "X86ISD::MOVDDUP";
11639  case X86ISD::MOVSHDUP:           return "X86ISD::MOVSHDUP";
11640  case X86ISD::MOVSLDUP:           return "X86ISD::MOVSLDUP";
11641  case X86ISD::MOVSD:              return "X86ISD::MOVSD";
11642  case X86ISD::MOVSS:              return "X86ISD::MOVSS";
11643  case X86ISD::UNPCKL:             return "X86ISD::UNPCKL";
11644  case X86ISD::UNPCKH:             return "X86ISD::UNPCKH";
11645  case X86ISD::VBROADCAST:         return "X86ISD::VBROADCAST";
11646  case X86ISD::VPERMILP:           return "X86ISD::VPERMILP";
11647  case X86ISD::VPERM2X128:         return "X86ISD::VPERM2X128";
11648  case X86ISD::VPERMV:             return "X86ISD::VPERMV";
11649  case X86ISD::VPERMI:             return "X86ISD::VPERMI";
11650  case X86ISD::PMULUDQ:            return "X86ISD::PMULUDQ";
11651  case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
11652  case X86ISD::VAARG_64:           return "X86ISD::VAARG_64";
11653  case X86ISD::WIN_ALLOCA:         return "X86ISD::WIN_ALLOCA";
11654  case X86ISD::MEMBARRIER:         return "X86ISD::MEMBARRIER";
11655  case X86ISD::SEG_ALLOCA:         return "X86ISD::SEG_ALLOCA";
11656  case X86ISD::WIN_FTOL:           return "X86ISD::WIN_FTOL";
11657  case X86ISD::SAHF:               return "X86ISD::SAHF";
11658  case X86ISD::RDRAND:             return "X86ISD::RDRAND";
11659  case X86ISD::FMADD:              return "X86ISD::FMADD";
11660  case X86ISD::FMSUB:              return "X86ISD::FMSUB";
11661  case X86ISD::FNMADD:             return "X86ISD::FNMADD";
11662  case X86ISD::FNMSUB:             return "X86ISD::FNMSUB";
11663  case X86ISD::FMADDSUB:           return "X86ISD::FMADDSUB";
11664  case X86ISD::FMSUBADD:           return "X86ISD::FMSUBADD";
11665  }
11666}
11667
11668// isLegalAddressingMode - Return true if the addressing mode represented
11669// by AM is legal for this target, for a load/store of the specified type.
11670bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
11671                                              Type *Ty) const {
11672  // X86 supports extremely general addressing modes.
11673  CodeModel::Model M = getTargetMachine().getCodeModel();
11674  Reloc::Model R = getTargetMachine().getRelocationModel();
11675
11676  // X86 allows a sign-extended 32-bit immediate field as a displacement.
11677  if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != NULL))
11678    return false;
11679
11680  if (AM.BaseGV) {
11681    unsigned GVFlags =
11682      Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
11683
11684    // If a reference to this global requires an extra load, we can't fold it.
11685    if (isGlobalStubReference(GVFlags))
11686      return false;
11687
11688    // If BaseGV requires a register for the PIC base, we cannot also have a
11689    // BaseReg specified.
11690    if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
11691      return false;
11692
11693    // If lower 4G is not available, then we must use rip-relative addressing.
11694    if ((M != CodeModel::Small || R != Reloc::Static) &&
11695        Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
11696      return false;
11697  }
11698
11699  switch (AM.Scale) {
11700  case 0:
11701  case 1:
11702  case 2:
11703  case 4:
11704  case 8:
11705    // These scales always work.
11706    break;
11707  case 3:
11708  case 5:
11709  case 9:
11710    // These scales are formed with basereg+scalereg.  Only accept if there is
11711    // no basereg yet.
11712    if (AM.HasBaseReg)
11713      return false;
11714    break;
11715  default:  // Other stuff never works.
11716    return false;
11717  }
11718
11719  return true;
11720}
11721
11722
11723bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
11724  if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
11725    return false;
11726  unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
11727  unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
11728  if (NumBits1 <= NumBits2)
11729    return false;
11730  return true;
11731}
11732
11733bool X86TargetLowering::isLegalICmpImmediate(int64_t Imm) const {
11734  return Imm == (int32_t)Imm;
11735}
11736
11737bool X86TargetLowering::isLegalAddImmediate(int64_t Imm) const {
11738  // Can also use sub to handle negated immediates.
11739  return Imm == (int32_t)Imm;
11740}
11741
11742bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
11743  if (!VT1.isInteger() || !VT2.isInteger())
11744    return false;
11745  unsigned NumBits1 = VT1.getSizeInBits();
11746  unsigned NumBits2 = VT2.getSizeInBits();
11747  if (NumBits1 <= NumBits2)
11748    return false;
11749  return true;
11750}
11751
11752bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
11753  // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
11754  return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
11755}
11756
11757bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
11758  // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
11759  return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
11760}
11761
11762bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
11763  // i16 instructions are longer (0x66 prefix) and potentially slower.
11764  return !(VT1 == MVT::i32 && VT2 == MVT::i16);
11765}
11766
11767/// isShuffleMaskLegal - Targets can use this to indicate that they only
11768/// support *some* VECTOR_SHUFFLE operations, those with specific masks.
11769/// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
11770/// are assumed to be legal.
11771bool
11772X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
11773                                      EVT VT) const {
11774  // Very little shuffling can be done for 64-bit vectors right now.
11775  if (VT.getSizeInBits() == 64)
11776    return false;
11777
11778  // FIXME: pshufb, blends, shifts.
11779  return (VT.getVectorNumElements() == 2 ||
11780          ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
11781          isMOVLMask(M, VT) ||
11782          isSHUFPMask(M, VT, Subtarget->hasAVX()) ||
11783          isPSHUFDMask(M, VT) ||
11784          isPSHUFHWMask(M, VT, Subtarget->hasAVX2()) ||
11785          isPSHUFLWMask(M, VT, Subtarget->hasAVX2()) ||
11786          isPALIGNRMask(M, VT, Subtarget) ||
11787          isUNPCKLMask(M, VT, Subtarget->hasAVX2()) ||
11788          isUNPCKHMask(M, VT, Subtarget->hasAVX2()) ||
11789          isUNPCKL_v_undef_Mask(M, VT, Subtarget->hasAVX2()) ||
11790          isUNPCKH_v_undef_Mask(M, VT, Subtarget->hasAVX2()));
11791}
11792
11793bool
11794X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
11795                                          EVT VT) const {
11796  unsigned NumElts = VT.getVectorNumElements();
11797  // FIXME: This collection of masks seems suspect.
11798  if (NumElts == 2)
11799    return true;
11800  if (NumElts == 4 && VT.is128BitVector()) {
11801    return (isMOVLMask(Mask, VT)  ||
11802            isCommutedMOVLMask(Mask, VT, true) ||
11803            isSHUFPMask(Mask, VT, Subtarget->hasAVX()) ||
11804            isSHUFPMask(Mask, VT, Subtarget->hasAVX(), /* Commuted */ true));
11805  }
11806  return false;
11807}
11808
11809//===----------------------------------------------------------------------===//
11810//                           X86 Scheduler Hooks
11811//===----------------------------------------------------------------------===//
11812
11813// private utility function
11814MachineBasicBlock *
11815X86TargetLowering::EmitAtomicBitwiseWithCustomInserter(MachineInstr *bInstr,
11816                                                       MachineBasicBlock *MBB,
11817                                                       unsigned regOpc,
11818                                                       unsigned immOpc,
11819                                                       unsigned LoadOpc,
11820                                                       unsigned CXchgOpc,
11821                                                       unsigned notOpc,
11822                                                       unsigned EAXreg,
11823                                                 const TargetRegisterClass *RC,
11824                                                       bool Invert) const {
11825  // For the atomic bitwise operator, we generate
11826  //   thisMBB:
11827  //   newMBB:
11828  //     ld  t1 = [bitinstr.addr]
11829  //     op  t2 = t1, [bitinstr.val]
11830  //     not t3 = t2  (if Invert)
11831  //     mov EAX = t1
11832  //     lcs dest = [bitinstr.addr], t3  [EAX is implicit]
11833  //     bz  newMBB
11834  //     fallthrough -->nextMBB
11835  const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11836  const BasicBlock *LLVM_BB = MBB->getBasicBlock();
11837  MachineFunction::iterator MBBIter = MBB;
11838  ++MBBIter;
11839
11840  /// First build the CFG
11841  MachineFunction *F = MBB->getParent();
11842  MachineBasicBlock *thisMBB = MBB;
11843  MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
11844  MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
11845  F->insert(MBBIter, newMBB);
11846  F->insert(MBBIter, nextMBB);
11847
11848  // Transfer the remainder of thisMBB and its successor edges to nextMBB.
11849  nextMBB->splice(nextMBB->begin(), thisMBB,
11850                  llvm::next(MachineBasicBlock::iterator(bInstr)),
11851                  thisMBB->end());
11852  nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
11853
11854  // Update thisMBB to fall through to newMBB
11855  thisMBB->addSuccessor(newMBB);
11856
11857  // newMBB jumps to itself and fall through to nextMBB
11858  newMBB->addSuccessor(nextMBB);
11859  newMBB->addSuccessor(newMBB);
11860
11861  // Insert instructions into newMBB based on incoming instruction
11862  assert(bInstr->getNumOperands() < X86::AddrNumOperands + 4 &&
11863         "unexpected number of operands");
11864  DebugLoc dl = bInstr->getDebugLoc();
11865  MachineOperand& destOper = bInstr->getOperand(0);
11866  MachineOperand* argOpers[2 + X86::AddrNumOperands];
11867  int numArgs = bInstr->getNumOperands() - 1;
11868  for (int i=0; i < numArgs; ++i)
11869    argOpers[i] = &bInstr->getOperand(i+1);
11870
11871  // x86 address has 4 operands: base, index, scale, and displacement
11872  int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
11873  int valArgIndx = lastAddrIndx + 1;
11874
11875  unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
11876  MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(LoadOpc), t1);
11877  for (int i=0; i <= lastAddrIndx; ++i)
11878    (*MIB).addOperand(*argOpers[i]);
11879
11880  unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
11881  assert((argOpers[valArgIndx]->isReg() ||
11882          argOpers[valArgIndx]->isImm()) &&
11883         "invalid operand");
11884  if (argOpers[valArgIndx]->isReg())
11885    MIB = BuildMI(newMBB, dl, TII->get(regOpc), t2);
11886  else
11887    MIB = BuildMI(newMBB, dl, TII->get(immOpc), t2);
11888  MIB.addReg(t1);
11889  (*MIB).addOperand(*argOpers[valArgIndx]);
11890
11891  unsigned t3 = F->getRegInfo().createVirtualRegister(RC);
11892  if (Invert) {
11893    MIB = BuildMI(newMBB, dl, TII->get(notOpc), t3).addReg(t2);
11894  }
11895  else
11896    t3 = t2;
11897
11898  MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), EAXreg);
11899  MIB.addReg(t1);
11900
11901  MIB = BuildMI(newMBB, dl, TII->get(CXchgOpc));
11902  for (int i=0; i <= lastAddrIndx; ++i)
11903    (*MIB).addOperand(*argOpers[i]);
11904  MIB.addReg(t3);
11905  assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
11906  (*MIB).setMemRefs(bInstr->memoperands_begin(),
11907                    bInstr->memoperands_end());
11908
11909  MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), destOper.getReg());
11910  MIB.addReg(EAXreg);
11911
11912  // insert branch
11913  BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
11914
11915  bInstr->eraseFromParent();   // The pseudo instruction is gone now.
11916  return nextMBB;
11917}
11918
11919// private utility function:  64 bit atomics on 32 bit host.
11920MachineBasicBlock *
11921X86TargetLowering::EmitAtomicBit6432WithCustomInserter(MachineInstr *bInstr,
11922                                                       MachineBasicBlock *MBB,
11923                                                       unsigned regOpcL,
11924                                                       unsigned regOpcH,
11925                                                       unsigned immOpcL,
11926                                                       unsigned immOpcH,
11927                                                       bool Invert) const {
11928  // For the atomic bitwise operator, we generate
11929  //   thisMBB (instructions are in pairs, except cmpxchg8b)
11930  //     ld t1,t2 = [bitinstr.addr]
11931  //   newMBB:
11932  //     out1, out2 = phi (thisMBB, t1/t2) (newMBB, t3/t4)
11933  //     op  t5, t6 <- out1, out2, [bitinstr.val]
11934  //      (for SWAP, substitute:  mov t5, t6 <- [bitinstr.val])
11935  //     neg t7, t8 < t5, t6  (if Invert)
11936  //     mov ECX, EBX <- t5, t6
11937  //     mov EAX, EDX <- t1, t2
11938  //     cmpxchg8b [bitinstr.addr]  [EAX, EDX, EBX, ECX implicit]
11939  //     mov t3, t4 <- EAX, EDX
11940  //     bz  newMBB
11941  //     result in out1, out2
11942  //     fallthrough -->nextMBB
11943
11944  const TargetRegisterClass *RC = &X86::GR32RegClass;
11945  const unsigned LoadOpc = X86::MOV32rm;
11946  const unsigned NotOpc = X86::NOT32r;
11947  const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11948  const BasicBlock *LLVM_BB = MBB->getBasicBlock();
11949  MachineFunction::iterator MBBIter = MBB;
11950  ++MBBIter;
11951
11952  /// First build the CFG
11953  MachineFunction *F = MBB->getParent();
11954  MachineBasicBlock *thisMBB = MBB;
11955  MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
11956  MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
11957  F->insert(MBBIter, newMBB);
11958  F->insert(MBBIter, nextMBB);
11959
11960  // Transfer the remainder of thisMBB and its successor edges to nextMBB.
11961  nextMBB->splice(nextMBB->begin(), thisMBB,
11962                  llvm::next(MachineBasicBlock::iterator(bInstr)),
11963                  thisMBB->end());
11964  nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
11965
11966  // Update thisMBB to fall through to newMBB
11967  thisMBB->addSuccessor(newMBB);
11968
11969  // newMBB jumps to itself and fall through to nextMBB
11970  newMBB->addSuccessor(nextMBB);
11971  newMBB->addSuccessor(newMBB);
11972
11973  DebugLoc dl = bInstr->getDebugLoc();
11974  // Insert instructions into newMBB based on incoming instruction
11975  // There are 8 "real" operands plus 9 implicit def/uses, ignored here.
11976  assert(bInstr->getNumOperands() < X86::AddrNumOperands + 14 &&
11977         "unexpected number of operands");
11978  MachineOperand& dest1Oper = bInstr->getOperand(0);
11979  MachineOperand& dest2Oper = bInstr->getOperand(1);
11980  MachineOperand* argOpers[2 + X86::AddrNumOperands];
11981  for (int i=0; i < 2 + X86::AddrNumOperands; ++i) {
11982    argOpers[i] = &bInstr->getOperand(i+2);
11983
11984    // We use some of the operands multiple times, so conservatively just
11985    // clear any kill flags that might be present.
11986    if (argOpers[i]->isReg() && argOpers[i]->isUse())
11987      argOpers[i]->setIsKill(false);
11988  }
11989
11990  // x86 address has 5 operands: base, index, scale, displacement, and segment.
11991  int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
11992
11993  unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
11994  MachineInstrBuilder MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t1);
11995  for (int i=0; i <= lastAddrIndx; ++i)
11996    (*MIB).addOperand(*argOpers[i]);
11997  unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
11998  MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t2);
11999  // add 4 to displacement.
12000  for (int i=0; i <= lastAddrIndx-2; ++i)
12001    (*MIB).addOperand(*argOpers[i]);
12002  MachineOperand newOp3 = *(argOpers[3]);
12003  if (newOp3.isImm())
12004    newOp3.setImm(newOp3.getImm()+4);
12005  else
12006    newOp3.setOffset(newOp3.getOffset()+4);
12007  (*MIB).addOperand(newOp3);
12008  (*MIB).addOperand(*argOpers[lastAddrIndx]);
12009
12010  // t3/4 are defined later, at the bottom of the loop
12011  unsigned t3 = F->getRegInfo().createVirtualRegister(RC);
12012  unsigned t4 = F->getRegInfo().createVirtualRegister(RC);
12013  BuildMI(newMBB, dl, TII->get(X86::PHI), dest1Oper.getReg())
12014    .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(newMBB);
12015  BuildMI(newMBB, dl, TII->get(X86::PHI), dest2Oper.getReg())
12016    .addReg(t2).addMBB(thisMBB).addReg(t4).addMBB(newMBB);
12017
12018  // The subsequent operations should be using the destination registers of
12019  // the PHI instructions.
12020  t1 = dest1Oper.getReg();
12021  t2 = dest2Oper.getReg();
12022
12023  int valArgIndx = lastAddrIndx + 1;
12024  assert((argOpers[valArgIndx]->isReg() ||
12025          argOpers[valArgIndx]->isImm()) &&
12026         "invalid operand");
12027  unsigned t5 = F->getRegInfo().createVirtualRegister(RC);
12028  unsigned t6 = F->getRegInfo().createVirtualRegister(RC);
12029  if (argOpers[valArgIndx]->isReg())
12030    MIB = BuildMI(newMBB, dl, TII->get(regOpcL), t5);
12031  else
12032    MIB = BuildMI(newMBB, dl, TII->get(immOpcL), t5);
12033  if (regOpcL != X86::MOV32rr)
12034    MIB.addReg(t1);
12035  (*MIB).addOperand(*argOpers[valArgIndx]);
12036  assert(argOpers[valArgIndx + 1]->isReg() ==
12037         argOpers[valArgIndx]->isReg());
12038  assert(argOpers[valArgIndx + 1]->isImm() ==
12039         argOpers[valArgIndx]->isImm());
12040  if (argOpers[valArgIndx + 1]->isReg())
12041    MIB = BuildMI(newMBB, dl, TII->get(regOpcH), t6);
12042  else
12043    MIB = BuildMI(newMBB, dl, TII->get(immOpcH), t6);
12044  if (regOpcH != X86::MOV32rr)
12045    MIB.addReg(t2);
12046  (*MIB).addOperand(*argOpers[valArgIndx + 1]);
12047
12048  unsigned t7, t8;
12049  if (Invert) {
12050    t7 = F->getRegInfo().createVirtualRegister(RC);
12051    t8 = F->getRegInfo().createVirtualRegister(RC);
12052    MIB = BuildMI(newMBB, dl, TII->get(NotOpc), t7).addReg(t5);
12053    MIB = BuildMI(newMBB, dl, TII->get(NotOpc), t8).addReg(t6);
12054  } else {
12055    t7 = t5;
12056    t8 = t6;
12057  }
12058
12059  MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EAX);
12060  MIB.addReg(t1);
12061  MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EDX);
12062  MIB.addReg(t2);
12063
12064  MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EBX);
12065  MIB.addReg(t7);
12066  MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::ECX);
12067  MIB.addReg(t8);
12068
12069  MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG8B));
12070  for (int i=0; i <= lastAddrIndx; ++i)
12071    (*MIB).addOperand(*argOpers[i]);
12072
12073  assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
12074  (*MIB).setMemRefs(bInstr->memoperands_begin(),
12075                    bInstr->memoperands_end());
12076
12077  MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t3);
12078  MIB.addReg(X86::EAX);
12079  MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t4);
12080  MIB.addReg(X86::EDX);
12081
12082  // insert branch
12083  BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
12084
12085  bInstr->eraseFromParent();   // The pseudo instruction is gone now.
12086  return nextMBB;
12087}
12088
12089// private utility function
12090MachineBasicBlock *
12091X86TargetLowering::EmitAtomicMinMaxWithCustomInserter(MachineInstr *mInstr,
12092                                                      MachineBasicBlock *MBB,
12093                                                      unsigned cmovOpc) const {
12094  // For the atomic min/max operator, we generate
12095  //   thisMBB:
12096  //   newMBB:
12097  //     ld t1 = [min/max.addr]
12098  //     mov t2 = [min/max.val]
12099  //     cmp  t1, t2
12100  //     cmov[cond] t2 = t1
12101  //     mov EAX = t1
12102  //     lcs dest = [bitinstr.addr], t2  [EAX is implicit]
12103  //     bz   newMBB
12104  //     fallthrough -->nextMBB
12105  //
12106  const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12107  const BasicBlock *LLVM_BB = MBB->getBasicBlock();
12108  MachineFunction::iterator MBBIter = MBB;
12109  ++MBBIter;
12110
12111  /// First build the CFG
12112  MachineFunction *F = MBB->getParent();
12113  MachineBasicBlock *thisMBB = MBB;
12114  MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
12115  MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
12116  F->insert(MBBIter, newMBB);
12117  F->insert(MBBIter, nextMBB);
12118
12119  // Transfer the remainder of thisMBB and its successor edges to nextMBB.
12120  nextMBB->splice(nextMBB->begin(), thisMBB,
12121                  llvm::next(MachineBasicBlock::iterator(mInstr)),
12122                  thisMBB->end());
12123  nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
12124
12125  // Update thisMBB to fall through to newMBB
12126  thisMBB->addSuccessor(newMBB);
12127
12128  // newMBB jumps to newMBB and fall through to nextMBB
12129  newMBB->addSuccessor(nextMBB);
12130  newMBB->addSuccessor(newMBB);
12131
12132  DebugLoc dl = mInstr->getDebugLoc();
12133  // Insert instructions into newMBB based on incoming instruction
12134  assert(mInstr->getNumOperands() < X86::AddrNumOperands + 4 &&
12135         "unexpected number of operands");
12136  MachineOperand& destOper = mInstr->getOperand(0);
12137  MachineOperand* argOpers[2 + X86::AddrNumOperands];
12138  int numArgs = mInstr->getNumOperands() - 1;
12139  for (int i=0; i < numArgs; ++i)
12140    argOpers[i] = &mInstr->getOperand(i+1);
12141
12142  // x86 address has 4 operands: base, index, scale, and displacement
12143  int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
12144  int valArgIndx = lastAddrIndx + 1;
12145
12146  unsigned t1 = F->getRegInfo().createVirtualRegister(&X86::GR32RegClass);
12147  MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rm), t1);
12148  for (int i=0; i <= lastAddrIndx; ++i)
12149    (*MIB).addOperand(*argOpers[i]);
12150
12151  // We only support register and immediate values
12152  assert((argOpers[valArgIndx]->isReg() ||
12153          argOpers[valArgIndx]->isImm()) &&
12154         "invalid operand");
12155
12156  unsigned t2 = F->getRegInfo().createVirtualRegister(&X86::GR32RegClass);
12157  if (argOpers[valArgIndx]->isReg())
12158    MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t2);
12159  else
12160    MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rr), t2);
12161  (*MIB).addOperand(*argOpers[valArgIndx]);
12162
12163  MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EAX);
12164  MIB.addReg(t1);
12165
12166  MIB = BuildMI(newMBB, dl, TII->get(X86::CMP32rr));
12167  MIB.addReg(t1);
12168  MIB.addReg(t2);
12169
12170  // Generate movc
12171  unsigned t3 = F->getRegInfo().createVirtualRegister(&X86::GR32RegClass);
12172  MIB = BuildMI(newMBB, dl, TII->get(cmovOpc),t3);
12173  MIB.addReg(t2);
12174  MIB.addReg(t1);
12175
12176  // Cmp and exchange if none has modified the memory location
12177  MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG32));
12178  for (int i=0; i <= lastAddrIndx; ++i)
12179    (*MIB).addOperand(*argOpers[i]);
12180  MIB.addReg(t3);
12181  assert(mInstr->hasOneMemOperand() && "Unexpected number of memoperand");
12182  (*MIB).setMemRefs(mInstr->memoperands_begin(),
12183                    mInstr->memoperands_end());
12184
12185  MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), destOper.getReg());
12186  MIB.addReg(X86::EAX);
12187
12188  // insert branch
12189  BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
12190
12191  mInstr->eraseFromParent();   // The pseudo instruction is gone now.
12192  return nextMBB;
12193}
12194
12195// FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
12196// or XMM0_V32I8 in AVX all of this code can be replaced with that
12197// in the .td file.
12198MachineBasicBlock *
12199X86TargetLowering::EmitPCMP(MachineInstr *MI, MachineBasicBlock *BB,
12200                            unsigned numArgs, bool memArg) const {
12201  assert(Subtarget->hasSSE42() &&
12202         "Target must have SSE4.2 or AVX features enabled");
12203
12204  DebugLoc dl = MI->getDebugLoc();
12205  const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12206  unsigned Opc;
12207  if (!Subtarget->hasAVX()) {
12208    if (memArg)
12209      Opc = numArgs == 3 ? X86::PCMPISTRM128rm : X86::PCMPESTRM128rm;
12210    else
12211      Opc = numArgs == 3 ? X86::PCMPISTRM128rr : X86::PCMPESTRM128rr;
12212  } else {
12213    if (memArg)
12214      Opc = numArgs == 3 ? X86::VPCMPISTRM128rm : X86::VPCMPESTRM128rm;
12215    else
12216      Opc = numArgs == 3 ? X86::VPCMPISTRM128rr : X86::VPCMPESTRM128rr;
12217  }
12218
12219  MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
12220  for (unsigned i = 0; i < numArgs; ++i) {
12221    MachineOperand &Op = MI->getOperand(i+1);
12222    if (!(Op.isReg() && Op.isImplicit()))
12223      MIB.addOperand(Op);
12224  }
12225  BuildMI(*BB, MI, dl,
12226    TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
12227    .addReg(X86::XMM0);
12228
12229  MI->eraseFromParent();
12230  return BB;
12231}
12232
12233MachineBasicBlock *
12234X86TargetLowering::EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB) const {
12235  DebugLoc dl = MI->getDebugLoc();
12236  const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12237
12238  // Address into RAX/EAX, other two args into ECX, EDX.
12239  unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
12240  unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
12241  MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
12242  for (int i = 0; i < X86::AddrNumOperands; ++i)
12243    MIB.addOperand(MI->getOperand(i));
12244
12245  unsigned ValOps = X86::AddrNumOperands;
12246  BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
12247    .addReg(MI->getOperand(ValOps).getReg());
12248  BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
12249    .addReg(MI->getOperand(ValOps+1).getReg());
12250
12251  // The instruction doesn't actually take any operands though.
12252  BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
12253
12254  MI->eraseFromParent(); // The pseudo is gone now.
12255  return BB;
12256}
12257
12258MachineBasicBlock *
12259X86TargetLowering::EmitVAARG64WithCustomInserter(
12260                   MachineInstr *MI,
12261                   MachineBasicBlock *MBB) const {
12262  // Emit va_arg instruction on X86-64.
12263
12264  // Operands to this pseudo-instruction:
12265  // 0  ) Output        : destination address (reg)
12266  // 1-5) Input         : va_list address (addr, i64mem)
12267  // 6  ) ArgSize       : Size (in bytes) of vararg type
12268  // 7  ) ArgMode       : 0=overflow only, 1=use gp_offset, 2=use fp_offset
12269  // 8  ) Align         : Alignment of type
12270  // 9  ) EFLAGS (implicit-def)
12271
12272  assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
12273  assert(X86::AddrNumOperands == 5 && "VAARG_64 assumes 5 address operands");
12274
12275  unsigned DestReg = MI->getOperand(0).getReg();
12276  MachineOperand &Base = MI->getOperand(1);
12277  MachineOperand &Scale = MI->getOperand(2);
12278  MachineOperand &Index = MI->getOperand(3);
12279  MachineOperand &Disp = MI->getOperand(4);
12280  MachineOperand &Segment = MI->getOperand(5);
12281  unsigned ArgSize = MI->getOperand(6).getImm();
12282  unsigned ArgMode = MI->getOperand(7).getImm();
12283  unsigned Align = MI->getOperand(8).getImm();
12284
12285  // Memory Reference
12286  assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
12287  MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
12288  MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
12289
12290  // Machine Information
12291  const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12292  MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
12293  const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
12294  const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
12295  DebugLoc DL = MI->getDebugLoc();
12296
12297  // struct va_list {
12298  //   i32   gp_offset
12299  //   i32   fp_offset
12300  //   i64   overflow_area (address)
12301  //   i64   reg_save_area (address)
12302  // }
12303  // sizeof(va_list) = 24
12304  // alignment(va_list) = 8
12305
12306  unsigned TotalNumIntRegs = 6;
12307  unsigned TotalNumXMMRegs = 8;
12308  bool UseGPOffset = (ArgMode == 1);
12309  bool UseFPOffset = (ArgMode == 2);
12310  unsigned MaxOffset = TotalNumIntRegs * 8 +
12311                       (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
12312
12313  /* Align ArgSize to a multiple of 8 */
12314  unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
12315  bool NeedsAlign = (Align > 8);
12316
12317  MachineBasicBlock *thisMBB = MBB;
12318  MachineBasicBlock *overflowMBB;
12319  MachineBasicBlock *offsetMBB;
12320  MachineBasicBlock *endMBB;
12321
12322  unsigned OffsetDestReg = 0;    // Argument address computed by offsetMBB
12323  unsigned OverflowDestReg = 0;  // Argument address computed by overflowMBB
12324  unsigned OffsetReg = 0;
12325
12326  if (!UseGPOffset && !UseFPOffset) {
12327    // If we only pull from the overflow region, we don't create a branch.
12328    // We don't need to alter control flow.
12329    OffsetDestReg = 0; // unused
12330    OverflowDestReg = DestReg;
12331
12332    offsetMBB = NULL;
12333    overflowMBB = thisMBB;
12334    endMBB = thisMBB;
12335  } else {
12336    // First emit code to check if gp_offset (or fp_offset) is below the bound.
12337    // If so, pull the argument from reg_save_area. (branch to offsetMBB)
12338    // If not, pull from overflow_area. (branch to overflowMBB)
12339    //
12340    //       thisMBB
12341    //         |     .
12342    //         |        .
12343    //     offsetMBB   overflowMBB
12344    //         |        .
12345    //         |     .
12346    //        endMBB
12347
12348    // Registers for the PHI in endMBB
12349    OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
12350    OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
12351
12352    const BasicBlock *LLVM_BB = MBB->getBasicBlock();
12353    MachineFunction *MF = MBB->getParent();
12354    overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
12355    offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
12356    endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
12357
12358    MachineFunction::iterator MBBIter = MBB;
12359    ++MBBIter;
12360
12361    // Insert the new basic blocks
12362    MF->insert(MBBIter, offsetMBB);
12363    MF->insert(MBBIter, overflowMBB);
12364    MF->insert(MBBIter, endMBB);
12365
12366    // Transfer the remainder of MBB and its successor edges to endMBB.
12367    endMBB->splice(endMBB->begin(), thisMBB,
12368                    llvm::next(MachineBasicBlock::iterator(MI)),
12369                    thisMBB->end());
12370    endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
12371
12372    // Make offsetMBB and overflowMBB successors of thisMBB
12373    thisMBB->addSuccessor(offsetMBB);
12374    thisMBB->addSuccessor(overflowMBB);
12375
12376    // endMBB is a successor of both offsetMBB and overflowMBB
12377    offsetMBB->addSuccessor(endMBB);
12378    overflowMBB->addSuccessor(endMBB);
12379
12380    // Load the offset value into a register
12381    OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
12382    BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
12383      .addOperand(Base)
12384      .addOperand(Scale)
12385      .addOperand(Index)
12386      .addDisp(Disp, UseFPOffset ? 4 : 0)
12387      .addOperand(Segment)
12388      .setMemRefs(MMOBegin, MMOEnd);
12389
12390    // Check if there is enough room left to pull this argument.
12391    BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
12392      .addReg(OffsetReg)
12393      .addImm(MaxOffset + 8 - ArgSizeA8);
12394
12395    // Branch to "overflowMBB" if offset >= max
12396    // Fall through to "offsetMBB" otherwise
12397    BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
12398      .addMBB(overflowMBB);
12399  }
12400
12401  // In offsetMBB, emit code to use the reg_save_area.
12402  if (offsetMBB) {
12403    assert(OffsetReg != 0);
12404
12405    // Read the reg_save_area address.
12406    unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
12407    BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
12408      .addOperand(Base)
12409      .addOperand(Scale)
12410      .addOperand(Index)
12411      .addDisp(Disp, 16)
12412      .addOperand(Segment)
12413      .setMemRefs(MMOBegin, MMOEnd);
12414
12415    // Zero-extend the offset
12416    unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
12417      BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
12418        .addImm(0)
12419        .addReg(OffsetReg)
12420        .addImm(X86::sub_32bit);
12421
12422    // Add the offset to the reg_save_area to get the final address.
12423    BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
12424      .addReg(OffsetReg64)
12425      .addReg(RegSaveReg);
12426
12427    // Compute the offset for the next argument
12428    unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
12429    BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
12430      .addReg(OffsetReg)
12431      .addImm(UseFPOffset ? 16 : 8);
12432
12433    // Store it back into the va_list.
12434    BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
12435      .addOperand(Base)
12436      .addOperand(Scale)
12437      .addOperand(Index)
12438      .addDisp(Disp, UseFPOffset ? 4 : 0)
12439      .addOperand(Segment)
12440      .addReg(NextOffsetReg)
12441      .setMemRefs(MMOBegin, MMOEnd);
12442
12443    // Jump to endMBB
12444    BuildMI(offsetMBB, DL, TII->get(X86::JMP_4))
12445      .addMBB(endMBB);
12446  }
12447
12448  //
12449  // Emit code to use overflow area
12450  //
12451
12452  // Load the overflow_area address into a register.
12453  unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
12454  BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
12455    .addOperand(Base)
12456    .addOperand(Scale)
12457    .addOperand(Index)
12458    .addDisp(Disp, 8)
12459    .addOperand(Segment)
12460    .setMemRefs(MMOBegin, MMOEnd);
12461
12462  // If we need to align it, do so. Otherwise, just copy the address
12463  // to OverflowDestReg.
12464  if (NeedsAlign) {
12465    // Align the overflow address
12466    assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
12467    unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
12468
12469    // aligned_addr = (addr + (align-1)) & ~(align-1)
12470    BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
12471      .addReg(OverflowAddrReg)
12472      .addImm(Align-1);
12473
12474    BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
12475      .addReg(TmpReg)
12476      .addImm(~(uint64_t)(Align-1));
12477  } else {
12478    BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
12479      .addReg(OverflowAddrReg);
12480  }
12481
12482  // Compute the next overflow address after this argument.
12483  // (the overflow address should be kept 8-byte aligned)
12484  unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
12485  BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
12486    .addReg(OverflowDestReg)
12487    .addImm(ArgSizeA8);
12488
12489  // Store the new overflow address.
12490  BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
12491    .addOperand(Base)
12492    .addOperand(Scale)
12493    .addOperand(Index)
12494    .addDisp(Disp, 8)
12495    .addOperand(Segment)
12496    .addReg(NextAddrReg)
12497    .setMemRefs(MMOBegin, MMOEnd);
12498
12499  // If we branched, emit the PHI to the front of endMBB.
12500  if (offsetMBB) {
12501    BuildMI(*endMBB, endMBB->begin(), DL,
12502            TII->get(X86::PHI), DestReg)
12503      .addReg(OffsetDestReg).addMBB(offsetMBB)
12504      .addReg(OverflowDestReg).addMBB(overflowMBB);
12505  }
12506
12507  // Erase the pseudo instruction
12508  MI->eraseFromParent();
12509
12510  return endMBB;
12511}
12512
12513MachineBasicBlock *
12514X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
12515                                                 MachineInstr *MI,
12516                                                 MachineBasicBlock *MBB) const {
12517  // Emit code to save XMM registers to the stack. The ABI says that the
12518  // number of registers to save is given in %al, so it's theoretically
12519  // possible to do an indirect jump trick to avoid saving all of them,
12520  // however this code takes a simpler approach and just executes all
12521  // of the stores if %al is non-zero. It's less code, and it's probably
12522  // easier on the hardware branch predictor, and stores aren't all that
12523  // expensive anyway.
12524
12525  // Create the new basic blocks. One block contains all the XMM stores,
12526  // and one block is the final destination regardless of whether any
12527  // stores were performed.
12528  const BasicBlock *LLVM_BB = MBB->getBasicBlock();
12529  MachineFunction *F = MBB->getParent();
12530  MachineFunction::iterator MBBIter = MBB;
12531  ++MBBIter;
12532  MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
12533  MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
12534  F->insert(MBBIter, XMMSaveMBB);
12535  F->insert(MBBIter, EndMBB);
12536
12537  // Transfer the remainder of MBB and its successor edges to EndMBB.
12538  EndMBB->splice(EndMBB->begin(), MBB,
12539                 llvm::next(MachineBasicBlock::iterator(MI)),
12540                 MBB->end());
12541  EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
12542
12543  // The original block will now fall through to the XMM save block.
12544  MBB->addSuccessor(XMMSaveMBB);
12545  // The XMMSaveMBB will fall through to the end block.
12546  XMMSaveMBB->addSuccessor(EndMBB);
12547
12548  // Now add the instructions.
12549  const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12550  DebugLoc DL = MI->getDebugLoc();
12551
12552  unsigned CountReg = MI->getOperand(0).getReg();
12553  int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
12554  int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
12555
12556  if (!Subtarget->isTargetWin64()) {
12557    // If %al is 0, branch around the XMM save block.
12558    BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
12559    BuildMI(MBB, DL, TII->get(X86::JE_4)).addMBB(EndMBB);
12560    MBB->addSuccessor(EndMBB);
12561  }
12562
12563  unsigned MOVOpc = Subtarget->hasAVX() ? X86::VMOVAPSmr : X86::MOVAPSmr;
12564  // In the XMM save block, save all the XMM argument registers.
12565  for (int i = 3, e = MI->getNumOperands(); i != e; ++i) {
12566    int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
12567    MachineMemOperand *MMO =
12568      F->getMachineMemOperand(
12569          MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
12570        MachineMemOperand::MOStore,
12571        /*Size=*/16, /*Align=*/16);
12572    BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
12573      .addFrameIndex(RegSaveFrameIndex)
12574      .addImm(/*Scale=*/1)
12575      .addReg(/*IndexReg=*/0)
12576      .addImm(/*Disp=*/Offset)
12577      .addReg(/*Segment=*/0)
12578      .addReg(MI->getOperand(i).getReg())
12579      .addMemOperand(MMO);
12580  }
12581
12582  MI->eraseFromParent();   // The pseudo instruction is gone now.
12583
12584  return EndMBB;
12585}
12586
12587// The EFLAGS operand of SelectItr might be missing a kill marker
12588// because there were multiple uses of EFLAGS, and ISel didn't know
12589// which to mark. Figure out whether SelectItr should have had a
12590// kill marker, and set it if it should. Returns the correct kill
12591// marker value.
12592static bool checkAndUpdateEFLAGSKill(MachineBasicBlock::iterator SelectItr,
12593                                     MachineBasicBlock* BB,
12594                                     const TargetRegisterInfo* TRI) {
12595  // Scan forward through BB for a use/def of EFLAGS.
12596  MachineBasicBlock::iterator miI(llvm::next(SelectItr));
12597  for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
12598    const MachineInstr& mi = *miI;
12599    if (mi.readsRegister(X86::EFLAGS))
12600      return false;
12601    if (mi.definesRegister(X86::EFLAGS))
12602      break; // Should have kill-flag - update below.
12603  }
12604
12605  // If we hit the end of the block, check whether EFLAGS is live into a
12606  // successor.
12607  if (miI == BB->end()) {
12608    for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
12609                                          sEnd = BB->succ_end();
12610         sItr != sEnd; ++sItr) {
12611      MachineBasicBlock* succ = *sItr;
12612      if (succ->isLiveIn(X86::EFLAGS))
12613        return false;
12614    }
12615  }
12616
12617  // We found a def, or hit the end of the basic block and EFLAGS wasn't live
12618  // out. SelectMI should have a kill flag on EFLAGS.
12619  SelectItr->addRegisterKilled(X86::EFLAGS, TRI);
12620  return true;
12621}
12622
12623MachineBasicBlock *
12624X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
12625                                     MachineBasicBlock *BB) const {
12626  const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12627  DebugLoc DL = MI->getDebugLoc();
12628
12629  // To "insert" a SELECT_CC instruction, we actually have to insert the
12630  // diamond control-flow pattern.  The incoming instruction knows the
12631  // destination vreg to set, the condition code register to branch on, the
12632  // true/false values to select between, and a branch opcode to use.
12633  const BasicBlock *LLVM_BB = BB->getBasicBlock();
12634  MachineFunction::iterator It = BB;
12635  ++It;
12636
12637  //  thisMBB:
12638  //  ...
12639  //   TrueVal = ...
12640  //   cmpTY ccX, r1, r2
12641  //   bCC copy1MBB
12642  //   fallthrough --> copy0MBB
12643  MachineBasicBlock *thisMBB = BB;
12644  MachineFunction *F = BB->getParent();
12645  MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
12646  MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
12647  F->insert(It, copy0MBB);
12648  F->insert(It, sinkMBB);
12649
12650  // If the EFLAGS register isn't dead in the terminator, then claim that it's
12651  // live into the sink and copy blocks.
12652  const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
12653  if (!MI->killsRegister(X86::EFLAGS) &&
12654      !checkAndUpdateEFLAGSKill(MI, BB, TRI)) {
12655    copy0MBB->addLiveIn(X86::EFLAGS);
12656    sinkMBB->addLiveIn(X86::EFLAGS);
12657  }
12658
12659  // Transfer the remainder of BB and its successor edges to sinkMBB.
12660  sinkMBB->splice(sinkMBB->begin(), BB,
12661                  llvm::next(MachineBasicBlock::iterator(MI)),
12662                  BB->end());
12663  sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
12664
12665  // Add the true and fallthrough blocks as its successors.
12666  BB->addSuccessor(copy0MBB);
12667  BB->addSuccessor(sinkMBB);
12668
12669  // Create the conditional branch instruction.
12670  unsigned Opc =
12671    X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
12672  BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
12673
12674  //  copy0MBB:
12675  //   %FalseValue = ...
12676  //   # fallthrough to sinkMBB
12677  copy0MBB->addSuccessor(sinkMBB);
12678
12679  //  sinkMBB:
12680  //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
12681  //  ...
12682  BuildMI(*sinkMBB, sinkMBB->begin(), DL,
12683          TII->get(X86::PHI), MI->getOperand(0).getReg())
12684    .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
12685    .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
12686
12687  MI->eraseFromParent();   // The pseudo instruction is gone now.
12688  return sinkMBB;
12689}
12690
12691MachineBasicBlock *
12692X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI, MachineBasicBlock *BB,
12693                                        bool Is64Bit) const {
12694  const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12695  DebugLoc DL = MI->getDebugLoc();
12696  MachineFunction *MF = BB->getParent();
12697  const BasicBlock *LLVM_BB = BB->getBasicBlock();
12698
12699  assert(getTargetMachine().Options.EnableSegmentedStacks);
12700
12701  unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
12702  unsigned TlsOffset = Is64Bit ? 0x70 : 0x30;
12703
12704  // BB:
12705  //  ... [Till the alloca]
12706  // If stacklet is not large enough, jump to mallocMBB
12707  //
12708  // bumpMBB:
12709  //  Allocate by subtracting from RSP
12710  //  Jump to continueMBB
12711  //
12712  // mallocMBB:
12713  //  Allocate by call to runtime
12714  //
12715  // continueMBB:
12716  //  ...
12717  //  [rest of original BB]
12718  //
12719
12720  MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
12721  MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
12722  MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
12723
12724  MachineRegisterInfo &MRI = MF->getRegInfo();
12725  const TargetRegisterClass *AddrRegClass =
12726    getRegClassFor(Is64Bit ? MVT::i64:MVT::i32);
12727
12728  unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
12729    bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
12730    tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
12731    SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
12732    sizeVReg = MI->getOperand(1).getReg(),
12733    physSPReg = Is64Bit ? X86::RSP : X86::ESP;
12734
12735  MachineFunction::iterator MBBIter = BB;
12736  ++MBBIter;
12737
12738  MF->insert(MBBIter, bumpMBB);
12739  MF->insert(MBBIter, mallocMBB);
12740  MF->insert(MBBIter, continueMBB);
12741
12742  continueMBB->splice(continueMBB->begin(), BB, llvm::next
12743                      (MachineBasicBlock::iterator(MI)), BB->end());
12744  continueMBB->transferSuccessorsAndUpdatePHIs(BB);
12745
12746  // Add code to the main basic block to check if the stack limit has been hit,
12747  // and if so, jump to mallocMBB otherwise to bumpMBB.
12748  BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
12749  BuildMI(BB, DL, TII->get(Is64Bit ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
12750    .addReg(tmpSPVReg).addReg(sizeVReg);
12751  BuildMI(BB, DL, TII->get(Is64Bit ? X86::CMP64mr:X86::CMP32mr))
12752    .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg)
12753    .addReg(SPLimitVReg);
12754  BuildMI(BB, DL, TII->get(X86::JG_4)).addMBB(mallocMBB);
12755
12756  // bumpMBB simply decreases the stack pointer, since we know the current
12757  // stacklet has enough space.
12758  BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
12759    .addReg(SPLimitVReg);
12760  BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
12761    .addReg(SPLimitVReg);
12762  BuildMI(bumpMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
12763
12764  // Calls into a routine in libgcc to allocate more space from the heap.
12765  const uint32_t *RegMask =
12766    getTargetMachine().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
12767  if (Is64Bit) {
12768    BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
12769      .addReg(sizeVReg);
12770    BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
12771      .addExternalSymbol("__morestack_allocate_stack_space")
12772      .addRegMask(RegMask)
12773      .addReg(X86::RDI, RegState::Implicit)
12774      .addReg(X86::RAX, RegState::ImplicitDefine);
12775  } else {
12776    BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
12777      .addImm(12);
12778    BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
12779    BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
12780      .addExternalSymbol("__morestack_allocate_stack_space")
12781      .addRegMask(RegMask)
12782      .addReg(X86::EAX, RegState::ImplicitDefine);
12783  }
12784
12785  if (!Is64Bit)
12786    BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
12787      .addImm(16);
12788
12789  BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
12790    .addReg(Is64Bit ? X86::RAX : X86::EAX);
12791  BuildMI(mallocMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
12792
12793  // Set up the CFG correctly.
12794  BB->addSuccessor(bumpMBB);
12795  BB->addSuccessor(mallocMBB);
12796  mallocMBB->addSuccessor(continueMBB);
12797  bumpMBB->addSuccessor(continueMBB);
12798
12799  // Take care of the PHI nodes.
12800  BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
12801          MI->getOperand(0).getReg())
12802    .addReg(mallocPtrVReg).addMBB(mallocMBB)
12803    .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
12804
12805  // Delete the original pseudo instruction.
12806  MI->eraseFromParent();
12807
12808  // And we're done.
12809  return continueMBB;
12810}
12811
12812MachineBasicBlock *
12813X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
12814                                          MachineBasicBlock *BB) const {
12815  const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12816  DebugLoc DL = MI->getDebugLoc();
12817
12818  assert(!Subtarget->isTargetEnvMacho());
12819
12820  // The lowering is pretty easy: we're just emitting the call to _alloca.  The
12821  // non-trivial part is impdef of ESP.
12822
12823  if (Subtarget->isTargetWin64()) {
12824    if (Subtarget->isTargetCygMing()) {
12825      // ___chkstk(Mingw64):
12826      // Clobbers R10, R11, RAX and EFLAGS.
12827      // Updates RSP.
12828      BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
12829        .addExternalSymbol("___chkstk")
12830        .addReg(X86::RAX, RegState::Implicit)
12831        .addReg(X86::RSP, RegState::Implicit)
12832        .addReg(X86::RAX, RegState::Define | RegState::Implicit)
12833        .addReg(X86::RSP, RegState::Define | RegState::Implicit)
12834        .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
12835    } else {
12836      // __chkstk(MSVCRT): does not update stack pointer.
12837      // Clobbers R10, R11 and EFLAGS.
12838      // FIXME: RAX(allocated size) might be reused and not killed.
12839      BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
12840        .addExternalSymbol("__chkstk")
12841        .addReg(X86::RAX, RegState::Implicit)
12842        .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
12843      // RAX has the offset to subtracted from RSP.
12844      BuildMI(*BB, MI, DL, TII->get(X86::SUB64rr), X86::RSP)
12845        .addReg(X86::RSP)
12846        .addReg(X86::RAX);
12847    }
12848  } else {
12849    const char *StackProbeSymbol =
12850      Subtarget->isTargetWindows() ? "_chkstk" : "_alloca";
12851
12852    BuildMI(*BB, MI, DL, TII->get(X86::CALLpcrel32))
12853      .addExternalSymbol(StackProbeSymbol)
12854      .addReg(X86::EAX, RegState::Implicit)
12855      .addReg(X86::ESP, RegState::Implicit)
12856      .addReg(X86::EAX, RegState::Define | RegState::Implicit)
12857      .addReg(X86::ESP, RegState::Define | RegState::Implicit)
12858      .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
12859  }
12860
12861  MI->eraseFromParent();   // The pseudo instruction is gone now.
12862  return BB;
12863}
12864
12865MachineBasicBlock *
12866X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
12867                                      MachineBasicBlock *BB) const {
12868  // This is pretty easy.  We're taking the value that we received from
12869  // our load from the relocation, sticking it in either RDI (x86-64)
12870  // or EAX and doing an indirect call.  The return value will then
12871  // be in the normal return register.
12872  const X86InstrInfo *TII
12873    = static_cast<const X86InstrInfo*>(getTargetMachine().getInstrInfo());
12874  DebugLoc DL = MI->getDebugLoc();
12875  MachineFunction *F = BB->getParent();
12876
12877  assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
12878  assert(MI->getOperand(3).isGlobal() && "This should be a global");
12879
12880  // Get a register mask for the lowered call.
12881  // FIXME: The 32-bit calls have non-standard calling conventions. Use a
12882  // proper register mask.
12883  const uint32_t *RegMask =
12884    getTargetMachine().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
12885  if (Subtarget->is64Bit()) {
12886    MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
12887                                      TII->get(X86::MOV64rm), X86::RDI)
12888    .addReg(X86::RIP)
12889    .addImm(0).addReg(0)
12890    .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
12891                      MI->getOperand(3).getTargetFlags())
12892    .addReg(0);
12893    MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
12894    addDirectMem(MIB, X86::RDI);
12895    MIB.addReg(X86::RAX, RegState::ImplicitDefine).addRegMask(RegMask);
12896  } else if (getTargetMachine().getRelocationModel() != Reloc::PIC_) {
12897    MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
12898                                      TII->get(X86::MOV32rm), X86::EAX)
12899    .addReg(0)
12900    .addImm(0).addReg(0)
12901    .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
12902                      MI->getOperand(3).getTargetFlags())
12903    .addReg(0);
12904    MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
12905    addDirectMem(MIB, X86::EAX);
12906    MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
12907  } else {
12908    MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
12909                                      TII->get(X86::MOV32rm), X86::EAX)
12910    .addReg(TII->getGlobalBaseReg(F))
12911    .addImm(0).addReg(0)
12912    .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
12913                      MI->getOperand(3).getTargetFlags())
12914    .addReg(0);
12915    MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
12916    addDirectMem(MIB, X86::EAX);
12917    MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
12918  }
12919
12920  MI->eraseFromParent(); // The pseudo instruction is gone now.
12921  return BB;
12922}
12923
12924MachineBasicBlock *
12925X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
12926                                               MachineBasicBlock *BB) const {
12927  switch (MI->getOpcode()) {
12928  default: llvm_unreachable("Unexpected instr type to insert");
12929  case X86::TAILJMPd64:
12930  case X86::TAILJMPr64:
12931  case X86::TAILJMPm64:
12932    llvm_unreachable("TAILJMP64 would not be touched here.");
12933  case X86::TCRETURNdi64:
12934  case X86::TCRETURNri64:
12935  case X86::TCRETURNmi64:
12936    return BB;
12937  case X86::WIN_ALLOCA:
12938    return EmitLoweredWinAlloca(MI, BB);
12939  case X86::SEG_ALLOCA_32:
12940    return EmitLoweredSegAlloca(MI, BB, false);
12941  case X86::SEG_ALLOCA_64:
12942    return EmitLoweredSegAlloca(MI, BB, true);
12943  case X86::TLSCall_32:
12944  case X86::TLSCall_64:
12945    return EmitLoweredTLSCall(MI, BB);
12946  case X86::CMOV_GR8:
12947  case X86::CMOV_FR32:
12948  case X86::CMOV_FR64:
12949  case X86::CMOV_V4F32:
12950  case X86::CMOV_V2F64:
12951  case X86::CMOV_V2I64:
12952  case X86::CMOV_V8F32:
12953  case X86::CMOV_V4F64:
12954  case X86::CMOV_V4I64:
12955  case X86::CMOV_GR16:
12956  case X86::CMOV_GR32:
12957  case X86::CMOV_RFP32:
12958  case X86::CMOV_RFP64:
12959  case X86::CMOV_RFP80:
12960    return EmitLoweredSelect(MI, BB);
12961
12962  case X86::FP32_TO_INT16_IN_MEM:
12963  case X86::FP32_TO_INT32_IN_MEM:
12964  case X86::FP32_TO_INT64_IN_MEM:
12965  case X86::FP64_TO_INT16_IN_MEM:
12966  case X86::FP64_TO_INT32_IN_MEM:
12967  case X86::FP64_TO_INT64_IN_MEM:
12968  case X86::FP80_TO_INT16_IN_MEM:
12969  case X86::FP80_TO_INT32_IN_MEM:
12970  case X86::FP80_TO_INT64_IN_MEM: {
12971    const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12972    DebugLoc DL = MI->getDebugLoc();
12973
12974    // Change the floating point control register to use "round towards zero"
12975    // mode when truncating to an integer value.
12976    MachineFunction *F = BB->getParent();
12977    int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
12978    addFrameReference(BuildMI(*BB, MI, DL,
12979                              TII->get(X86::FNSTCW16m)), CWFrameIdx);
12980
12981    // Load the old value of the high byte of the control word...
12982    unsigned OldCW =
12983      F->getRegInfo().createVirtualRegister(&X86::GR16RegClass);
12984    addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
12985                      CWFrameIdx);
12986
12987    // Set the high part to be round to zero...
12988    addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
12989      .addImm(0xC7F);
12990
12991    // Reload the modified control word now...
12992    addFrameReference(BuildMI(*BB, MI, DL,
12993                              TII->get(X86::FLDCW16m)), CWFrameIdx);
12994
12995    // Restore the memory image of control word to original value
12996    addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
12997      .addReg(OldCW);
12998
12999    // Get the X86 opcode to use.
13000    unsigned Opc;
13001    switch (MI->getOpcode()) {
13002    default: llvm_unreachable("illegal opcode!");
13003    case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
13004    case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
13005    case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
13006    case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
13007    case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
13008    case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
13009    case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
13010    case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
13011    case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
13012    }
13013
13014    X86AddressMode AM;
13015    MachineOperand &Op = MI->getOperand(0);
13016    if (Op.isReg()) {
13017      AM.BaseType = X86AddressMode::RegBase;
13018      AM.Base.Reg = Op.getReg();
13019    } else {
13020      AM.BaseType = X86AddressMode::FrameIndexBase;
13021      AM.Base.FrameIndex = Op.getIndex();
13022    }
13023    Op = MI->getOperand(1);
13024    if (Op.isImm())
13025      AM.Scale = Op.getImm();
13026    Op = MI->getOperand(2);
13027    if (Op.isImm())
13028      AM.IndexReg = Op.getImm();
13029    Op = MI->getOperand(3);
13030    if (Op.isGlobal()) {
13031      AM.GV = Op.getGlobal();
13032    } else {
13033      AM.Disp = Op.getImm();
13034    }
13035    addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
13036                      .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
13037
13038    // Reload the original control word now.
13039    addFrameReference(BuildMI(*BB, MI, DL,
13040                              TII->get(X86::FLDCW16m)), CWFrameIdx);
13041
13042    MI->eraseFromParent();   // The pseudo instruction is gone now.
13043    return BB;
13044  }
13045    // String/text processing lowering.
13046  case X86::PCMPISTRM128REG:
13047  case X86::VPCMPISTRM128REG:
13048  case X86::PCMPISTRM128MEM:
13049  case X86::VPCMPISTRM128MEM:
13050  case X86::PCMPESTRM128REG:
13051  case X86::VPCMPESTRM128REG:
13052  case X86::PCMPESTRM128MEM:
13053  case X86::VPCMPESTRM128MEM: {
13054    unsigned NumArgs;
13055    bool MemArg;
13056    switch (MI->getOpcode()) {
13057    default: llvm_unreachable("illegal opcode!");
13058    case X86::PCMPISTRM128REG:
13059    case X86::VPCMPISTRM128REG:
13060      NumArgs = 3; MemArg = false; break;
13061    case X86::PCMPISTRM128MEM:
13062    case X86::VPCMPISTRM128MEM:
13063      NumArgs = 3; MemArg = true; break;
13064    case X86::PCMPESTRM128REG:
13065    case X86::VPCMPESTRM128REG:
13066      NumArgs = 5; MemArg = false; break;
13067    case X86::PCMPESTRM128MEM:
13068    case X86::VPCMPESTRM128MEM:
13069      NumArgs = 5; MemArg = true; break;
13070    }
13071    return EmitPCMP(MI, BB, NumArgs, MemArg);
13072  }
13073
13074    // Thread synchronization.
13075  case X86::MONITOR:
13076    return EmitMonitor(MI, BB);
13077
13078    // Atomic Lowering.
13079  case X86::ATOMMIN32:
13080  case X86::ATOMMAX32:
13081  case X86::ATOMUMIN32:
13082  case X86::ATOMUMAX32:
13083  case X86::ATOMMIN16:
13084  case X86::ATOMMAX16:
13085  case X86::ATOMUMIN16:
13086  case X86::ATOMUMAX16:
13087  case X86::ATOMMIN64:
13088  case X86::ATOMMAX64:
13089  case X86::ATOMUMIN64:
13090  case X86::ATOMUMAX64: {
13091    unsigned Opc;
13092    switch (MI->getOpcode()) {
13093    default: llvm_unreachable("illegal opcode!");
13094    case X86::ATOMMIN32:  Opc = X86::CMOVL32rr; break;
13095    case X86::ATOMMAX32:  Opc = X86::CMOVG32rr; break;
13096    case X86::ATOMUMIN32: Opc = X86::CMOVB32rr; break;
13097    case X86::ATOMUMAX32: Opc = X86::CMOVA32rr; break;
13098    case X86::ATOMMIN16:  Opc = X86::CMOVL16rr; break;
13099    case X86::ATOMMAX16:  Opc = X86::CMOVG16rr; break;
13100    case X86::ATOMUMIN16: Opc = X86::CMOVB16rr; break;
13101    case X86::ATOMUMAX16: Opc = X86::CMOVA16rr; break;
13102    case X86::ATOMMIN64:  Opc = X86::CMOVL64rr; break;
13103    case X86::ATOMMAX64:  Opc = X86::CMOVG64rr; break;
13104    case X86::ATOMUMIN64: Opc = X86::CMOVB64rr; break;
13105    case X86::ATOMUMAX64: Opc = X86::CMOVA64rr; break;
13106    // FIXME: There are no CMOV8 instructions; MIN/MAX need some other way.
13107    }
13108    return EmitAtomicMinMaxWithCustomInserter(MI, BB, Opc);
13109  }
13110
13111  case X86::ATOMAND32:
13112  case X86::ATOMOR32:
13113  case X86::ATOMXOR32:
13114  case X86::ATOMNAND32: {
13115    bool Invert = false;
13116    unsigned RegOpc, ImmOpc;
13117    switch (MI->getOpcode()) {
13118    default: llvm_unreachable("illegal opcode!");
13119    case X86::ATOMAND32:
13120      RegOpc = X86::AND32rr; ImmOpc = X86::AND32ri; break;
13121    case X86::ATOMOR32:
13122      RegOpc = X86::OR32rr;  ImmOpc = X86::OR32ri; break;
13123    case X86::ATOMXOR32:
13124      RegOpc = X86::XOR32rr; ImmOpc = X86::XOR32ri; break;
13125    case X86::ATOMNAND32:
13126      RegOpc = X86::AND32rr; ImmOpc = X86::AND32ri; Invert = true; break;
13127    }
13128    return EmitAtomicBitwiseWithCustomInserter(MI, BB, RegOpc, ImmOpc,
13129                                               X86::MOV32rm, X86::LCMPXCHG32,
13130                                               X86::NOT32r, X86::EAX,
13131                                               &X86::GR32RegClass, Invert);
13132  }
13133
13134  case X86::ATOMAND16:
13135  case X86::ATOMOR16:
13136  case X86::ATOMXOR16:
13137  case X86::ATOMNAND16: {
13138    bool Invert = false;
13139    unsigned RegOpc, ImmOpc;
13140    switch (MI->getOpcode()) {
13141    default: llvm_unreachable("illegal opcode!");
13142    case X86::ATOMAND16:
13143      RegOpc = X86::AND16rr; ImmOpc = X86::AND16ri; break;
13144    case X86::ATOMOR16:
13145      RegOpc = X86::OR16rr;  ImmOpc = X86::OR16ri; break;
13146    case X86::ATOMXOR16:
13147      RegOpc = X86::XOR16rr; ImmOpc = X86::XOR16ri; break;
13148    case X86::ATOMNAND16:
13149      RegOpc = X86::AND16rr; ImmOpc = X86::AND16ri; Invert = true; break;
13150    }
13151    return EmitAtomicBitwiseWithCustomInserter(MI, BB, RegOpc, ImmOpc,
13152                                               X86::MOV16rm, X86::LCMPXCHG16,
13153                                               X86::NOT16r, X86::AX,
13154                                               &X86::GR16RegClass, Invert);
13155  }
13156
13157  case X86::ATOMAND8:
13158  case X86::ATOMOR8:
13159  case X86::ATOMXOR8:
13160  case X86::ATOMNAND8: {
13161    bool Invert = false;
13162    unsigned RegOpc, ImmOpc;
13163    switch (MI->getOpcode()) {
13164    default: llvm_unreachable("illegal opcode!");
13165    case X86::ATOMAND8:
13166      RegOpc = X86::AND8rr; ImmOpc = X86::AND8ri; break;
13167    case X86::ATOMOR8:
13168      RegOpc = X86::OR8rr;  ImmOpc = X86::OR8ri; break;
13169    case X86::ATOMXOR8:
13170      RegOpc = X86::XOR8rr; ImmOpc = X86::XOR8ri; break;
13171    case X86::ATOMNAND8:
13172      RegOpc = X86::AND8rr; ImmOpc = X86::AND8ri; Invert = true; break;
13173    }
13174    return EmitAtomicBitwiseWithCustomInserter(MI, BB, RegOpc, ImmOpc,
13175                                               X86::MOV8rm, X86::LCMPXCHG8,
13176                                               X86::NOT8r, X86::AL,
13177                                               &X86::GR8RegClass, Invert);
13178  }
13179
13180  // This group is for 64-bit host.
13181  case X86::ATOMAND64:
13182  case X86::ATOMOR64:
13183  case X86::ATOMXOR64:
13184  case X86::ATOMNAND64: {
13185    bool Invert = false;
13186    unsigned RegOpc, ImmOpc;
13187    switch (MI->getOpcode()) {
13188    default: llvm_unreachable("illegal opcode!");
13189    case X86::ATOMAND64:
13190      RegOpc = X86::AND64rr; ImmOpc = X86::AND64ri32; break;
13191    case X86::ATOMOR64:
13192      RegOpc = X86::OR64rr;  ImmOpc = X86::OR64ri32; break;
13193    case X86::ATOMXOR64:
13194      RegOpc = X86::XOR64rr; ImmOpc = X86::XOR64ri32; break;
13195    case X86::ATOMNAND64:
13196      RegOpc = X86::AND64rr; ImmOpc = X86::AND64ri32; Invert = true; break;
13197    }
13198    return EmitAtomicBitwiseWithCustomInserter(MI, BB, RegOpc, ImmOpc,
13199                                               X86::MOV64rm, X86::LCMPXCHG64,
13200                                               X86::NOT64r, X86::RAX,
13201                                               &X86::GR64RegClass, Invert);
13202  }
13203
13204  // This group does 64-bit operations on a 32-bit host.
13205  case X86::ATOMAND6432:
13206  case X86::ATOMOR6432:
13207  case X86::ATOMXOR6432:
13208  case X86::ATOMNAND6432:
13209  case X86::ATOMADD6432:
13210  case X86::ATOMSUB6432:
13211  case X86::ATOMSWAP6432: {
13212    bool Invert = false;
13213    unsigned RegOpcL, RegOpcH, ImmOpcL, ImmOpcH;
13214    switch (MI->getOpcode()) {
13215    default: llvm_unreachable("illegal opcode!");
13216    case X86::ATOMAND6432:
13217      RegOpcL = RegOpcH = X86::AND32rr;
13218      ImmOpcL = ImmOpcH = X86::AND32ri;
13219      break;
13220    case X86::ATOMOR6432:
13221      RegOpcL = RegOpcH = X86::OR32rr;
13222      ImmOpcL = ImmOpcH = X86::OR32ri;
13223      break;
13224    case X86::ATOMXOR6432:
13225      RegOpcL = RegOpcH = X86::XOR32rr;
13226      ImmOpcL = ImmOpcH = X86::XOR32ri;
13227      break;
13228    case X86::ATOMNAND6432:
13229      RegOpcL = RegOpcH = X86::AND32rr;
13230      ImmOpcL = ImmOpcH = X86::AND32ri;
13231      Invert = true;
13232      break;
13233    case X86::ATOMADD6432:
13234      RegOpcL = X86::ADD32rr; RegOpcH = X86::ADC32rr;
13235      ImmOpcL = X86::ADD32ri; ImmOpcH = X86::ADC32ri;
13236      break;
13237    case X86::ATOMSUB6432:
13238      RegOpcL = X86::SUB32rr; RegOpcH = X86::SBB32rr;
13239      ImmOpcL = X86::SUB32ri; ImmOpcH = X86::SBB32ri;
13240      break;
13241    case X86::ATOMSWAP6432:
13242      RegOpcL = RegOpcH = X86::MOV32rr;
13243      ImmOpcL = ImmOpcH = X86::MOV32ri;
13244      break;
13245    }
13246    return EmitAtomicBit6432WithCustomInserter(MI, BB, RegOpcL, RegOpcH,
13247                                               ImmOpcL, ImmOpcH, Invert);
13248  }
13249
13250  case X86::VASTART_SAVE_XMM_REGS:
13251    return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
13252
13253  case X86::VAARG_64:
13254    return EmitVAARG64WithCustomInserter(MI, BB);
13255  }
13256}
13257
13258//===----------------------------------------------------------------------===//
13259//                           X86 Optimization Hooks
13260//===----------------------------------------------------------------------===//
13261
13262void X86TargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
13263                                                       APInt &KnownZero,
13264                                                       APInt &KnownOne,
13265                                                       const SelectionDAG &DAG,
13266                                                       unsigned Depth) const {
13267  unsigned BitWidth = KnownZero.getBitWidth();
13268  unsigned Opc = Op.getOpcode();
13269  assert((Opc >= ISD::BUILTIN_OP_END ||
13270          Opc == ISD::INTRINSIC_WO_CHAIN ||
13271          Opc == ISD::INTRINSIC_W_CHAIN ||
13272          Opc == ISD::INTRINSIC_VOID) &&
13273         "Should use MaskedValueIsZero if you don't know whether Op"
13274         " is a target node!");
13275
13276  KnownZero = KnownOne = APInt(BitWidth, 0);   // Don't know anything.
13277  switch (Opc) {
13278  default: break;
13279  case X86ISD::ADD:
13280  case X86ISD::SUB:
13281  case X86ISD::ADC:
13282  case X86ISD::SBB:
13283  case X86ISD::SMUL:
13284  case X86ISD::UMUL:
13285  case X86ISD::INC:
13286  case X86ISD::DEC:
13287  case X86ISD::OR:
13288  case X86ISD::XOR:
13289  case X86ISD::AND:
13290    // These nodes' second result is a boolean.
13291    if (Op.getResNo() == 0)
13292      break;
13293    // Fallthrough
13294  case X86ISD::SETCC:
13295    KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
13296    break;
13297  case ISD::INTRINSIC_WO_CHAIN: {
13298    unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
13299    unsigned NumLoBits = 0;
13300    switch (IntId) {
13301    default: break;
13302    case Intrinsic::x86_sse_movmsk_ps:
13303    case Intrinsic::x86_avx_movmsk_ps_256:
13304    case Intrinsic::x86_sse2_movmsk_pd:
13305    case Intrinsic::x86_avx_movmsk_pd_256:
13306    case Intrinsic::x86_mmx_pmovmskb:
13307    case Intrinsic::x86_sse2_pmovmskb_128:
13308    case Intrinsic::x86_avx2_pmovmskb: {
13309      // High bits of movmskp{s|d}, pmovmskb are known zero.
13310      switch (IntId) {
13311        default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
13312        case Intrinsic::x86_sse_movmsk_ps:      NumLoBits = 4; break;
13313        case Intrinsic::x86_avx_movmsk_ps_256:  NumLoBits = 8; break;
13314        case Intrinsic::x86_sse2_movmsk_pd:     NumLoBits = 2; break;
13315        case Intrinsic::x86_avx_movmsk_pd_256:  NumLoBits = 4; break;
13316        case Intrinsic::x86_mmx_pmovmskb:       NumLoBits = 8; break;
13317        case Intrinsic::x86_sse2_pmovmskb_128:  NumLoBits = 16; break;
13318        case Intrinsic::x86_avx2_pmovmskb:      NumLoBits = 32; break;
13319      }
13320      KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - NumLoBits);
13321      break;
13322    }
13323    }
13324    break;
13325  }
13326  }
13327}
13328
13329unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(SDValue Op,
13330                                                         unsigned Depth) const {
13331  // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
13332  if (Op.getOpcode() == X86ISD::SETCC_CARRY)
13333    return Op.getValueType().getScalarType().getSizeInBits();
13334
13335  // Fallback case.
13336  return 1;
13337}
13338
13339/// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
13340/// node is a GlobalAddress + offset.
13341bool X86TargetLowering::isGAPlusOffset(SDNode *N,
13342                                       const GlobalValue* &GA,
13343                                       int64_t &Offset) const {
13344  if (N->getOpcode() == X86ISD::Wrapper) {
13345    if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
13346      GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
13347      Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
13348      return true;
13349    }
13350  }
13351  return TargetLowering::isGAPlusOffset(N, GA, Offset);
13352}
13353
13354/// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the
13355/// same as extracting the high 128-bit part of 256-bit vector and then
13356/// inserting the result into the low part of a new 256-bit vector
13357static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) {
13358  EVT VT = SVOp->getValueType(0);
13359  unsigned NumElems = VT.getVectorNumElements();
13360
13361  // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
13362  for (unsigned i = 0, j = NumElems/2; i != NumElems/2; ++i, ++j)
13363    if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
13364        SVOp->getMaskElt(j) >= 0)
13365      return false;
13366
13367  return true;
13368}
13369
13370/// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the
13371/// same as extracting the low 128-bit part of 256-bit vector and then
13372/// inserting the result into the high part of a new 256-bit vector
13373static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) {
13374  EVT VT = SVOp->getValueType(0);
13375  unsigned NumElems = VT.getVectorNumElements();
13376
13377  // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
13378  for (unsigned i = NumElems/2, j = 0; i != NumElems; ++i, ++j)
13379    if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
13380        SVOp->getMaskElt(j) >= 0)
13381      return false;
13382
13383  return true;
13384}
13385
13386/// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
13387static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
13388                                        TargetLowering::DAGCombinerInfo &DCI,
13389                                        const X86Subtarget* Subtarget) {
13390  DebugLoc dl = N->getDebugLoc();
13391  ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
13392  SDValue V1 = SVOp->getOperand(0);
13393  SDValue V2 = SVOp->getOperand(1);
13394  EVT VT = SVOp->getValueType(0);
13395  unsigned NumElems = VT.getVectorNumElements();
13396
13397  if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
13398      V2.getOpcode() == ISD::CONCAT_VECTORS) {
13399    //
13400    //                   0,0,0,...
13401    //                      |
13402    //    V      UNDEF    BUILD_VECTOR    UNDEF
13403    //     \      /           \           /
13404    //  CONCAT_VECTOR         CONCAT_VECTOR
13405    //         \                  /
13406    //          \                /
13407    //          RESULT: V + zero extended
13408    //
13409    if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
13410        V2.getOperand(1).getOpcode() != ISD::UNDEF ||
13411        V1.getOperand(1).getOpcode() != ISD::UNDEF)
13412      return SDValue();
13413
13414    if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
13415      return SDValue();
13416
13417    // To match the shuffle mask, the first half of the mask should
13418    // be exactly the first vector, and all the rest a splat with the
13419    // first element of the second one.
13420    for (unsigned i = 0; i != NumElems/2; ++i)
13421      if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
13422          !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
13423        return SDValue();
13424
13425    // If V1 is coming from a vector load then just fold to a VZEXT_LOAD.
13426    if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(V1.getOperand(0))) {
13427      if (Ld->hasNUsesOfValue(1, 0)) {
13428        SDVTList Tys = DAG.getVTList(MVT::v4i64, MVT::Other);
13429        SDValue Ops[] = { Ld->getChain(), Ld->getBasePtr() };
13430        SDValue ResNode =
13431          DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops, 2,
13432                                  Ld->getMemoryVT(),
13433                                  Ld->getPointerInfo(),
13434                                  Ld->getAlignment(),
13435                                  false/*isVolatile*/, true/*ReadMem*/,
13436                                  false/*WriteMem*/);
13437        return DAG.getNode(ISD::BITCAST, dl, VT, ResNode);
13438      }
13439    }
13440
13441    // Emit a zeroed vector and insert the desired subvector on its
13442    // first half.
13443    SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
13444    SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0), 0, DAG, dl);
13445    return DCI.CombineTo(N, InsV);
13446  }
13447
13448  //===--------------------------------------------------------------------===//
13449  // Combine some shuffles into subvector extracts and inserts:
13450  //
13451
13452  // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
13453  if (isShuffleHigh128VectorInsertLow(SVOp)) {
13454    SDValue V = Extract128BitVector(V1, NumElems/2, DAG, dl);
13455    SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, 0, DAG, dl);
13456    return DCI.CombineTo(N, InsV);
13457  }
13458
13459  // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
13460  if (isShuffleLow128VectorInsertHigh(SVOp)) {
13461    SDValue V = Extract128BitVector(V1, 0, DAG, dl);
13462    SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, NumElems/2, DAG, dl);
13463    return DCI.CombineTo(N, InsV);
13464  }
13465
13466  return SDValue();
13467}
13468
13469/// PerformShuffleCombine - Performs several different shuffle combines.
13470static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
13471                                     TargetLowering::DAGCombinerInfo &DCI,
13472                                     const X86Subtarget *Subtarget) {
13473  DebugLoc dl = N->getDebugLoc();
13474  EVT VT = N->getValueType(0);
13475
13476  // Don't create instructions with illegal types after legalize types has run.
13477  const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13478  if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
13479    return SDValue();
13480
13481  // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
13482  if (Subtarget->hasAVX() && VT.is256BitVector() &&
13483      N->getOpcode() == ISD::VECTOR_SHUFFLE)
13484    return PerformShuffleCombine256(N, DAG, DCI, Subtarget);
13485
13486  // Only handle 128 wide vector from here on.
13487  if (!VT.is128BitVector())
13488    return SDValue();
13489
13490  // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
13491  // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
13492  // consecutive, non-overlapping, and in the right order.
13493  SmallVector<SDValue, 16> Elts;
13494  for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
13495    Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
13496
13497  return EltsFromConsecutiveLoads(VT, Elts, dl, DAG);
13498}
13499
13500
13501/// DCI, PerformTruncateCombine - Converts truncate operation to
13502/// a sequence of vector shuffle operations.
13503/// It is possible when we truncate 256-bit vector to 128-bit vector
13504
13505SDValue X86TargetLowering::PerformTruncateCombine(SDNode *N, SelectionDAG &DAG,
13506                                                  DAGCombinerInfo &DCI) const {
13507  if (!DCI.isBeforeLegalizeOps())
13508    return SDValue();
13509
13510  if (!Subtarget->hasAVX())
13511    return SDValue();
13512
13513  EVT VT = N->getValueType(0);
13514  SDValue Op = N->getOperand(0);
13515  EVT OpVT = Op.getValueType();
13516  DebugLoc dl = N->getDebugLoc();
13517
13518  if ((VT == MVT::v4i32) && (OpVT == MVT::v4i64)) {
13519
13520    if (Subtarget->hasAVX2()) {
13521      // AVX2: v4i64 -> v4i32
13522
13523      // VPERMD
13524      static const int ShufMask[] = {0, 2, 4, 6, -1, -1, -1, -1};
13525
13526      Op = DAG.getNode(ISD::BITCAST, dl, MVT::v8i32, Op);
13527      Op = DAG.getVectorShuffle(MVT::v8i32, dl, Op, DAG.getUNDEF(MVT::v8i32),
13528                                ShufMask);
13529
13530      return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, Op,
13531                         DAG.getIntPtrConstant(0));
13532    }
13533
13534    // AVX: v4i64 -> v4i32
13535    SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v2i64, Op,
13536                               DAG.getIntPtrConstant(0));
13537
13538    SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v2i64, Op,
13539                               DAG.getIntPtrConstant(2));
13540
13541    OpLo = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, OpLo);
13542    OpHi = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, OpHi);
13543
13544    // PSHUFD
13545    static const int ShufMask1[] = {0, 2, 0, 0};
13546
13547    SDValue Undef = DAG.getUNDEF(VT);
13548    OpLo = DAG.getVectorShuffle(VT, dl, OpLo, Undef, ShufMask1);
13549    OpHi = DAG.getVectorShuffle(VT, dl, OpHi, Undef, ShufMask1);
13550
13551    // MOVLHPS
13552    static const int ShufMask2[] = {0, 1, 4, 5};
13553
13554    return DAG.getVectorShuffle(VT, dl, OpLo, OpHi, ShufMask2);
13555  }
13556
13557  if ((VT == MVT::v8i16) && (OpVT == MVT::v8i32)) {
13558
13559    if (Subtarget->hasAVX2()) {
13560      // AVX2: v8i32 -> v8i16
13561
13562      Op = DAG.getNode(ISD::BITCAST, dl, MVT::v32i8, Op);
13563
13564      // PSHUFB
13565      SmallVector<SDValue,32> pshufbMask;
13566      for (unsigned i = 0; i < 2; ++i) {
13567        pshufbMask.push_back(DAG.getConstant(0x0, MVT::i8));
13568        pshufbMask.push_back(DAG.getConstant(0x1, MVT::i8));
13569        pshufbMask.push_back(DAG.getConstant(0x4, MVT::i8));
13570        pshufbMask.push_back(DAG.getConstant(0x5, MVT::i8));
13571        pshufbMask.push_back(DAG.getConstant(0x8, MVT::i8));
13572        pshufbMask.push_back(DAG.getConstant(0x9, MVT::i8));
13573        pshufbMask.push_back(DAG.getConstant(0xc, MVT::i8));
13574        pshufbMask.push_back(DAG.getConstant(0xd, MVT::i8));
13575        for (unsigned j = 0; j < 8; ++j)
13576          pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
13577      }
13578      SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v32i8,
13579                               &pshufbMask[0], 32);
13580      Op = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v32i8, Op, BV);
13581
13582      Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4i64, Op);
13583
13584      static const int ShufMask[] = {0,  2,  -1,  -1};
13585      Op = DAG.getVectorShuffle(MVT::v4i64, dl,  Op, DAG.getUNDEF(MVT::v4i64),
13586                                &ShufMask[0]);
13587
13588      Op = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v2i64, Op,
13589                       DAG.getIntPtrConstant(0));
13590
13591      return DAG.getNode(ISD::BITCAST, dl, VT, Op);
13592    }
13593
13594    SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i32, Op,
13595                               DAG.getIntPtrConstant(0));
13596
13597    SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i32, Op,
13598                               DAG.getIntPtrConstant(4));
13599
13600    OpLo = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpLo);
13601    OpHi = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpHi);
13602
13603    // PSHUFB
13604    static const int ShufMask1[] = {0,  1,  4,  5,  8,  9, 12, 13,
13605                                   -1, -1, -1, -1, -1, -1, -1, -1};
13606
13607    SDValue Undef = DAG.getUNDEF(MVT::v16i8);
13608    OpLo = DAG.getVectorShuffle(MVT::v16i8, dl, OpLo, Undef, ShufMask1);
13609    OpHi = DAG.getVectorShuffle(MVT::v16i8, dl, OpHi, Undef, ShufMask1);
13610
13611    OpLo = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, OpLo);
13612    OpHi = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, OpHi);
13613
13614    // MOVLHPS
13615    static const int ShufMask2[] = {0, 1, 4, 5};
13616
13617    SDValue res = DAG.getVectorShuffle(MVT::v4i32, dl, OpLo, OpHi, ShufMask2);
13618    return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, res);
13619  }
13620
13621  return SDValue();
13622}
13623
13624/// XFormVExtractWithShuffleIntoLoad - Check if a vector extract from a target
13625/// specific shuffle of a load can be folded into a single element load.
13626/// Similar handling for VECTOR_SHUFFLE is performed by DAGCombiner, but
13627/// shuffles have been customed lowered so we need to handle those here.
13628static SDValue XFormVExtractWithShuffleIntoLoad(SDNode *N, SelectionDAG &DAG,
13629                                         TargetLowering::DAGCombinerInfo &DCI) {
13630  if (DCI.isBeforeLegalizeOps())
13631    return SDValue();
13632
13633  SDValue InVec = N->getOperand(0);
13634  SDValue EltNo = N->getOperand(1);
13635
13636  if (!isa<ConstantSDNode>(EltNo))
13637    return SDValue();
13638
13639  EVT VT = InVec.getValueType();
13640
13641  bool HasShuffleIntoBitcast = false;
13642  if (InVec.getOpcode() == ISD::BITCAST) {
13643    // Don't duplicate a load with other uses.
13644    if (!InVec.hasOneUse())
13645      return SDValue();
13646    EVT BCVT = InVec.getOperand(0).getValueType();
13647    if (BCVT.getVectorNumElements() != VT.getVectorNumElements())
13648      return SDValue();
13649    InVec = InVec.getOperand(0);
13650    HasShuffleIntoBitcast = true;
13651  }
13652
13653  if (!isTargetShuffle(InVec.getOpcode()))
13654    return SDValue();
13655
13656  // Don't duplicate a load with other uses.
13657  if (!InVec.hasOneUse())
13658    return SDValue();
13659
13660  SmallVector<int, 16> ShuffleMask;
13661  bool UnaryShuffle;
13662  if (!getTargetShuffleMask(InVec.getNode(), VT.getSimpleVT(), ShuffleMask,
13663                            UnaryShuffle))
13664    return SDValue();
13665
13666  // Select the input vector, guarding against out of range extract vector.
13667  unsigned NumElems = VT.getVectorNumElements();
13668  int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
13669  int Idx = (Elt > (int)NumElems) ? -1 : ShuffleMask[Elt];
13670  SDValue LdNode = (Idx < (int)NumElems) ? InVec.getOperand(0)
13671                                         : InVec.getOperand(1);
13672
13673  // If inputs to shuffle are the same for both ops, then allow 2 uses
13674  unsigned AllowedUses = InVec.getOperand(0) == InVec.getOperand(1) ? 2 : 1;
13675
13676  if (LdNode.getOpcode() == ISD::BITCAST) {
13677    // Don't duplicate a load with other uses.
13678    if (!LdNode.getNode()->hasNUsesOfValue(AllowedUses, 0))
13679      return SDValue();
13680
13681    AllowedUses = 1; // only allow 1 load use if we have a bitcast
13682    LdNode = LdNode.getOperand(0);
13683  }
13684
13685  if (!ISD::isNormalLoad(LdNode.getNode()))
13686    return SDValue();
13687
13688  LoadSDNode *LN0 = cast<LoadSDNode>(LdNode);
13689
13690  if (!LN0 ||!LN0->hasNUsesOfValue(AllowedUses, 0) || LN0->isVolatile())
13691    return SDValue();
13692
13693  if (HasShuffleIntoBitcast) {
13694    // If there's a bitcast before the shuffle, check if the load type and
13695    // alignment is valid.
13696    unsigned Align = LN0->getAlignment();
13697    const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13698    unsigned NewAlign = TLI.getTargetData()->
13699      getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
13700
13701    if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VT))
13702      return SDValue();
13703  }
13704
13705  // All checks match so transform back to vector_shuffle so that DAG combiner
13706  // can finish the job
13707  DebugLoc dl = N->getDebugLoc();
13708
13709  // Create shuffle node taking into account the case that its a unary shuffle
13710  SDValue Shuffle = (UnaryShuffle) ? DAG.getUNDEF(VT) : InVec.getOperand(1);
13711  Shuffle = DAG.getVectorShuffle(InVec.getValueType(), dl,
13712                                 InVec.getOperand(0), Shuffle,
13713                                 &ShuffleMask[0]);
13714  Shuffle = DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
13715  return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0), Shuffle,
13716                     EltNo);
13717}
13718
13719/// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
13720/// generation and convert it from being a bunch of shuffles and extracts
13721/// to a simple store and scalar loads to extract the elements.
13722static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
13723                                         TargetLowering::DAGCombinerInfo &DCI) {
13724  SDValue NewOp = XFormVExtractWithShuffleIntoLoad(N, DAG, DCI);
13725  if (NewOp.getNode())
13726    return NewOp;
13727
13728  SDValue InputVector = N->getOperand(0);
13729
13730  // Only operate on vectors of 4 elements, where the alternative shuffling
13731  // gets to be more expensive.
13732  if (InputVector.getValueType() != MVT::v4i32)
13733    return SDValue();
13734
13735  // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
13736  // single use which is a sign-extend or zero-extend, and all elements are
13737  // used.
13738  SmallVector<SDNode *, 4> Uses;
13739  unsigned ExtractedElements = 0;
13740  for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
13741       UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
13742    if (UI.getUse().getResNo() != InputVector.getResNo())
13743      return SDValue();
13744
13745    SDNode *Extract = *UI;
13746    if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
13747      return SDValue();
13748
13749    if (Extract->getValueType(0) != MVT::i32)
13750      return SDValue();
13751    if (!Extract->hasOneUse())
13752      return SDValue();
13753    if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
13754        Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
13755      return SDValue();
13756    if (!isa<ConstantSDNode>(Extract->getOperand(1)))
13757      return SDValue();
13758
13759    // Record which element was extracted.
13760    ExtractedElements |=
13761      1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
13762
13763    Uses.push_back(Extract);
13764  }
13765
13766  // If not all the elements were used, this may not be worthwhile.
13767  if (ExtractedElements != 15)
13768    return SDValue();
13769
13770  // Ok, we've now decided to do the transformation.
13771  DebugLoc dl = InputVector.getDebugLoc();
13772
13773  // Store the value to a temporary stack slot.
13774  SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
13775  SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
13776                            MachinePointerInfo(), false, false, 0);
13777
13778  // Replace each use (extract) with a load of the appropriate element.
13779  for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
13780       UE = Uses.end(); UI != UE; ++UI) {
13781    SDNode *Extract = *UI;
13782
13783    // cOMpute the element's address.
13784    SDValue Idx = Extract->getOperand(1);
13785    unsigned EltSize =
13786        InputVector.getValueType().getVectorElementType().getSizeInBits()/8;
13787    uint64_t Offset = EltSize * cast<ConstantSDNode>(Idx)->getZExtValue();
13788    const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13789    SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy());
13790
13791    SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(),
13792                                     StackPtr, OffsetVal);
13793
13794    // Load the scalar.
13795    SDValue LoadScalar = DAG.getLoad(Extract->getValueType(0), dl, Ch,
13796                                     ScalarAddr, MachinePointerInfo(),
13797                                     false, false, false, 0);
13798
13799    // Replace the exact with the load.
13800    DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), LoadScalar);
13801  }
13802
13803  // The replacement was made in place; don't return anything.
13804  return SDValue();
13805}
13806
13807/// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
13808/// nodes.
13809static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
13810                                    TargetLowering::DAGCombinerInfo &DCI,
13811                                    const X86Subtarget *Subtarget) {
13812  DebugLoc DL = N->getDebugLoc();
13813  SDValue Cond = N->getOperand(0);
13814  // Get the LHS/RHS of the select.
13815  SDValue LHS = N->getOperand(1);
13816  SDValue RHS = N->getOperand(2);
13817  EVT VT = LHS.getValueType();
13818
13819  // If we have SSE[12] support, try to form min/max nodes. SSE min/max
13820  // instructions match the semantics of the common C idiom x<y?x:y but not
13821  // x<=y?x:y, because of how they handle negative zero (which can be
13822  // ignored in unsafe-math mode).
13823  if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
13824      VT != MVT::f80 && DAG.getTargetLoweringInfo().isTypeLegal(VT) &&
13825      (Subtarget->hasSSE2() ||
13826       (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
13827    ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
13828
13829    unsigned Opcode = 0;
13830    // Check for x CC y ? x : y.
13831    if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
13832        DAG.isEqualTo(RHS, Cond.getOperand(1))) {
13833      switch (CC) {
13834      default: break;
13835      case ISD::SETULT:
13836        // Converting this to a min would handle NaNs incorrectly, and swapping
13837        // the operands would cause it to handle comparisons between positive
13838        // and negative zero incorrectly.
13839        if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
13840          if (!DAG.getTarget().Options.UnsafeFPMath &&
13841              !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
13842            break;
13843          std::swap(LHS, RHS);
13844        }
13845        Opcode = X86ISD::FMIN;
13846        break;
13847      case ISD::SETOLE:
13848        // Converting this to a min would handle comparisons between positive
13849        // and negative zero incorrectly.
13850        if (!DAG.getTarget().Options.UnsafeFPMath &&
13851            !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
13852          break;
13853        Opcode = X86ISD::FMIN;
13854        break;
13855      case ISD::SETULE:
13856        // Converting this to a min would handle both negative zeros and NaNs
13857        // incorrectly, but we can swap the operands to fix both.
13858        std::swap(LHS, RHS);
13859      case ISD::SETOLT:
13860      case ISD::SETLT:
13861      case ISD::SETLE:
13862        Opcode = X86ISD::FMIN;
13863        break;
13864
13865      case ISD::SETOGE:
13866        // Converting this to a max would handle comparisons between positive
13867        // and negative zero incorrectly.
13868        if (!DAG.getTarget().Options.UnsafeFPMath &&
13869            !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
13870          break;
13871        Opcode = X86ISD::FMAX;
13872        break;
13873      case ISD::SETUGT:
13874        // Converting this to a max would handle NaNs incorrectly, and swapping
13875        // the operands would cause it to handle comparisons between positive
13876        // and negative zero incorrectly.
13877        if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
13878          if (!DAG.getTarget().Options.UnsafeFPMath &&
13879              !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
13880            break;
13881          std::swap(LHS, RHS);
13882        }
13883        Opcode = X86ISD::FMAX;
13884        break;
13885      case ISD::SETUGE:
13886        // Converting this to a max would handle both negative zeros and NaNs
13887        // incorrectly, but we can swap the operands to fix both.
13888        std::swap(LHS, RHS);
13889      case ISD::SETOGT:
13890      case ISD::SETGT:
13891      case ISD::SETGE:
13892        Opcode = X86ISD::FMAX;
13893        break;
13894      }
13895    // Check for x CC y ? y : x -- a min/max with reversed arms.
13896    } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
13897               DAG.isEqualTo(RHS, Cond.getOperand(0))) {
13898      switch (CC) {
13899      default: break;
13900      case ISD::SETOGE:
13901        // Converting this to a min would handle comparisons between positive
13902        // and negative zero incorrectly, and swapping the operands would
13903        // cause it to handle NaNs incorrectly.
13904        if (!DAG.getTarget().Options.UnsafeFPMath &&
13905            !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
13906          if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
13907            break;
13908          std::swap(LHS, RHS);
13909        }
13910        Opcode = X86ISD::FMIN;
13911        break;
13912      case ISD::SETUGT:
13913        // Converting this to a min would handle NaNs incorrectly.
13914        if (!DAG.getTarget().Options.UnsafeFPMath &&
13915            (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
13916          break;
13917        Opcode = X86ISD::FMIN;
13918        break;
13919      case ISD::SETUGE:
13920        // Converting this to a min would handle both negative zeros and NaNs
13921        // incorrectly, but we can swap the operands to fix both.
13922        std::swap(LHS, RHS);
13923      case ISD::SETOGT:
13924      case ISD::SETGT:
13925      case ISD::SETGE:
13926        Opcode = X86ISD::FMIN;
13927        break;
13928
13929      case ISD::SETULT:
13930        // Converting this to a max would handle NaNs incorrectly.
13931        if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
13932          break;
13933        Opcode = X86ISD::FMAX;
13934        break;
13935      case ISD::SETOLE:
13936        // Converting this to a max would handle comparisons between positive
13937        // and negative zero incorrectly, and swapping the operands would
13938        // cause it to handle NaNs incorrectly.
13939        if (!DAG.getTarget().Options.UnsafeFPMath &&
13940            !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
13941          if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
13942            break;
13943          std::swap(LHS, RHS);
13944        }
13945        Opcode = X86ISD::FMAX;
13946        break;
13947      case ISD::SETULE:
13948        // Converting this to a max would handle both negative zeros and NaNs
13949        // incorrectly, but we can swap the operands to fix both.
13950        std::swap(LHS, RHS);
13951      case ISD::SETOLT:
13952      case ISD::SETLT:
13953      case ISD::SETLE:
13954        Opcode = X86ISD::FMAX;
13955        break;
13956      }
13957    }
13958
13959    if (Opcode)
13960      return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
13961  }
13962
13963  // If this is a select between two integer constants, try to do some
13964  // optimizations.
13965  if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
13966    if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
13967      // Don't do this for crazy integer types.
13968      if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
13969        // If this is efficiently invertible, canonicalize the LHSC/RHSC values
13970        // so that TrueC (the true value) is larger than FalseC.
13971        bool NeedsCondInvert = false;
13972
13973        if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
13974            // Efficiently invertible.
13975            (Cond.getOpcode() == ISD::SETCC ||  // setcc -> invertible.
13976             (Cond.getOpcode() == ISD::XOR &&   // xor(X, C) -> invertible.
13977              isa<ConstantSDNode>(Cond.getOperand(1))))) {
13978          NeedsCondInvert = true;
13979          std::swap(TrueC, FalseC);
13980        }
13981
13982        // Optimize C ? 8 : 0 -> zext(C) << 3.  Likewise for any pow2/0.
13983        if (FalseC->getAPIntValue() == 0 &&
13984            TrueC->getAPIntValue().isPowerOf2()) {
13985          if (NeedsCondInvert) // Invert the condition if needed.
13986            Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
13987                               DAG.getConstant(1, Cond.getValueType()));
13988
13989          // Zero extend the condition if needed.
13990          Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
13991
13992          unsigned ShAmt = TrueC->getAPIntValue().logBase2();
13993          return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
13994                             DAG.getConstant(ShAmt, MVT::i8));
13995        }
13996
13997        // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
13998        if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
13999          if (NeedsCondInvert) // Invert the condition if needed.
14000            Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
14001                               DAG.getConstant(1, Cond.getValueType()));
14002
14003          // Zero extend the condition if needed.
14004          Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
14005                             FalseC->getValueType(0), Cond);
14006          return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
14007                             SDValue(FalseC, 0));
14008        }
14009
14010        // Optimize cases that will turn into an LEA instruction.  This requires
14011        // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
14012        if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
14013          uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
14014          if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
14015
14016          bool isFastMultiplier = false;
14017          if (Diff < 10) {
14018            switch ((unsigned char)Diff) {
14019              default: break;
14020              case 1:  // result = add base, cond
14021              case 2:  // result = lea base(    , cond*2)
14022              case 3:  // result = lea base(cond, cond*2)
14023              case 4:  // result = lea base(    , cond*4)
14024              case 5:  // result = lea base(cond, cond*4)
14025              case 8:  // result = lea base(    , cond*8)
14026              case 9:  // result = lea base(cond, cond*8)
14027                isFastMultiplier = true;
14028                break;
14029            }
14030          }
14031
14032          if (isFastMultiplier) {
14033            APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
14034            if (NeedsCondInvert) // Invert the condition if needed.
14035              Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
14036                                 DAG.getConstant(1, Cond.getValueType()));
14037
14038            // Zero extend the condition if needed.
14039            Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
14040                               Cond);
14041            // Scale the condition by the difference.
14042            if (Diff != 1)
14043              Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
14044                                 DAG.getConstant(Diff, Cond.getValueType()));
14045
14046            // Add the base if non-zero.
14047            if (FalseC->getAPIntValue() != 0)
14048              Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
14049                                 SDValue(FalseC, 0));
14050            return Cond;
14051          }
14052        }
14053      }
14054  }
14055
14056  // Canonicalize max and min:
14057  // (x > y) ? x : y -> (x >= y) ? x : y
14058  // (x < y) ? x : y -> (x <= y) ? x : y
14059  // This allows use of COND_S / COND_NS (see TranslateX86CC) which eliminates
14060  // the need for an extra compare
14061  // against zero. e.g.
14062  // (x - y) > 0 : (x - y) ? 0 -> (x - y) >= 0 : (x - y) ? 0
14063  // subl   %esi, %edi
14064  // testl  %edi, %edi
14065  // movl   $0, %eax
14066  // cmovgl %edi, %eax
14067  // =>
14068  // xorl   %eax, %eax
14069  // subl   %esi, $edi
14070  // cmovsl %eax, %edi
14071  if (N->getOpcode() == ISD::SELECT && Cond.getOpcode() == ISD::SETCC &&
14072      DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
14073      DAG.isEqualTo(RHS, Cond.getOperand(1))) {
14074    ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
14075    switch (CC) {
14076    default: break;
14077    case ISD::SETLT:
14078    case ISD::SETGT: {
14079      ISD::CondCode NewCC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGE;
14080      Cond = DAG.getSetCC(Cond.getDebugLoc(), Cond.getValueType(),
14081                          Cond.getOperand(0), Cond.getOperand(1), NewCC);
14082      return DAG.getNode(ISD::SELECT, DL, VT, Cond, LHS, RHS);
14083    }
14084    }
14085  }
14086
14087  // If we know that this node is legal then we know that it is going to be
14088  // matched by one of the SSE/AVX BLEND instructions. These instructions only
14089  // depend on the highest bit in each word. Try to use SimplifyDemandedBits
14090  // to simplify previous instructions.
14091  const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14092  if (N->getOpcode() == ISD::VSELECT && DCI.isBeforeLegalizeOps() &&
14093      !DCI.isBeforeLegalize() && TLI.isOperationLegal(ISD::VSELECT, VT)) {
14094    unsigned BitWidth = Cond.getValueType().getScalarType().getSizeInBits();
14095
14096    // Don't optimize vector selects that map to mask-registers.
14097    if (BitWidth == 1)
14098      return SDValue();
14099
14100    assert(BitWidth >= 8 && BitWidth <= 64 && "Invalid mask size");
14101    APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 1);
14102
14103    APInt KnownZero, KnownOne;
14104    TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
14105                                          DCI.isBeforeLegalizeOps());
14106    if (TLO.ShrinkDemandedConstant(Cond, DemandedMask) ||
14107        TLI.SimplifyDemandedBits(Cond, DemandedMask, KnownZero, KnownOne, TLO))
14108      DCI.CommitTargetLoweringOpt(TLO);
14109  }
14110
14111  return SDValue();
14112}
14113
14114// Check whether a boolean test is testing a boolean value generated by
14115// X86ISD::SETCC. If so, return the operand of that SETCC and proper condition
14116// code.
14117//
14118// Simplify the following patterns:
14119// (Op (CMP (SETCC Cond EFLAGS) 1) EQ) or
14120// (Op (CMP (SETCC Cond EFLAGS) 0) NEQ)
14121// to (Op EFLAGS Cond)
14122//
14123// (Op (CMP (SETCC Cond EFLAGS) 0) EQ) or
14124// (Op (CMP (SETCC Cond EFLAGS) 1) NEQ)
14125// to (Op EFLAGS !Cond)
14126//
14127// where Op could be BRCOND or CMOV.
14128//
14129static SDValue checkBoolTestSetCCCombine(SDValue Cmp, X86::CondCode &CC) {
14130  // Quit if not CMP and SUB with its value result used.
14131  if (Cmp.getOpcode() != X86ISD::CMP &&
14132      (Cmp.getOpcode() != X86ISD::SUB || Cmp.getNode()->hasAnyUseOfValue(0)))
14133      return SDValue();
14134
14135  // Quit if not used as a boolean value.
14136  if (CC != X86::COND_E && CC != X86::COND_NE)
14137    return SDValue();
14138
14139  // Check CMP operands. One of them should be 0 or 1 and the other should be
14140  // an SetCC or extended from it.
14141  SDValue Op1 = Cmp.getOperand(0);
14142  SDValue Op2 = Cmp.getOperand(1);
14143
14144  SDValue SetCC;
14145  const ConstantSDNode* C = 0;
14146  bool needOppositeCond = (CC == X86::COND_E);
14147
14148  if ((C = dyn_cast<ConstantSDNode>(Op1)))
14149    SetCC = Op2;
14150  else if ((C = dyn_cast<ConstantSDNode>(Op2)))
14151    SetCC = Op1;
14152  else // Quit if all operands are not constants.
14153    return SDValue();
14154
14155  if (C->getZExtValue() == 1)
14156    needOppositeCond = !needOppositeCond;
14157  else if (C->getZExtValue() != 0)
14158    // Quit if the constant is neither 0 or 1.
14159    return SDValue();
14160
14161  // Skip 'zext' node.
14162  if (SetCC.getOpcode() == ISD::ZERO_EXTEND)
14163    SetCC = SetCC.getOperand(0);
14164
14165  switch (SetCC.getOpcode()) {
14166  case X86ISD::SETCC:
14167    // Set the condition code or opposite one if necessary.
14168    CC = X86::CondCode(SetCC.getConstantOperandVal(0));
14169    if (needOppositeCond)
14170      CC = X86::GetOppositeBranchCondition(CC);
14171    return SetCC.getOperand(1);
14172  case X86ISD::CMOV: {
14173    // Check whether false/true value has canonical one, i.e. 0 or 1.
14174    ConstantSDNode *FVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(0));
14175    ConstantSDNode *TVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(1));
14176    // Quit if true value is not a constant.
14177    if (!TVal)
14178      return SDValue();
14179    // Quit if false value is not a constant.
14180    if (!FVal) {
14181      // A special case for rdrand, where 0 is set if false cond is found.
14182      SDValue Op = SetCC.getOperand(0);
14183      if (Op.getOpcode() != X86ISD::RDRAND)
14184        return SDValue();
14185    }
14186    // Quit if false value is not the constant 0 or 1.
14187    bool FValIsFalse = true;
14188    if (FVal && FVal->getZExtValue() != 0) {
14189      if (FVal->getZExtValue() != 1)
14190        return SDValue();
14191      // If FVal is 1, opposite cond is needed.
14192      needOppositeCond = !needOppositeCond;
14193      FValIsFalse = false;
14194    }
14195    // Quit if TVal is not the constant opposite of FVal.
14196    if (FValIsFalse && TVal->getZExtValue() != 1)
14197      return SDValue();
14198    if (!FValIsFalse && TVal->getZExtValue() != 0)
14199      return SDValue();
14200    CC = X86::CondCode(SetCC.getConstantOperandVal(2));
14201    if (needOppositeCond)
14202      CC = X86::GetOppositeBranchCondition(CC);
14203    return SetCC.getOperand(3);
14204  }
14205  }
14206
14207  return SDValue();
14208}
14209
14210/// checkFlaggedOrCombine - DAG combination on X86ISD::OR, i.e. with EFLAGS
14211/// updated. If only flag result is used and the result is evaluated from a
14212/// series of element extraction, try to combine it into a PTEST.
14213static SDValue checkFlaggedOrCombine(SDValue Or, X86::CondCode &CC,
14214                                     SelectionDAG &DAG,
14215                                     const X86Subtarget *Subtarget) {
14216  SDNode *N = Or.getNode();
14217  DebugLoc DL = N->getDebugLoc();
14218
14219  // Only SSE4.1 and beyond supports PTEST or like.
14220  if (!Subtarget->hasSSE41())
14221    return SDValue();
14222
14223  if (N->getOpcode() != X86ISD::OR)
14224    return SDValue();
14225
14226  // Quit if the value result of OR is used.
14227  if (N->hasAnyUseOfValue(0))
14228    return SDValue();
14229
14230  // Quit if not used as a boolean value.
14231  if (CC != X86::COND_E && CC != X86::COND_NE)
14232    return SDValue();
14233
14234  SmallVector<SDValue, 8> Opnds;
14235  SDValue VecIn;
14236  EVT VT = MVT::Other;
14237  unsigned Mask = 0;
14238
14239  // Recognize a special case where a vector is casted into wide integer to
14240  // test all 0s.
14241  Opnds.push_back(N->getOperand(0));
14242  Opnds.push_back(N->getOperand(1));
14243
14244  for (unsigned Slot = 0, e = Opnds.size(); Slot < e; ++Slot) {
14245    SmallVector<SDValue, 8>::const_iterator I = Opnds.begin() + Slot;
14246    // BFS traverse all OR'd operands.
14247    if (I->getOpcode() == ISD::OR) {
14248      Opnds.push_back(I->getOperand(0));
14249      Opnds.push_back(I->getOperand(1));
14250      // Re-evaluate the number of nodes to be traversed.
14251      e += 2; // 2 more nodes (LHS and RHS) are pushed.
14252      continue;
14253    }
14254
14255    // Quit if a non-EXTRACT_VECTOR_ELT
14256    if (I->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
14257      return SDValue();
14258
14259    // Quit if without a constant index.
14260    SDValue Idx = I->getOperand(1);
14261    if (!isa<ConstantSDNode>(Idx))
14262      return SDValue();
14263
14264    // Check if all elements are extracted from the same vector.
14265    SDValue ExtractedFromVec = I->getOperand(0);
14266    if (VecIn.getNode() == 0) {
14267      VT = ExtractedFromVec.getValueType();
14268      // FIXME: only 128-bit vector is supported so far.
14269      if (!VT.is128BitVector())
14270        return SDValue();
14271      VecIn = ExtractedFromVec;
14272    } else if (VecIn != ExtractedFromVec)
14273      return SDValue();
14274
14275    // Record the constant index.
14276    Mask |= 1U << cast<ConstantSDNode>(Idx)->getZExtValue();
14277  }
14278
14279  assert(VT.is128BitVector() && "Only 128-bit vector PTEST is supported so far.");
14280
14281  // Quit if not all elements are used.
14282  if (Mask != (1U << VT.getVectorNumElements()) - 1U)
14283    return SDValue();
14284
14285  return DAG.getNode(X86ISD::PTEST, DL, MVT::i32, VecIn, VecIn);
14286}
14287
14288/// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
14289static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
14290                                  TargetLowering::DAGCombinerInfo &DCI,
14291                                  const X86Subtarget *Subtarget) {
14292  DebugLoc DL = N->getDebugLoc();
14293
14294  // If the flag operand isn't dead, don't touch this CMOV.
14295  if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
14296    return SDValue();
14297
14298  SDValue FalseOp = N->getOperand(0);
14299  SDValue TrueOp = N->getOperand(1);
14300  X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
14301  SDValue Cond = N->getOperand(3);
14302
14303  if (CC == X86::COND_E || CC == X86::COND_NE) {
14304    switch (Cond.getOpcode()) {
14305    default: break;
14306    case X86ISD::BSR:
14307    case X86ISD::BSF:
14308      // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
14309      if (DAG.isKnownNeverZero(Cond.getOperand(0)))
14310        return (CC == X86::COND_E) ? FalseOp : TrueOp;
14311    }
14312  }
14313
14314  SDValue Flags;
14315
14316  Flags = checkBoolTestSetCCCombine(Cond, CC);
14317  if (Flags.getNode() &&
14318      // Extra check as FCMOV only supports a subset of X86 cond.
14319      (FalseOp.getValueType() != MVT::f80 || hasFPCMov(CC))) {
14320    SDValue Ops[] = { FalseOp, TrueOp,
14321                      DAG.getConstant(CC, MVT::i8), Flags };
14322    return DAG.getNode(X86ISD::CMOV, DL, N->getVTList(),
14323                       Ops, array_lengthof(Ops));
14324  }
14325
14326  Flags = checkFlaggedOrCombine(Cond, CC, DAG, Subtarget);
14327  if (Flags.getNode()) {
14328    SDValue Ops[] = { FalseOp, TrueOp,
14329                      DAG.getConstant(CC, MVT::i8), Flags };
14330    return DAG.getNode(X86ISD::CMOV, DL, N->getVTList(),
14331                       Ops, array_lengthof(Ops));
14332  }
14333
14334  // If this is a select between two integer constants, try to do some
14335  // optimizations.  Note that the operands are ordered the opposite of SELECT
14336  // operands.
14337  if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
14338    if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
14339      // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
14340      // larger than FalseC (the false value).
14341      if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
14342        CC = X86::GetOppositeBranchCondition(CC);
14343        std::swap(TrueC, FalseC);
14344      }
14345
14346      // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3.  Likewise for any pow2/0.
14347      // This is efficient for any integer data type (including i8/i16) and
14348      // shift amount.
14349      if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
14350        Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
14351                           DAG.getConstant(CC, MVT::i8), Cond);
14352
14353        // Zero extend the condition if needed.
14354        Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
14355
14356        unsigned ShAmt = TrueC->getAPIntValue().logBase2();
14357        Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
14358                           DAG.getConstant(ShAmt, MVT::i8));
14359        if (N->getNumValues() == 2)  // Dead flag value?
14360          return DCI.CombineTo(N, Cond, SDValue());
14361        return Cond;
14362      }
14363
14364      // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.  This is efficient
14365      // for any integer data type, including i8/i16.
14366      if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
14367        Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
14368                           DAG.getConstant(CC, MVT::i8), Cond);
14369
14370        // Zero extend the condition if needed.
14371        Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
14372                           FalseC->getValueType(0), Cond);
14373        Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
14374                           SDValue(FalseC, 0));
14375
14376        if (N->getNumValues() == 2)  // Dead flag value?
14377          return DCI.CombineTo(N, Cond, SDValue());
14378        return Cond;
14379      }
14380
14381      // Optimize cases that will turn into an LEA instruction.  This requires
14382      // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
14383      if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
14384        uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
14385        if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
14386
14387        bool isFastMultiplier = false;
14388        if (Diff < 10) {
14389          switch ((unsigned char)Diff) {
14390          default: break;
14391          case 1:  // result = add base, cond
14392          case 2:  // result = lea base(    , cond*2)
14393          case 3:  // result = lea base(cond, cond*2)
14394          case 4:  // result = lea base(    , cond*4)
14395          case 5:  // result = lea base(cond, cond*4)
14396          case 8:  // result = lea base(    , cond*8)
14397          case 9:  // result = lea base(cond, cond*8)
14398            isFastMultiplier = true;
14399            break;
14400          }
14401        }
14402
14403        if (isFastMultiplier) {
14404          APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
14405          Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
14406                             DAG.getConstant(CC, MVT::i8), Cond);
14407          // Zero extend the condition if needed.
14408          Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
14409                             Cond);
14410          // Scale the condition by the difference.
14411          if (Diff != 1)
14412            Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
14413                               DAG.getConstant(Diff, Cond.getValueType()));
14414
14415          // Add the base if non-zero.
14416          if (FalseC->getAPIntValue() != 0)
14417            Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
14418                               SDValue(FalseC, 0));
14419          if (N->getNumValues() == 2)  // Dead flag value?
14420            return DCI.CombineTo(N, Cond, SDValue());
14421          return Cond;
14422        }
14423      }
14424    }
14425  }
14426  return SDValue();
14427}
14428
14429
14430/// PerformMulCombine - Optimize a single multiply with constant into two
14431/// in order to implement it with two cheaper instructions, e.g.
14432/// LEA + SHL, LEA + LEA.
14433static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
14434                                 TargetLowering::DAGCombinerInfo &DCI) {
14435  if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
14436    return SDValue();
14437
14438  EVT VT = N->getValueType(0);
14439  if (VT != MVT::i64)
14440    return SDValue();
14441
14442  ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
14443  if (!C)
14444    return SDValue();
14445  uint64_t MulAmt = C->getZExtValue();
14446  if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
14447    return SDValue();
14448
14449  uint64_t MulAmt1 = 0;
14450  uint64_t MulAmt2 = 0;
14451  if ((MulAmt % 9) == 0) {
14452    MulAmt1 = 9;
14453    MulAmt2 = MulAmt / 9;
14454  } else if ((MulAmt % 5) == 0) {
14455    MulAmt1 = 5;
14456    MulAmt2 = MulAmt / 5;
14457  } else if ((MulAmt % 3) == 0) {
14458    MulAmt1 = 3;
14459    MulAmt2 = MulAmt / 3;
14460  }
14461  if (MulAmt2 &&
14462      (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
14463    DebugLoc DL = N->getDebugLoc();
14464
14465    if (isPowerOf2_64(MulAmt2) &&
14466        !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
14467      // If second multiplifer is pow2, issue it first. We want the multiply by
14468      // 3, 5, or 9 to be folded into the addressing mode unless the lone use
14469      // is an add.
14470      std::swap(MulAmt1, MulAmt2);
14471
14472    SDValue NewMul;
14473    if (isPowerOf2_64(MulAmt1))
14474      NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
14475                           DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
14476    else
14477      NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
14478                           DAG.getConstant(MulAmt1, VT));
14479
14480    if (isPowerOf2_64(MulAmt2))
14481      NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
14482                           DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
14483    else
14484      NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
14485                           DAG.getConstant(MulAmt2, VT));
14486
14487    // Do not add new nodes to DAG combiner worklist.
14488    DCI.CombineTo(N, NewMul, false);
14489  }
14490  return SDValue();
14491}
14492
14493static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
14494  SDValue N0 = N->getOperand(0);
14495  SDValue N1 = N->getOperand(1);
14496  ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
14497  EVT VT = N0.getValueType();
14498
14499  // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
14500  // since the result of setcc_c is all zero's or all ones.
14501  if (VT.isInteger() && !VT.isVector() &&
14502      N1C && N0.getOpcode() == ISD::AND &&
14503      N0.getOperand(1).getOpcode() == ISD::Constant) {
14504    SDValue N00 = N0.getOperand(0);
14505    if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
14506        ((N00.getOpcode() == ISD::ANY_EXTEND ||
14507          N00.getOpcode() == ISD::ZERO_EXTEND) &&
14508         N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
14509      APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
14510      APInt ShAmt = N1C->getAPIntValue();
14511      Mask = Mask.shl(ShAmt);
14512      if (Mask != 0)
14513        return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
14514                           N00, DAG.getConstant(Mask, VT));
14515    }
14516  }
14517
14518
14519  // Hardware support for vector shifts is sparse which makes us scalarize the
14520  // vector operations in many cases. Also, on sandybridge ADD is faster than
14521  // shl.
14522  // (shl V, 1) -> add V,V
14523  if (isSplatVector(N1.getNode())) {
14524    assert(N0.getValueType().isVector() && "Invalid vector shift type");
14525    ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1->getOperand(0));
14526    // We shift all of the values by one. In many cases we do not have
14527    // hardware support for this operation. This is better expressed as an ADD
14528    // of two values.
14529    if (N1C && (1 == N1C->getZExtValue())) {
14530      return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, N0, N0);
14531    }
14532  }
14533
14534  return SDValue();
14535}
14536
14537/// PerformShiftCombine - Transforms vector shift nodes to use vector shifts
14538///                       when possible.
14539static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
14540                                   TargetLowering::DAGCombinerInfo &DCI,
14541                                   const X86Subtarget *Subtarget) {
14542  EVT VT = N->getValueType(0);
14543  if (N->getOpcode() == ISD::SHL) {
14544    SDValue V = PerformSHLCombine(N, DAG);
14545    if (V.getNode()) return V;
14546  }
14547
14548  // On X86 with SSE2 support, we can transform this to a vector shift if
14549  // all elements are shifted by the same amount.  We can't do this in legalize
14550  // because the a constant vector is typically transformed to a constant pool
14551  // so we have no knowledge of the shift amount.
14552  if (!Subtarget->hasSSE2())
14553    return SDValue();
14554
14555  if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16 &&
14556      (!Subtarget->hasAVX2() ||
14557       (VT != MVT::v4i64 && VT != MVT::v8i32 && VT != MVT::v16i16)))
14558    return SDValue();
14559
14560  SDValue ShAmtOp = N->getOperand(1);
14561  EVT EltVT = VT.getVectorElementType();
14562  DebugLoc DL = N->getDebugLoc();
14563  SDValue BaseShAmt = SDValue();
14564  if (ShAmtOp.getOpcode() == ISD::BUILD_VECTOR) {
14565    unsigned NumElts = VT.getVectorNumElements();
14566    unsigned i = 0;
14567    for (; i != NumElts; ++i) {
14568      SDValue Arg = ShAmtOp.getOperand(i);
14569      if (Arg.getOpcode() == ISD::UNDEF) continue;
14570      BaseShAmt = Arg;
14571      break;
14572    }
14573    // Handle the case where the build_vector is all undef
14574    // FIXME: Should DAG allow this?
14575    if (i == NumElts)
14576      return SDValue();
14577
14578    for (; i != NumElts; ++i) {
14579      SDValue Arg = ShAmtOp.getOperand(i);
14580      if (Arg.getOpcode() == ISD::UNDEF) continue;
14581      if (Arg != BaseShAmt) {
14582        return SDValue();
14583      }
14584    }
14585  } else if (ShAmtOp.getOpcode() == ISD::VECTOR_SHUFFLE &&
14586             cast<ShuffleVectorSDNode>(ShAmtOp)->isSplat()) {
14587    SDValue InVec = ShAmtOp.getOperand(0);
14588    if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
14589      unsigned NumElts = InVec.getValueType().getVectorNumElements();
14590      unsigned i = 0;
14591      for (; i != NumElts; ++i) {
14592        SDValue Arg = InVec.getOperand(i);
14593        if (Arg.getOpcode() == ISD::UNDEF) continue;
14594        BaseShAmt = Arg;
14595        break;
14596      }
14597    } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
14598       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
14599         unsigned SplatIdx= cast<ShuffleVectorSDNode>(ShAmtOp)->getSplatIndex();
14600         if (C->getZExtValue() == SplatIdx)
14601           BaseShAmt = InVec.getOperand(1);
14602       }
14603    }
14604    if (BaseShAmt.getNode() == 0) {
14605      // Don't create instructions with illegal types after legalize
14606      // types has run.
14607      if (!DAG.getTargetLoweringInfo().isTypeLegal(EltVT) &&
14608          !DCI.isBeforeLegalize())
14609        return SDValue();
14610
14611      BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, ShAmtOp,
14612                              DAG.getIntPtrConstant(0));
14613    }
14614  } else
14615    return SDValue();
14616
14617  // The shift amount is an i32.
14618  if (EltVT.bitsGT(MVT::i32))
14619    BaseShAmt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, BaseShAmt);
14620  else if (EltVT.bitsLT(MVT::i32))
14621    BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, BaseShAmt);
14622
14623  // The shift amount is identical so we can do a vector shift.
14624  SDValue  ValOp = N->getOperand(0);
14625  switch (N->getOpcode()) {
14626  default:
14627    llvm_unreachable("Unknown shift opcode!");
14628  case ISD::SHL:
14629    switch (VT.getSimpleVT().SimpleTy) {
14630    default: return SDValue();
14631    case MVT::v2i64:
14632    case MVT::v4i32:
14633    case MVT::v8i16:
14634    case MVT::v4i64:
14635    case MVT::v8i32:
14636    case MVT::v16i16:
14637      return getTargetVShiftNode(X86ISD::VSHLI, DL, VT, ValOp, BaseShAmt, DAG);
14638    }
14639  case ISD::SRA:
14640    switch (VT.getSimpleVT().SimpleTy) {
14641    default: return SDValue();
14642    case MVT::v4i32:
14643    case MVT::v8i16:
14644    case MVT::v8i32:
14645    case MVT::v16i16:
14646      return getTargetVShiftNode(X86ISD::VSRAI, DL, VT, ValOp, BaseShAmt, DAG);
14647    }
14648  case ISD::SRL:
14649    switch (VT.getSimpleVT().SimpleTy) {
14650    default: return SDValue();
14651    case MVT::v2i64:
14652    case MVT::v4i32:
14653    case MVT::v8i16:
14654    case MVT::v4i64:
14655    case MVT::v8i32:
14656    case MVT::v16i16:
14657      return getTargetVShiftNode(X86ISD::VSRLI, DL, VT, ValOp, BaseShAmt, DAG);
14658    }
14659  }
14660}
14661
14662
14663// CMPEQCombine - Recognize the distinctive  (AND (setcc ...) (setcc ..))
14664// where both setccs reference the same FP CMP, and rewrite for CMPEQSS
14665// and friends.  Likewise for OR -> CMPNEQSS.
14666static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
14667                            TargetLowering::DAGCombinerInfo &DCI,
14668                            const X86Subtarget *Subtarget) {
14669  unsigned opcode;
14670
14671  // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
14672  // we're requiring SSE2 for both.
14673  if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
14674    SDValue N0 = N->getOperand(0);
14675    SDValue N1 = N->getOperand(1);
14676    SDValue CMP0 = N0->getOperand(1);
14677    SDValue CMP1 = N1->getOperand(1);
14678    DebugLoc DL = N->getDebugLoc();
14679
14680    // The SETCCs should both refer to the same CMP.
14681    if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
14682      return SDValue();
14683
14684    SDValue CMP00 = CMP0->getOperand(0);
14685    SDValue CMP01 = CMP0->getOperand(1);
14686    EVT     VT    = CMP00.getValueType();
14687
14688    if (VT == MVT::f32 || VT == MVT::f64) {
14689      bool ExpectingFlags = false;
14690      // Check for any users that want flags:
14691      for (SDNode::use_iterator UI = N->use_begin(),
14692             UE = N->use_end();
14693           !ExpectingFlags && UI != UE; ++UI)
14694        switch (UI->getOpcode()) {
14695        default:
14696        case ISD::BR_CC:
14697        case ISD::BRCOND:
14698        case ISD::SELECT:
14699          ExpectingFlags = true;
14700          break;
14701        case ISD::CopyToReg:
14702        case ISD::SIGN_EXTEND:
14703        case ISD::ZERO_EXTEND:
14704        case ISD::ANY_EXTEND:
14705          break;
14706        }
14707
14708      if (!ExpectingFlags) {
14709        enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
14710        enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
14711
14712        if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
14713          X86::CondCode tmp = cc0;
14714          cc0 = cc1;
14715          cc1 = tmp;
14716        }
14717
14718        if ((cc0 == X86::COND_E  && cc1 == X86::COND_NP) ||
14719            (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
14720          bool is64BitFP = (CMP00.getValueType() == MVT::f64);
14721          X86ISD::NodeType NTOperator = is64BitFP ?
14722            X86ISD::FSETCCsd : X86ISD::FSETCCss;
14723          // FIXME: need symbolic constants for these magic numbers.
14724          // See X86ATTInstPrinter.cpp:printSSECC().
14725          unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
14726          SDValue OnesOrZeroesF = DAG.getNode(NTOperator, DL, MVT::f32, CMP00, CMP01,
14727                                              DAG.getConstant(x86cc, MVT::i8));
14728          SDValue OnesOrZeroesI = DAG.getNode(ISD::BITCAST, DL, MVT::i32,
14729                                              OnesOrZeroesF);
14730          SDValue ANDed = DAG.getNode(ISD::AND, DL, MVT::i32, OnesOrZeroesI,
14731                                      DAG.getConstant(1, MVT::i32));
14732          SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8, ANDed);
14733          return OneBitOfTruth;
14734        }
14735      }
14736    }
14737  }
14738  return SDValue();
14739}
14740
14741/// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
14742/// so it can be folded inside ANDNP.
14743static bool CanFoldXORWithAllOnes(const SDNode *N) {
14744  EVT VT = N->getValueType(0);
14745
14746  // Match direct AllOnes for 128 and 256-bit vectors
14747  if (ISD::isBuildVectorAllOnes(N))
14748    return true;
14749
14750  // Look through a bit convert.
14751  if (N->getOpcode() == ISD::BITCAST)
14752    N = N->getOperand(0).getNode();
14753
14754  // Sometimes the operand may come from a insert_subvector building a 256-bit
14755  // allones vector
14756  if (VT.is256BitVector() &&
14757      N->getOpcode() == ISD::INSERT_SUBVECTOR) {
14758    SDValue V1 = N->getOperand(0);
14759    SDValue V2 = N->getOperand(1);
14760
14761    if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
14762        V1.getOperand(0).getOpcode() == ISD::UNDEF &&
14763        ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
14764        ISD::isBuildVectorAllOnes(V2.getNode()))
14765      return true;
14766  }
14767
14768  return false;
14769}
14770
14771static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
14772                                 TargetLowering::DAGCombinerInfo &DCI,
14773                                 const X86Subtarget *Subtarget) {
14774  if (DCI.isBeforeLegalizeOps())
14775    return SDValue();
14776
14777  SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
14778  if (R.getNode())
14779    return R;
14780
14781  EVT VT = N->getValueType(0);
14782
14783  // Create ANDN, BLSI, and BLSR instructions
14784  // BLSI is X & (-X)
14785  // BLSR is X & (X-1)
14786  if (Subtarget->hasBMI() && (VT == MVT::i32 || VT == MVT::i64)) {
14787    SDValue N0 = N->getOperand(0);
14788    SDValue N1 = N->getOperand(1);
14789    DebugLoc DL = N->getDebugLoc();
14790
14791    // Check LHS for not
14792    if (N0.getOpcode() == ISD::XOR && isAllOnes(N0.getOperand(1)))
14793      return DAG.getNode(X86ISD::ANDN, DL, VT, N0.getOperand(0), N1);
14794    // Check RHS for not
14795    if (N1.getOpcode() == ISD::XOR && isAllOnes(N1.getOperand(1)))
14796      return DAG.getNode(X86ISD::ANDN, DL, VT, N1.getOperand(0), N0);
14797
14798    // Check LHS for neg
14799    if (N0.getOpcode() == ISD::SUB && N0.getOperand(1) == N1 &&
14800        isZero(N0.getOperand(0)))
14801      return DAG.getNode(X86ISD::BLSI, DL, VT, N1);
14802
14803    // Check RHS for neg
14804    if (N1.getOpcode() == ISD::SUB && N1.getOperand(1) == N0 &&
14805        isZero(N1.getOperand(0)))
14806      return DAG.getNode(X86ISD::BLSI, DL, VT, N0);
14807
14808    // Check LHS for X-1
14809    if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1 &&
14810        isAllOnes(N0.getOperand(1)))
14811      return DAG.getNode(X86ISD::BLSR, DL, VT, N1);
14812
14813    // Check RHS for X-1
14814    if (N1.getOpcode() == ISD::ADD && N1.getOperand(0) == N0 &&
14815        isAllOnes(N1.getOperand(1)))
14816      return DAG.getNode(X86ISD::BLSR, DL, VT, N0);
14817
14818    return SDValue();
14819  }
14820
14821  // Want to form ANDNP nodes:
14822  // 1) In the hopes of then easily combining them with OR and AND nodes
14823  //    to form PBLEND/PSIGN.
14824  // 2) To match ANDN packed intrinsics
14825  if (VT != MVT::v2i64 && VT != MVT::v4i64)
14826    return SDValue();
14827
14828  SDValue N0 = N->getOperand(0);
14829  SDValue N1 = N->getOperand(1);
14830  DebugLoc DL = N->getDebugLoc();
14831
14832  // Check LHS for vnot
14833  if (N0.getOpcode() == ISD::XOR &&
14834      //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
14835      CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
14836    return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
14837
14838  // Check RHS for vnot
14839  if (N1.getOpcode() == ISD::XOR &&
14840      //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
14841      CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
14842    return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
14843
14844  return SDValue();
14845}
14846
14847static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
14848                                TargetLowering::DAGCombinerInfo &DCI,
14849                                const X86Subtarget *Subtarget) {
14850  if (DCI.isBeforeLegalizeOps())
14851    return SDValue();
14852
14853  SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
14854  if (R.getNode())
14855    return R;
14856
14857  EVT VT = N->getValueType(0);
14858
14859  SDValue N0 = N->getOperand(0);
14860  SDValue N1 = N->getOperand(1);
14861
14862  // look for psign/blend
14863  if (VT == MVT::v2i64 || VT == MVT::v4i64) {
14864    if (!Subtarget->hasSSSE3() ||
14865        (VT == MVT::v4i64 && !Subtarget->hasAVX2()))
14866      return SDValue();
14867
14868    // Canonicalize pandn to RHS
14869    if (N0.getOpcode() == X86ISD::ANDNP)
14870      std::swap(N0, N1);
14871    // or (and (m, y), (pandn m, x))
14872    if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
14873      SDValue Mask = N1.getOperand(0);
14874      SDValue X    = N1.getOperand(1);
14875      SDValue Y;
14876      if (N0.getOperand(0) == Mask)
14877        Y = N0.getOperand(1);
14878      if (N0.getOperand(1) == Mask)
14879        Y = N0.getOperand(0);
14880
14881      // Check to see if the mask appeared in both the AND and ANDNP and
14882      if (!Y.getNode())
14883        return SDValue();
14884
14885      // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
14886      // Look through mask bitcast.
14887      if (Mask.getOpcode() == ISD::BITCAST)
14888        Mask = Mask.getOperand(0);
14889      if (X.getOpcode() == ISD::BITCAST)
14890        X = X.getOperand(0);
14891      if (Y.getOpcode() == ISD::BITCAST)
14892        Y = Y.getOperand(0);
14893
14894      EVT MaskVT = Mask.getValueType();
14895
14896      // Validate that the Mask operand is a vector sra node.
14897      // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
14898      // there is no psrai.b
14899      if (Mask.getOpcode() != X86ISD::VSRAI)
14900        return SDValue();
14901
14902      // Check that the SRA is all signbits.
14903      SDValue SraC = Mask.getOperand(1);
14904      unsigned SraAmt  = cast<ConstantSDNode>(SraC)->getZExtValue();
14905      unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
14906      if ((SraAmt + 1) != EltBits)
14907        return SDValue();
14908
14909      DebugLoc DL = N->getDebugLoc();
14910
14911      // Now we know we at least have a plendvb with the mask val.  See if
14912      // we can form a psignb/w/d.
14913      // psign = x.type == y.type == mask.type && y = sub(0, x);
14914      if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
14915          ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
14916          X.getValueType() == MaskVT && Y.getValueType() == MaskVT) {
14917        assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
14918               "Unsupported VT for PSIGN");
14919        Mask = DAG.getNode(X86ISD::PSIGN, DL, MaskVT, X, Mask.getOperand(0));
14920        return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
14921      }
14922      // PBLENDVB only available on SSE 4.1
14923      if (!Subtarget->hasSSE41())
14924        return SDValue();
14925
14926      EVT BlendVT = (VT == MVT::v4i64) ? MVT::v32i8 : MVT::v16i8;
14927
14928      X = DAG.getNode(ISD::BITCAST, DL, BlendVT, X);
14929      Y = DAG.getNode(ISD::BITCAST, DL, BlendVT, Y);
14930      Mask = DAG.getNode(ISD::BITCAST, DL, BlendVT, Mask);
14931      Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, Y, X);
14932      return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
14933    }
14934  }
14935
14936  if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
14937    return SDValue();
14938
14939  // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
14940  if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
14941    std::swap(N0, N1);
14942  if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
14943    return SDValue();
14944  if (!N0.hasOneUse() || !N1.hasOneUse())
14945    return SDValue();
14946
14947  SDValue ShAmt0 = N0.getOperand(1);
14948  if (ShAmt0.getValueType() != MVT::i8)
14949    return SDValue();
14950  SDValue ShAmt1 = N1.getOperand(1);
14951  if (ShAmt1.getValueType() != MVT::i8)
14952    return SDValue();
14953  if (ShAmt0.getOpcode() == ISD::TRUNCATE)
14954    ShAmt0 = ShAmt0.getOperand(0);
14955  if (ShAmt1.getOpcode() == ISD::TRUNCATE)
14956    ShAmt1 = ShAmt1.getOperand(0);
14957
14958  DebugLoc DL = N->getDebugLoc();
14959  unsigned Opc = X86ISD::SHLD;
14960  SDValue Op0 = N0.getOperand(0);
14961  SDValue Op1 = N1.getOperand(0);
14962  if (ShAmt0.getOpcode() == ISD::SUB) {
14963    Opc = X86ISD::SHRD;
14964    std::swap(Op0, Op1);
14965    std::swap(ShAmt0, ShAmt1);
14966  }
14967
14968  unsigned Bits = VT.getSizeInBits();
14969  if (ShAmt1.getOpcode() == ISD::SUB) {
14970    SDValue Sum = ShAmt1.getOperand(0);
14971    if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
14972      SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
14973      if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
14974        ShAmt1Op1 = ShAmt1Op1.getOperand(0);
14975      if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
14976        return DAG.getNode(Opc, DL, VT,
14977                           Op0, Op1,
14978                           DAG.getNode(ISD::TRUNCATE, DL,
14979                                       MVT::i8, ShAmt0));
14980    }
14981  } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
14982    ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
14983    if (ShAmt0C &&
14984        ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
14985      return DAG.getNode(Opc, DL, VT,
14986                         N0.getOperand(0), N1.getOperand(0),
14987                         DAG.getNode(ISD::TRUNCATE, DL,
14988                                       MVT::i8, ShAmt0));
14989  }
14990
14991  return SDValue();
14992}
14993
14994// Generate NEG and CMOV for integer abs.
14995static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
14996  EVT VT = N->getValueType(0);
14997
14998  // Since X86 does not have CMOV for 8-bit integer, we don't convert
14999  // 8-bit integer abs to NEG and CMOV.
15000  if (VT.isInteger() && VT.getSizeInBits() == 8)
15001    return SDValue();
15002
15003  SDValue N0 = N->getOperand(0);
15004  SDValue N1 = N->getOperand(1);
15005  DebugLoc DL = N->getDebugLoc();
15006
15007  // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
15008  // and change it to SUB and CMOV.
15009  if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
15010      N0.getOpcode() == ISD::ADD &&
15011      N0.getOperand(1) == N1 &&
15012      N1.getOpcode() == ISD::SRA &&
15013      N1.getOperand(0) == N0.getOperand(0))
15014    if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
15015      if (Y1C->getAPIntValue() == VT.getSizeInBits()-1) {
15016        // Generate SUB & CMOV.
15017        SDValue Neg = DAG.getNode(X86ISD::SUB, DL, DAG.getVTList(VT, MVT::i32),
15018                                  DAG.getConstant(0, VT), N0.getOperand(0));
15019
15020        SDValue Ops[] = { N0.getOperand(0), Neg,
15021                          DAG.getConstant(X86::COND_GE, MVT::i8),
15022                          SDValue(Neg.getNode(), 1) };
15023        return DAG.getNode(X86ISD::CMOV, DL, DAG.getVTList(VT, MVT::Glue),
15024                           Ops, array_lengthof(Ops));
15025      }
15026  return SDValue();
15027}
15028
15029// PerformXorCombine - Attempts to turn XOR nodes into BLSMSK nodes
15030static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
15031                                 TargetLowering::DAGCombinerInfo &DCI,
15032                                 const X86Subtarget *Subtarget) {
15033  if (DCI.isBeforeLegalizeOps())
15034    return SDValue();
15035
15036  if (Subtarget->hasCMov()) {
15037    SDValue RV = performIntegerAbsCombine(N, DAG);
15038    if (RV.getNode())
15039      return RV;
15040  }
15041
15042  // Try forming BMI if it is available.
15043  if (!Subtarget->hasBMI())
15044    return SDValue();
15045
15046  EVT VT = N->getValueType(0);
15047
15048  if (VT != MVT::i32 && VT != MVT::i64)
15049    return SDValue();
15050
15051  assert(Subtarget->hasBMI() && "Creating BLSMSK requires BMI instructions");
15052
15053  // Create BLSMSK instructions by finding X ^ (X-1)
15054  SDValue N0 = N->getOperand(0);
15055  SDValue N1 = N->getOperand(1);
15056  DebugLoc DL = N->getDebugLoc();
15057
15058  if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1 &&
15059      isAllOnes(N0.getOperand(1)))
15060    return DAG.getNode(X86ISD::BLSMSK, DL, VT, N1);
15061
15062  if (N1.getOpcode() == ISD::ADD && N1.getOperand(0) == N0 &&
15063      isAllOnes(N1.getOperand(1)))
15064    return DAG.getNode(X86ISD::BLSMSK, DL, VT, N0);
15065
15066  return SDValue();
15067}
15068
15069/// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
15070static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
15071                                  TargetLowering::DAGCombinerInfo &DCI,
15072                                  const X86Subtarget *Subtarget) {
15073  LoadSDNode *Ld = cast<LoadSDNode>(N);
15074  EVT RegVT = Ld->getValueType(0);
15075  EVT MemVT = Ld->getMemoryVT();
15076  DebugLoc dl = Ld->getDebugLoc();
15077  const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15078
15079  ISD::LoadExtType Ext = Ld->getExtensionType();
15080
15081  // If this is a vector EXT Load then attempt to optimize it using a
15082  // shuffle. We need SSE4 for the shuffles.
15083  // TODO: It is possible to support ZExt by zeroing the undef values
15084  // during the shuffle phase or after the shuffle.
15085  if (RegVT.isVector() && RegVT.isInteger() &&
15086      Ext == ISD::EXTLOAD && Subtarget->hasSSE41()) {
15087    assert(MemVT != RegVT && "Cannot extend to the same type");
15088    assert(MemVT.isVector() && "Must load a vector from memory");
15089
15090    unsigned NumElems = RegVT.getVectorNumElements();
15091    unsigned RegSz = RegVT.getSizeInBits();
15092    unsigned MemSz = MemVT.getSizeInBits();
15093    assert(RegSz > MemSz && "Register size must be greater than the mem size");
15094
15095    // All sizes must be a power of two.
15096    if (!isPowerOf2_32(RegSz * MemSz * NumElems))
15097      return SDValue();
15098
15099    // Attempt to load the original value using scalar loads.
15100    // Find the largest scalar type that divides the total loaded size.
15101    MVT SclrLoadTy = MVT::i8;
15102    for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
15103         tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
15104      MVT Tp = (MVT::SimpleValueType)tp;
15105      if (TLI.isTypeLegal(Tp) && ((MemSz % Tp.getSizeInBits()) == 0)) {
15106        SclrLoadTy = Tp;
15107      }
15108    }
15109
15110    // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
15111    if (TLI.isTypeLegal(MVT::f64) && SclrLoadTy.getSizeInBits() < 64 &&
15112        (64 <= MemSz))
15113      SclrLoadTy = MVT::f64;
15114
15115    // Calculate the number of scalar loads that we need to perform
15116    // in order to load our vector from memory.
15117    unsigned NumLoads = MemSz / SclrLoadTy.getSizeInBits();
15118
15119    // Represent our vector as a sequence of elements which are the
15120    // largest scalar that we can load.
15121    EVT LoadUnitVecVT = EVT::getVectorVT(*DAG.getContext(), SclrLoadTy,
15122      RegSz/SclrLoadTy.getSizeInBits());
15123
15124    // Represent the data using the same element type that is stored in
15125    // memory. In practice, we ''widen'' MemVT.
15126    EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
15127                                  RegSz/MemVT.getScalarType().getSizeInBits());
15128
15129    assert(WideVecVT.getSizeInBits() == LoadUnitVecVT.getSizeInBits() &&
15130      "Invalid vector type");
15131
15132    // We can't shuffle using an illegal type.
15133    if (!TLI.isTypeLegal(WideVecVT))
15134      return SDValue();
15135
15136    SmallVector<SDValue, 8> Chains;
15137    SDValue Ptr = Ld->getBasePtr();
15138    SDValue Increment = DAG.getConstant(SclrLoadTy.getSizeInBits()/8,
15139                                        TLI.getPointerTy());
15140    SDValue Res = DAG.getUNDEF(LoadUnitVecVT);
15141
15142    for (unsigned i = 0; i < NumLoads; ++i) {
15143      // Perform a single load.
15144      SDValue ScalarLoad = DAG.getLoad(SclrLoadTy, dl, Ld->getChain(),
15145                                       Ptr, Ld->getPointerInfo(),
15146                                       Ld->isVolatile(), Ld->isNonTemporal(),
15147                                       Ld->isInvariant(), Ld->getAlignment());
15148      Chains.push_back(ScalarLoad.getValue(1));
15149      // Create the first element type using SCALAR_TO_VECTOR in order to avoid
15150      // another round of DAGCombining.
15151      if (i == 0)
15152        Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LoadUnitVecVT, ScalarLoad);
15153      else
15154        Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, LoadUnitVecVT, Res,
15155                          ScalarLoad, DAG.getIntPtrConstant(i));
15156
15157      Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
15158    }
15159
15160    SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Chains[0],
15161                               Chains.size());
15162
15163    // Bitcast the loaded value to a vector of the original element type, in
15164    // the size of the target vector type.
15165    SDValue SlicedVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Res);
15166    unsigned SizeRatio = RegSz/MemSz;
15167
15168    // Redistribute the loaded elements into the different locations.
15169    SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
15170    for (unsigned i = 0; i != NumElems; ++i)
15171      ShuffleVec[i*SizeRatio] = i;
15172
15173    SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
15174                                         DAG.getUNDEF(WideVecVT),
15175                                         &ShuffleVec[0]);
15176
15177    // Bitcast to the requested type.
15178    Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
15179    // Replace the original load with the new sequence
15180    // and return the new chain.
15181    return DCI.CombineTo(N, Shuff, TF, true);
15182  }
15183
15184  return SDValue();
15185}
15186
15187/// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
15188static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
15189                                   const X86Subtarget *Subtarget) {
15190  StoreSDNode *St = cast<StoreSDNode>(N);
15191  EVT VT = St->getValue().getValueType();
15192  EVT StVT = St->getMemoryVT();
15193  DebugLoc dl = St->getDebugLoc();
15194  SDValue StoredVal = St->getOperand(1);
15195  const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15196
15197  // If we are saving a concatenation of two XMM registers, perform two stores.
15198  // On Sandy Bridge, 256-bit memory operations are executed by two
15199  // 128-bit ports. However, on Haswell it is better to issue a single 256-bit
15200  // memory  operation.
15201  if (VT.is256BitVector() && !Subtarget->hasAVX2() &&
15202      StoredVal.getNode()->getOpcode() == ISD::CONCAT_VECTORS &&
15203      StoredVal.getNumOperands() == 2) {
15204    SDValue Value0 = StoredVal.getOperand(0);
15205    SDValue Value1 = StoredVal.getOperand(1);
15206
15207    SDValue Stride = DAG.getConstant(16, TLI.getPointerTy());
15208    SDValue Ptr0 = St->getBasePtr();
15209    SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
15210
15211    SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
15212                                St->getPointerInfo(), St->isVolatile(),
15213                                St->isNonTemporal(), St->getAlignment());
15214    SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
15215                                St->getPointerInfo(), St->isVolatile(),
15216                                St->isNonTemporal(), St->getAlignment());
15217    return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
15218  }
15219
15220  // Optimize trunc store (of multiple scalars) to shuffle and store.
15221  // First, pack all of the elements in one place. Next, store to memory
15222  // in fewer chunks.
15223  if (St->isTruncatingStore() && VT.isVector()) {
15224    const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15225    unsigned NumElems = VT.getVectorNumElements();
15226    assert(StVT != VT && "Cannot truncate to the same type");
15227    unsigned FromSz = VT.getVectorElementType().getSizeInBits();
15228    unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
15229
15230    // From, To sizes and ElemCount must be pow of two
15231    if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
15232    // We are going to use the original vector elt for storing.
15233    // Accumulated smaller vector elements must be a multiple of the store size.
15234    if (0 != (NumElems * FromSz) % ToSz) return SDValue();
15235
15236    unsigned SizeRatio  = FromSz / ToSz;
15237
15238    assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
15239
15240    // Create a type on which we perform the shuffle
15241    EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
15242            StVT.getScalarType(), NumElems*SizeRatio);
15243
15244    assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
15245
15246    SDValue WideVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, St->getValue());
15247    SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
15248    for (unsigned i = 0; i != NumElems; ++i)
15249      ShuffleVec[i] = i * SizeRatio;
15250
15251    // Can't shuffle using an illegal type.
15252    if (!TLI.isTypeLegal(WideVecVT))
15253      return SDValue();
15254
15255    SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
15256                                         DAG.getUNDEF(WideVecVT),
15257                                         &ShuffleVec[0]);
15258    // At this point all of the data is stored at the bottom of the
15259    // register. We now need to save it to mem.
15260
15261    // Find the largest store unit
15262    MVT StoreType = MVT::i8;
15263    for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
15264         tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
15265      MVT Tp = (MVT::SimpleValueType)tp;
15266      if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToSz)
15267        StoreType = Tp;
15268    }
15269
15270    // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
15271    if (TLI.isTypeLegal(MVT::f64) && StoreType.getSizeInBits() < 64 &&
15272        (64 <= NumElems * ToSz))
15273      StoreType = MVT::f64;
15274
15275    // Bitcast the original vector into a vector of store-size units
15276    EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
15277            StoreType, VT.getSizeInBits()/StoreType.getSizeInBits());
15278    assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
15279    SDValue ShuffWide = DAG.getNode(ISD::BITCAST, dl, StoreVecVT, Shuff);
15280    SmallVector<SDValue, 8> Chains;
15281    SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
15282                                        TLI.getPointerTy());
15283    SDValue Ptr = St->getBasePtr();
15284
15285    // Perform one or more big stores into memory.
15286    for (unsigned i=0, e=(ToSz*NumElems)/StoreType.getSizeInBits(); i!=e; ++i) {
15287      SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
15288                                   StoreType, ShuffWide,
15289                                   DAG.getIntPtrConstant(i));
15290      SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
15291                                St->getPointerInfo(), St->isVolatile(),
15292                                St->isNonTemporal(), St->getAlignment());
15293      Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
15294      Chains.push_back(Ch);
15295    }
15296
15297    return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Chains[0],
15298                               Chains.size());
15299  }
15300
15301
15302  // Turn load->store of MMX types into GPR load/stores.  This avoids clobbering
15303  // the FP state in cases where an emms may be missing.
15304  // A preferable solution to the general problem is to figure out the right
15305  // places to insert EMMS.  This qualifies as a quick hack.
15306
15307  // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
15308  if (VT.getSizeInBits() != 64)
15309    return SDValue();
15310
15311  const Function *F = DAG.getMachineFunction().getFunction();
15312  bool NoImplicitFloatOps = F->hasFnAttr(Attribute::NoImplicitFloat);
15313  bool F64IsLegal = !DAG.getTarget().Options.UseSoftFloat && !NoImplicitFloatOps
15314                     && Subtarget->hasSSE2();
15315  if ((VT.isVector() ||
15316       (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
15317      isa<LoadSDNode>(St->getValue()) &&
15318      !cast<LoadSDNode>(St->getValue())->isVolatile() &&
15319      St->getChain().hasOneUse() && !St->isVolatile()) {
15320    SDNode* LdVal = St->getValue().getNode();
15321    LoadSDNode *Ld = 0;
15322    int TokenFactorIndex = -1;
15323    SmallVector<SDValue, 8> Ops;
15324    SDNode* ChainVal = St->getChain().getNode();
15325    // Must be a store of a load.  We currently handle two cases:  the load
15326    // is a direct child, and it's under an intervening TokenFactor.  It is
15327    // possible to dig deeper under nested TokenFactors.
15328    if (ChainVal == LdVal)
15329      Ld = cast<LoadSDNode>(St->getChain());
15330    else if (St->getValue().hasOneUse() &&
15331             ChainVal->getOpcode() == ISD::TokenFactor) {
15332      for (unsigned i = 0, e = ChainVal->getNumOperands(); i != e; ++i) {
15333        if (ChainVal->getOperand(i).getNode() == LdVal) {
15334          TokenFactorIndex = i;
15335          Ld = cast<LoadSDNode>(St->getValue());
15336        } else
15337          Ops.push_back(ChainVal->getOperand(i));
15338      }
15339    }
15340
15341    if (!Ld || !ISD::isNormalLoad(Ld))
15342      return SDValue();
15343
15344    // If this is not the MMX case, i.e. we are just turning i64 load/store
15345    // into f64 load/store, avoid the transformation if there are multiple
15346    // uses of the loaded value.
15347    if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
15348      return SDValue();
15349
15350    DebugLoc LdDL = Ld->getDebugLoc();
15351    DebugLoc StDL = N->getDebugLoc();
15352    // If we are a 64-bit capable x86, lower to a single movq load/store pair.
15353    // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
15354    // pair instead.
15355    if (Subtarget->is64Bit() || F64IsLegal) {
15356      EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
15357      SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
15358                                  Ld->getPointerInfo(), Ld->isVolatile(),
15359                                  Ld->isNonTemporal(), Ld->isInvariant(),
15360                                  Ld->getAlignment());
15361      SDValue NewChain = NewLd.getValue(1);
15362      if (TokenFactorIndex != -1) {
15363        Ops.push_back(NewChain);
15364        NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
15365                               Ops.size());
15366      }
15367      return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
15368                          St->getPointerInfo(),
15369                          St->isVolatile(), St->isNonTemporal(),
15370                          St->getAlignment());
15371    }
15372
15373    // Otherwise, lower to two pairs of 32-bit loads / stores.
15374    SDValue LoAddr = Ld->getBasePtr();
15375    SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
15376                                 DAG.getConstant(4, MVT::i32));
15377
15378    SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
15379                               Ld->getPointerInfo(),
15380                               Ld->isVolatile(), Ld->isNonTemporal(),
15381                               Ld->isInvariant(), Ld->getAlignment());
15382    SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
15383                               Ld->getPointerInfo().getWithOffset(4),
15384                               Ld->isVolatile(), Ld->isNonTemporal(),
15385                               Ld->isInvariant(),
15386                               MinAlign(Ld->getAlignment(), 4));
15387
15388    SDValue NewChain = LoLd.getValue(1);
15389    if (TokenFactorIndex != -1) {
15390      Ops.push_back(LoLd);
15391      Ops.push_back(HiLd);
15392      NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
15393                             Ops.size());
15394    }
15395
15396    LoAddr = St->getBasePtr();
15397    HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
15398                         DAG.getConstant(4, MVT::i32));
15399
15400    SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
15401                                St->getPointerInfo(),
15402                                St->isVolatile(), St->isNonTemporal(),
15403                                St->getAlignment());
15404    SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
15405                                St->getPointerInfo().getWithOffset(4),
15406                                St->isVolatile(),
15407                                St->isNonTemporal(),
15408                                MinAlign(St->getAlignment(), 4));
15409    return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
15410  }
15411  return SDValue();
15412}
15413
15414/// isHorizontalBinOp - Return 'true' if this vector operation is "horizontal"
15415/// and return the operands for the horizontal operation in LHS and RHS.  A
15416/// horizontal operation performs the binary operation on successive elements
15417/// of its first operand, then on successive elements of its second operand,
15418/// returning the resulting values in a vector.  For example, if
15419///   A = < float a0, float a1, float a2, float a3 >
15420/// and
15421///   B = < float b0, float b1, float b2, float b3 >
15422/// then the result of doing a horizontal operation on A and B is
15423///   A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
15424/// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
15425/// A horizontal-op B, for some already available A and B, and if so then LHS is
15426/// set to A, RHS to B, and the routine returns 'true'.
15427/// Note that the binary operation should have the property that if one of the
15428/// operands is UNDEF then the result is UNDEF.
15429static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool IsCommutative) {
15430  // Look for the following pattern: if
15431  //   A = < float a0, float a1, float a2, float a3 >
15432  //   B = < float b0, float b1, float b2, float b3 >
15433  // and
15434  //   LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
15435  //   RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
15436  // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
15437  // which is A horizontal-op B.
15438
15439  // At least one of the operands should be a vector shuffle.
15440  if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
15441      RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
15442    return false;
15443
15444  EVT VT = LHS.getValueType();
15445
15446  assert((VT.is128BitVector() || VT.is256BitVector()) &&
15447         "Unsupported vector type for horizontal add/sub");
15448
15449  // Handle 128 and 256-bit vector lengths. AVX defines horizontal add/sub to
15450  // operate independently on 128-bit lanes.
15451  unsigned NumElts = VT.getVectorNumElements();
15452  unsigned NumLanes = VT.getSizeInBits()/128;
15453  unsigned NumLaneElts = NumElts / NumLanes;
15454  assert((NumLaneElts % 2 == 0) &&
15455         "Vector type should have an even number of elements in each lane");
15456  unsigned HalfLaneElts = NumLaneElts/2;
15457
15458  // View LHS in the form
15459  //   LHS = VECTOR_SHUFFLE A, B, LMask
15460  // If LHS is not a shuffle then pretend it is the shuffle
15461  //   LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
15462  // NOTE: in what follows a default initialized SDValue represents an UNDEF of
15463  // type VT.
15464  SDValue A, B;
15465  SmallVector<int, 16> LMask(NumElts);
15466  if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
15467    if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
15468      A = LHS.getOperand(0);
15469    if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
15470      B = LHS.getOperand(1);
15471    ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(LHS.getNode())->getMask();
15472    std::copy(Mask.begin(), Mask.end(), LMask.begin());
15473  } else {
15474    if (LHS.getOpcode() != ISD::UNDEF)
15475      A = LHS;
15476    for (unsigned i = 0; i != NumElts; ++i)
15477      LMask[i] = i;
15478  }
15479
15480  // Likewise, view RHS in the form
15481  //   RHS = VECTOR_SHUFFLE C, D, RMask
15482  SDValue C, D;
15483  SmallVector<int, 16> RMask(NumElts);
15484  if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
15485    if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
15486      C = RHS.getOperand(0);
15487    if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
15488      D = RHS.getOperand(1);
15489    ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(RHS.getNode())->getMask();
15490    std::copy(Mask.begin(), Mask.end(), RMask.begin());
15491  } else {
15492    if (RHS.getOpcode() != ISD::UNDEF)
15493      C = RHS;
15494    for (unsigned i = 0; i != NumElts; ++i)
15495      RMask[i] = i;
15496  }
15497
15498  // Check that the shuffles are both shuffling the same vectors.
15499  if (!(A == C && B == D) && !(A == D && B == C))
15500    return false;
15501
15502  // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
15503  if (!A.getNode() && !B.getNode())
15504    return false;
15505
15506  // If A and B occur in reverse order in RHS, then "swap" them (which means
15507  // rewriting the mask).
15508  if (A != C)
15509    CommuteVectorShuffleMask(RMask, NumElts);
15510
15511  // At this point LHS and RHS are equivalent to
15512  //   LHS = VECTOR_SHUFFLE A, B, LMask
15513  //   RHS = VECTOR_SHUFFLE A, B, RMask
15514  // Check that the masks correspond to performing a horizontal operation.
15515  for (unsigned i = 0; i != NumElts; ++i) {
15516    int LIdx = LMask[i], RIdx = RMask[i];
15517
15518    // Ignore any UNDEF components.
15519    if (LIdx < 0 || RIdx < 0 ||
15520        (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) ||
15521        (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts)))
15522      continue;
15523
15524    // Check that successive elements are being operated on.  If not, this is
15525    // not a horizontal operation.
15526    unsigned Src = (i/HalfLaneElts) % 2; // each lane is split between srcs
15527    unsigned LaneStart = (i/NumLaneElts) * NumLaneElts;
15528    int Index = 2*(i%HalfLaneElts) + NumElts*Src + LaneStart;
15529    if (!(LIdx == Index && RIdx == Index + 1) &&
15530        !(IsCommutative && LIdx == Index + 1 && RIdx == Index))
15531      return false;
15532  }
15533
15534  LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
15535  RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
15536  return true;
15537}
15538
15539/// PerformFADDCombine - Do target-specific dag combines on floating point adds.
15540static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
15541                                  const X86Subtarget *Subtarget) {
15542  EVT VT = N->getValueType(0);
15543  SDValue LHS = N->getOperand(0);
15544  SDValue RHS = N->getOperand(1);
15545
15546  // Try to synthesize horizontal adds from adds of shuffles.
15547  if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
15548       (Subtarget->hasAVX() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
15549      isHorizontalBinOp(LHS, RHS, true))
15550    return DAG.getNode(X86ISD::FHADD, N->getDebugLoc(), VT, LHS, RHS);
15551  return SDValue();
15552}
15553
15554/// PerformFSUBCombine - Do target-specific dag combines on floating point subs.
15555static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
15556                                  const X86Subtarget *Subtarget) {
15557  EVT VT = N->getValueType(0);
15558  SDValue LHS = N->getOperand(0);
15559  SDValue RHS = N->getOperand(1);
15560
15561  // Try to synthesize horizontal subs from subs of shuffles.
15562  if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
15563       (Subtarget->hasAVX() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
15564      isHorizontalBinOp(LHS, RHS, false))
15565    return DAG.getNode(X86ISD::FHSUB, N->getDebugLoc(), VT, LHS, RHS);
15566  return SDValue();
15567}
15568
15569/// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
15570/// X86ISD::FXOR nodes.
15571static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
15572  assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
15573  // F[X]OR(0.0, x) -> x
15574  // F[X]OR(x, 0.0) -> x
15575  if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
15576    if (C->getValueAPF().isPosZero())
15577      return N->getOperand(1);
15578  if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
15579    if (C->getValueAPF().isPosZero())
15580      return N->getOperand(0);
15581  return SDValue();
15582}
15583
15584/// PerformFMinFMaxCombine - Do target-specific dag combines on X86ISD::FMIN and
15585/// X86ISD::FMAX nodes.
15586static SDValue PerformFMinFMaxCombine(SDNode *N, SelectionDAG &DAG) {
15587  assert(N->getOpcode() == X86ISD::FMIN || N->getOpcode() == X86ISD::FMAX);
15588
15589  // Only perform optimizations if UnsafeMath is used.
15590  if (!DAG.getTarget().Options.UnsafeFPMath)
15591    return SDValue();
15592
15593  // If we run in unsafe-math mode, then convert the FMAX and FMIN nodes
15594  // into FMINC and FMAXC, which are Commutative operations.
15595  unsigned NewOp = 0;
15596  switch (N->getOpcode()) {
15597    default: llvm_unreachable("unknown opcode");
15598    case X86ISD::FMIN:  NewOp = X86ISD::FMINC; break;
15599    case X86ISD::FMAX:  NewOp = X86ISD::FMAXC; break;
15600  }
15601
15602  return DAG.getNode(NewOp, N->getDebugLoc(), N->getValueType(0),
15603                     N->getOperand(0), N->getOperand(1));
15604}
15605
15606
15607/// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
15608static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
15609  // FAND(0.0, x) -> 0.0
15610  // FAND(x, 0.0) -> 0.0
15611  if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
15612    if (C->getValueAPF().isPosZero())
15613      return N->getOperand(0);
15614  if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
15615    if (C->getValueAPF().isPosZero())
15616      return N->getOperand(1);
15617  return SDValue();
15618}
15619
15620static SDValue PerformBTCombine(SDNode *N,
15621                                SelectionDAG &DAG,
15622                                TargetLowering::DAGCombinerInfo &DCI) {
15623  // BT ignores high bits in the bit index operand.
15624  SDValue Op1 = N->getOperand(1);
15625  if (Op1.hasOneUse()) {
15626    unsigned BitWidth = Op1.getValueSizeInBits();
15627    APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
15628    APInt KnownZero, KnownOne;
15629    TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
15630                                          !DCI.isBeforeLegalizeOps());
15631    const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15632    if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
15633        TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
15634      DCI.CommitTargetLoweringOpt(TLO);
15635  }
15636  return SDValue();
15637}
15638
15639static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
15640  SDValue Op = N->getOperand(0);
15641  if (Op.getOpcode() == ISD::BITCAST)
15642    Op = Op.getOperand(0);
15643  EVT VT = N->getValueType(0), OpVT = Op.getValueType();
15644  if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
15645      VT.getVectorElementType().getSizeInBits() ==
15646      OpVT.getVectorElementType().getSizeInBits()) {
15647    return DAG.getNode(ISD::BITCAST, N->getDebugLoc(), VT, Op);
15648  }
15649  return SDValue();
15650}
15651
15652static SDValue PerformSExtCombine(SDNode *N, SelectionDAG &DAG,
15653                                  TargetLowering::DAGCombinerInfo &DCI,
15654                                  const X86Subtarget *Subtarget) {
15655  if (!DCI.isBeforeLegalizeOps())
15656    return SDValue();
15657
15658  if (!Subtarget->hasAVX())
15659    return SDValue();
15660
15661  EVT VT = N->getValueType(0);
15662  SDValue Op = N->getOperand(0);
15663  EVT OpVT = Op.getValueType();
15664  DebugLoc dl = N->getDebugLoc();
15665
15666  if ((VT == MVT::v4i64 && OpVT == MVT::v4i32) ||
15667      (VT == MVT::v8i32 && OpVT == MVT::v8i16)) {
15668
15669    if (Subtarget->hasAVX2())
15670      return DAG.getNode(X86ISD::VSEXT_MOVL, dl, VT, Op);
15671
15672    // Optimize vectors in AVX mode
15673    // Sign extend  v8i16 to v8i32 and
15674    //              v4i32 to v4i64
15675    //
15676    // Divide input vector into two parts
15677    // for v4i32 the shuffle mask will be { 0, 1, -1, -1} {2, 3, -1, -1}
15678    // use vpmovsx instruction to extend v4i32 -> v2i64; v8i16 -> v4i32
15679    // concat the vectors to original VT
15680
15681    unsigned NumElems = OpVT.getVectorNumElements();
15682    SDValue Undef = DAG.getUNDEF(OpVT);
15683
15684    SmallVector<int,8> ShufMask1(NumElems, -1);
15685    for (unsigned i = 0; i != NumElems/2; ++i)
15686      ShufMask1[i] = i;
15687
15688    SDValue OpLo = DAG.getVectorShuffle(OpVT, dl, Op, Undef, &ShufMask1[0]);
15689
15690    SmallVector<int,8> ShufMask2(NumElems, -1);
15691    for (unsigned i = 0; i != NumElems/2; ++i)
15692      ShufMask2[i] = i + NumElems/2;
15693
15694    SDValue OpHi = DAG.getVectorShuffle(OpVT, dl, Op, Undef, &ShufMask2[0]);
15695
15696    EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), VT.getScalarType(),
15697                                  VT.getVectorNumElements()/2);
15698
15699    OpLo = DAG.getNode(X86ISD::VSEXT_MOVL, dl, HalfVT, OpLo);
15700    OpHi = DAG.getNode(X86ISD::VSEXT_MOVL, dl, HalfVT, OpHi);
15701
15702    return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
15703  }
15704  return SDValue();
15705}
15706
15707static SDValue PerformFMACombine(SDNode *N, SelectionDAG &DAG,
15708                                 const X86Subtarget* Subtarget) {
15709  DebugLoc dl = N->getDebugLoc();
15710  EVT VT = N->getValueType(0);
15711
15712  // Let legalize expand this if it isn't a legal type yet.
15713  if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
15714    return SDValue();
15715
15716  EVT ScalarVT = VT.getScalarType();
15717  if ((ScalarVT != MVT::f32 && ScalarVT != MVT::f64) ||
15718      (!Subtarget->hasFMA() && !Subtarget->hasFMA4()))
15719    return SDValue();
15720
15721  SDValue A = N->getOperand(0);
15722  SDValue B = N->getOperand(1);
15723  SDValue C = N->getOperand(2);
15724
15725  bool NegA = (A.getOpcode() == ISD::FNEG);
15726  bool NegB = (B.getOpcode() == ISD::FNEG);
15727  bool NegC = (C.getOpcode() == ISD::FNEG);
15728
15729  // Negative multiplication when NegA xor NegB
15730  bool NegMul = (NegA != NegB);
15731  if (NegA)
15732    A = A.getOperand(0);
15733  if (NegB)
15734    B = B.getOperand(0);
15735  if (NegC)
15736    C = C.getOperand(0);
15737
15738  unsigned Opcode;
15739  if (!NegMul)
15740    Opcode = (!NegC) ? X86ISD::FMADD : X86ISD::FMSUB;
15741  else
15742    Opcode = (!NegC) ? X86ISD::FNMADD : X86ISD::FNMSUB;
15743
15744  return DAG.getNode(Opcode, dl, VT, A, B, C);
15745}
15746
15747static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG,
15748                                  TargetLowering::DAGCombinerInfo &DCI,
15749                                  const X86Subtarget *Subtarget) {
15750  // (i32 zext (and (i8  x86isd::setcc_carry), 1)) ->
15751  //           (and (i32 x86isd::setcc_carry), 1)
15752  // This eliminates the zext. This transformation is necessary because
15753  // ISD::SETCC is always legalized to i8.
15754  DebugLoc dl = N->getDebugLoc();
15755  SDValue N0 = N->getOperand(0);
15756  EVT VT = N->getValueType(0);
15757  EVT OpVT = N0.getValueType();
15758
15759  if (N0.getOpcode() == ISD::AND &&
15760      N0.hasOneUse() &&
15761      N0.getOperand(0).hasOneUse()) {
15762    SDValue N00 = N0.getOperand(0);
15763    if (N00.getOpcode() != X86ISD::SETCC_CARRY)
15764      return SDValue();
15765    ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
15766    if (!C || C->getZExtValue() != 1)
15767      return SDValue();
15768    return DAG.getNode(ISD::AND, dl, VT,
15769                       DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
15770                                   N00.getOperand(0), N00.getOperand(1)),
15771                       DAG.getConstant(1, VT));
15772  }
15773
15774  // Optimize vectors in AVX mode:
15775  //
15776  //   v8i16 -> v8i32
15777  //   Use vpunpcklwd for 4 lower elements  v8i16 -> v4i32.
15778  //   Use vpunpckhwd for 4 upper elements  v8i16 -> v4i32.
15779  //   Concat upper and lower parts.
15780  //
15781  //   v4i32 -> v4i64
15782  //   Use vpunpckldq for 4 lower elements  v4i32 -> v2i64.
15783  //   Use vpunpckhdq for 4 upper elements  v4i32 -> v2i64.
15784  //   Concat upper and lower parts.
15785  //
15786  if (!DCI.isBeforeLegalizeOps())
15787    return SDValue();
15788
15789  if (!Subtarget->hasAVX())
15790    return SDValue();
15791
15792  if (((VT == MVT::v8i32) && (OpVT == MVT::v8i16)) ||
15793      ((VT == MVT::v4i64) && (OpVT == MVT::v4i32)))  {
15794
15795    if (Subtarget->hasAVX2())
15796      return DAG.getNode(X86ISD::VZEXT_MOVL, dl, VT, N0);
15797
15798    SDValue ZeroVec = getZeroVector(OpVT, Subtarget, DAG, dl);
15799    SDValue OpLo = getUnpackl(DAG, dl, OpVT, N0, ZeroVec);
15800    SDValue OpHi = getUnpackh(DAG, dl, OpVT, N0, ZeroVec);
15801
15802    EVT HVT = EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(),
15803                               VT.getVectorNumElements()/2);
15804
15805    OpLo = DAG.getNode(ISD::BITCAST, dl, HVT, OpLo);
15806    OpHi = DAG.getNode(ISD::BITCAST, dl, HVT, OpHi);
15807
15808    return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
15809  }
15810
15811  return SDValue();
15812}
15813
15814// Optimize x == -y --> x+y == 0
15815//          x != -y --> x+y != 0
15816static SDValue PerformISDSETCCCombine(SDNode *N, SelectionDAG &DAG) {
15817  ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
15818  SDValue LHS = N->getOperand(0);
15819  SDValue RHS = N->getOperand(1);
15820
15821  if ((CC == ISD::SETNE || CC == ISD::SETEQ) && LHS.getOpcode() == ISD::SUB)
15822    if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(LHS.getOperand(0)))
15823      if (C->getAPIntValue() == 0 && LHS.hasOneUse()) {
15824        SDValue addV = DAG.getNode(ISD::ADD, N->getDebugLoc(),
15825                                   LHS.getValueType(), RHS, LHS.getOperand(1));
15826        return DAG.getSetCC(N->getDebugLoc(), N->getValueType(0),
15827                            addV, DAG.getConstant(0, addV.getValueType()), CC);
15828      }
15829  if ((CC == ISD::SETNE || CC == ISD::SETEQ) && RHS.getOpcode() == ISD::SUB)
15830    if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS.getOperand(0)))
15831      if (C->getAPIntValue() == 0 && RHS.hasOneUse()) {
15832        SDValue addV = DAG.getNode(ISD::ADD, N->getDebugLoc(),
15833                                   RHS.getValueType(), LHS, RHS.getOperand(1));
15834        return DAG.getSetCC(N->getDebugLoc(), N->getValueType(0),
15835                            addV, DAG.getConstant(0, addV.getValueType()), CC);
15836      }
15837  return SDValue();
15838}
15839
15840// Optimize  RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
15841static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG,
15842                                   TargetLowering::DAGCombinerInfo &DCI,
15843                                   const X86Subtarget *Subtarget) {
15844  DebugLoc DL = N->getDebugLoc();
15845  X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(0));
15846  SDValue EFLAGS = N->getOperand(1);
15847
15848  // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
15849  // a zext and produces an all-ones bit which is more useful than 0/1 in some
15850  // cases.
15851  if (CC == X86::COND_B)
15852    return DAG.getNode(ISD::AND, DL, MVT::i8,
15853                       DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
15854                                   DAG.getConstant(CC, MVT::i8), EFLAGS),
15855                       DAG.getConstant(1, MVT::i8));
15856
15857  SDValue Flags;
15858
15859  Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
15860  if (Flags.getNode()) {
15861    SDValue Cond = DAG.getConstant(CC, MVT::i8);
15862    return DAG.getNode(X86ISD::SETCC, DL, N->getVTList(), Cond, Flags);
15863  }
15864
15865  Flags = checkFlaggedOrCombine(EFLAGS, CC, DAG, Subtarget);
15866  if (Flags.getNode()) {
15867    SDValue Cond = DAG.getConstant(CC, MVT::i8);
15868    return DAG.getNode(X86ISD::SETCC, DL, N->getVTList(), Cond, Flags);
15869  }
15870
15871  return SDValue();
15872}
15873
15874// Optimize branch condition evaluation.
15875//
15876static SDValue PerformBrCondCombine(SDNode *N, SelectionDAG &DAG,
15877                                    TargetLowering::DAGCombinerInfo &DCI,
15878                                    const X86Subtarget *Subtarget) {
15879  DebugLoc DL = N->getDebugLoc();
15880  SDValue Chain = N->getOperand(0);
15881  SDValue Dest = N->getOperand(1);
15882  SDValue EFLAGS = N->getOperand(3);
15883  X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(2));
15884
15885  SDValue Flags;
15886
15887  Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
15888  if (Flags.getNode()) {
15889    SDValue Cond = DAG.getConstant(CC, MVT::i8);
15890    return DAG.getNode(X86ISD::BRCOND, DL, N->getVTList(), Chain, Dest, Cond,
15891                       Flags);
15892  }
15893
15894  Flags = checkFlaggedOrCombine(EFLAGS, CC, DAG, Subtarget);
15895  if (Flags.getNode()) {
15896    SDValue Cond = DAG.getConstant(CC, MVT::i8);
15897    return DAG.getNode(X86ISD::BRCOND, DL, N->getVTList(), Chain, Dest, Cond,
15898                       Flags);
15899  }
15900
15901  return SDValue();
15902}
15903
15904static SDValue PerformUINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG) {
15905  SDValue Op0 = N->getOperand(0);
15906  EVT InVT = Op0->getValueType(0);
15907
15908  // UINT_TO_FP(v4i8) -> SINT_TO_FP(ZEXT(v4i8 to v4i32))
15909  if (InVT == MVT::v8i8 || InVT == MVT::v4i8) {
15910    DebugLoc dl = N->getDebugLoc();
15911    MVT DstVT = InVT == MVT::v4i8 ? MVT::v4i32 : MVT::v8i32;
15912    SDValue P = DAG.getNode(ISD::ZERO_EXTEND, dl, DstVT, Op0);
15913    // Notice that we use SINT_TO_FP because we know that the high bits
15914    // are zero and SINT_TO_FP is better supported by the hardware.
15915    return DAG.getNode(ISD::SINT_TO_FP, dl, N->getValueType(0), P);
15916  }
15917
15918  return SDValue();
15919}
15920
15921static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
15922                                        const X86TargetLowering *XTLI) {
15923  SDValue Op0 = N->getOperand(0);
15924  EVT InVT = Op0->getValueType(0);
15925
15926  // SINT_TO_FP(v4i8) -> SINT_TO_FP(SEXT(v4i8 to v4i32))
15927  if (InVT == MVT::v8i8 || InVT == MVT::v4i8) {
15928    DebugLoc dl = N->getDebugLoc();
15929    MVT DstVT = InVT == MVT::v4i8 ? MVT::v4i32 : MVT::v8i32;
15930    SDValue P = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Op0);
15931    return DAG.getNode(ISD::SINT_TO_FP, dl, N->getValueType(0), P);
15932  }
15933
15934  // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
15935  // a 32-bit target where SSE doesn't support i64->FP operations.
15936  if (Op0.getOpcode() == ISD::LOAD) {
15937    LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
15938    EVT VT = Ld->getValueType(0);
15939    if (!Ld->isVolatile() && !N->getValueType(0).isVector() &&
15940        ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
15941        !XTLI->getSubtarget()->is64Bit() &&
15942        !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
15943      SDValue FILDChain = XTLI->BuildFILD(SDValue(N, 0), Ld->getValueType(0),
15944                                          Ld->getChain(), Op0, DAG);
15945      DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
15946      return FILDChain;
15947    }
15948  }
15949  return SDValue();
15950}
15951
15952static SDValue PerformFP_TO_SINTCombine(SDNode *N, SelectionDAG &DAG) {
15953  EVT VT = N->getValueType(0);
15954
15955  // v4i8 = FP_TO_SINT() -> v4i8 = TRUNCATE (V4i32 = FP_TO_SINT()
15956  if (VT == MVT::v8i8 || VT == MVT::v4i8) {
15957    DebugLoc dl = N->getDebugLoc();
15958    MVT DstVT = VT == MVT::v4i8 ? MVT::v4i32 : MVT::v8i32;
15959    SDValue I = DAG.getNode(ISD::FP_TO_SINT, dl, DstVT, N->getOperand(0));
15960    return DAG.getNode(ISD::TRUNCATE, dl, VT, I);
15961  }
15962
15963  return SDValue();
15964}
15965
15966// Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
15967static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
15968                                 X86TargetLowering::DAGCombinerInfo &DCI) {
15969  // If the LHS and RHS of the ADC node are zero, then it can't overflow and
15970  // the result is either zero or one (depending on the input carry bit).
15971  // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
15972  if (X86::isZeroNode(N->getOperand(0)) &&
15973      X86::isZeroNode(N->getOperand(1)) &&
15974      // We don't have a good way to replace an EFLAGS use, so only do this when
15975      // dead right now.
15976      SDValue(N, 1).use_empty()) {
15977    DebugLoc DL = N->getDebugLoc();
15978    EVT VT = N->getValueType(0);
15979    SDValue CarryOut = DAG.getConstant(0, N->getValueType(1));
15980    SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
15981                               DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
15982                                           DAG.getConstant(X86::COND_B,MVT::i8),
15983                                           N->getOperand(2)),
15984                               DAG.getConstant(1, VT));
15985    return DCI.CombineTo(N, Res1, CarryOut);
15986  }
15987
15988  return SDValue();
15989}
15990
15991// fold (add Y, (sete  X, 0)) -> adc  0, Y
15992//      (add Y, (setne X, 0)) -> sbb -1, Y
15993//      (sub (sete  X, 0), Y) -> sbb  0, Y
15994//      (sub (setne X, 0), Y) -> adc -1, Y
15995static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
15996  DebugLoc DL = N->getDebugLoc();
15997
15998  // Look through ZExts.
15999  SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
16000  if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
16001    return SDValue();
16002
16003  SDValue SetCC = Ext.getOperand(0);
16004  if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
16005    return SDValue();
16006
16007  X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
16008  if (CC != X86::COND_E && CC != X86::COND_NE)
16009    return SDValue();
16010
16011  SDValue Cmp = SetCC.getOperand(1);
16012  if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
16013      !X86::isZeroNode(Cmp.getOperand(1)) ||
16014      !Cmp.getOperand(0).getValueType().isInteger())
16015    return SDValue();
16016
16017  SDValue CmpOp0 = Cmp.getOperand(0);
16018  SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
16019                               DAG.getConstant(1, CmpOp0.getValueType()));
16020
16021  SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
16022  if (CC == X86::COND_NE)
16023    return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
16024                       DL, OtherVal.getValueType(), OtherVal,
16025                       DAG.getConstant(-1ULL, OtherVal.getValueType()), NewCmp);
16026  return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
16027                     DL, OtherVal.getValueType(), OtherVal,
16028                     DAG.getConstant(0, OtherVal.getValueType()), NewCmp);
16029}
16030
16031/// PerformADDCombine - Do target-specific dag combines on integer adds.
16032static SDValue PerformAddCombine(SDNode *N, SelectionDAG &DAG,
16033                                 const X86Subtarget *Subtarget) {
16034  EVT VT = N->getValueType(0);
16035  SDValue Op0 = N->getOperand(0);
16036  SDValue Op1 = N->getOperand(1);
16037
16038  // Try to synthesize horizontal adds from adds of shuffles.
16039  if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
16040       (Subtarget->hasAVX2() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
16041      isHorizontalBinOp(Op0, Op1, true))
16042    return DAG.getNode(X86ISD::HADD, N->getDebugLoc(), VT, Op0, Op1);
16043
16044  return OptimizeConditionalInDecrement(N, DAG);
16045}
16046
16047static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG,
16048                                 const X86Subtarget *Subtarget) {
16049  SDValue Op0 = N->getOperand(0);
16050  SDValue Op1 = N->getOperand(1);
16051
16052  // X86 can't encode an immediate LHS of a sub. See if we can push the
16053  // negation into a preceding instruction.
16054  if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
16055    // If the RHS of the sub is a XOR with one use and a constant, invert the
16056    // immediate. Then add one to the LHS of the sub so we can turn
16057    // X-Y -> X+~Y+1, saving one register.
16058    if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
16059        isa<ConstantSDNode>(Op1.getOperand(1))) {
16060      APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
16061      EVT VT = Op0.getValueType();
16062      SDValue NewXor = DAG.getNode(ISD::XOR, Op1.getDebugLoc(), VT,
16063                                   Op1.getOperand(0),
16064                                   DAG.getConstant(~XorC, VT));
16065      return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, NewXor,
16066                         DAG.getConstant(C->getAPIntValue()+1, VT));
16067    }
16068  }
16069
16070  // Try to synthesize horizontal adds from adds of shuffles.
16071  EVT VT = N->getValueType(0);
16072  if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
16073       (Subtarget->hasAVX2() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
16074      isHorizontalBinOp(Op0, Op1, true))
16075    return DAG.getNode(X86ISD::HSUB, N->getDebugLoc(), VT, Op0, Op1);
16076
16077  return OptimizeConditionalInDecrement(N, DAG);
16078}
16079
16080SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
16081                                             DAGCombinerInfo &DCI) const {
16082  SelectionDAG &DAG = DCI.DAG;
16083  switch (N->getOpcode()) {
16084  default: break;
16085  case ISD::EXTRACT_VECTOR_ELT:
16086    return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, DCI);
16087  case ISD::VSELECT:
16088  case ISD::SELECT:         return PerformSELECTCombine(N, DAG, DCI, Subtarget);
16089  case X86ISD::CMOV:        return PerformCMOVCombine(N, DAG, DCI, Subtarget);
16090  case ISD::ADD:            return PerformAddCombine(N, DAG, Subtarget);
16091  case ISD::SUB:            return PerformSubCombine(N, DAG, Subtarget);
16092  case X86ISD::ADC:         return PerformADCCombine(N, DAG, DCI);
16093  case ISD::MUL:            return PerformMulCombine(N, DAG, DCI);
16094  case ISD::SHL:
16095  case ISD::SRA:
16096  case ISD::SRL:            return PerformShiftCombine(N, DAG, DCI, Subtarget);
16097  case ISD::AND:            return PerformAndCombine(N, DAG, DCI, Subtarget);
16098  case ISD::OR:             return PerformOrCombine(N, DAG, DCI, Subtarget);
16099  case ISD::XOR:            return PerformXorCombine(N, DAG, DCI, Subtarget);
16100  case ISD::LOAD:           return PerformLOADCombine(N, DAG, DCI, Subtarget);
16101  case ISD::STORE:          return PerformSTORECombine(N, DAG, Subtarget);
16102  case ISD::UINT_TO_FP:     return PerformUINT_TO_FPCombine(N, DAG);
16103  case ISD::SINT_TO_FP:     return PerformSINT_TO_FPCombine(N, DAG, this);
16104  case ISD::FP_TO_SINT:     return PerformFP_TO_SINTCombine(N, DAG);
16105  case ISD::FADD:           return PerformFADDCombine(N, DAG, Subtarget);
16106  case ISD::FSUB:           return PerformFSUBCombine(N, DAG, Subtarget);
16107  case X86ISD::FXOR:
16108  case X86ISD::FOR:         return PerformFORCombine(N, DAG);
16109  case X86ISD::FMIN:
16110  case X86ISD::FMAX:        return PerformFMinFMaxCombine(N, DAG);
16111  case X86ISD::FAND:        return PerformFANDCombine(N, DAG);
16112  case X86ISD::BT:          return PerformBTCombine(N, DAG, DCI);
16113  case X86ISD::VZEXT_MOVL:  return PerformVZEXT_MOVLCombine(N, DAG);
16114  case ISD::ANY_EXTEND:
16115  case ISD::ZERO_EXTEND:    return PerformZExtCombine(N, DAG, DCI, Subtarget);
16116  case ISD::SIGN_EXTEND:    return PerformSExtCombine(N, DAG, DCI, Subtarget);
16117  case ISD::TRUNCATE:       return PerformTruncateCombine(N, DAG, DCI);
16118  case ISD::SETCC:          return PerformISDSETCCCombine(N, DAG);
16119  case X86ISD::SETCC:       return PerformSETCCCombine(N, DAG, DCI, Subtarget);
16120  case X86ISD::BRCOND:      return PerformBrCondCombine(N, DAG, DCI, Subtarget);
16121  case X86ISD::SHUFP:       // Handle all target specific shuffles
16122  case X86ISD::PALIGN:
16123  case X86ISD::UNPCKH:
16124  case X86ISD::UNPCKL:
16125  case X86ISD::MOVHLPS:
16126  case X86ISD::MOVLHPS:
16127  case X86ISD::PSHUFD:
16128  case X86ISD::PSHUFHW:
16129  case X86ISD::PSHUFLW:
16130  case X86ISD::MOVSS:
16131  case X86ISD::MOVSD:
16132  case X86ISD::VPERMILP:
16133  case X86ISD::VPERM2X128:
16134  case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
16135  case ISD::FMA:            return PerformFMACombine(N, DAG, Subtarget);
16136  }
16137
16138  return SDValue();
16139}
16140
16141/// isTypeDesirableForOp - Return true if the target has native support for
16142/// the specified value type and it is 'desirable' to use the type for the
16143/// given node type. e.g. On x86 i16 is legal, but undesirable since i16
16144/// instruction encodings are longer and some i16 instructions are slow.
16145bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
16146  if (!isTypeLegal(VT))
16147    return false;
16148  if (VT != MVT::i16)
16149    return true;
16150
16151  switch (Opc) {
16152  default:
16153    return true;
16154  case ISD::LOAD:
16155  case ISD::SIGN_EXTEND:
16156  case ISD::ZERO_EXTEND:
16157  case ISD::ANY_EXTEND:
16158  case ISD::SHL:
16159  case ISD::SRL:
16160  case ISD::SUB:
16161  case ISD::ADD:
16162  case ISD::MUL:
16163  case ISD::AND:
16164  case ISD::OR:
16165  case ISD::XOR:
16166    return false;
16167  }
16168}
16169
16170/// IsDesirableToPromoteOp - This method query the target whether it is
16171/// beneficial for dag combiner to promote the specified node. If true, it
16172/// should return the desired promotion type by reference.
16173bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
16174  EVT VT = Op.getValueType();
16175  if (VT != MVT::i16)
16176    return false;
16177
16178  bool Promote = false;
16179  bool Commute = false;
16180  switch (Op.getOpcode()) {
16181  default: break;
16182  case ISD::LOAD: {
16183    LoadSDNode *LD = cast<LoadSDNode>(Op);
16184    // If the non-extending load has a single use and it's not live out, then it
16185    // might be folded.
16186    if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
16187                                                     Op.hasOneUse()*/) {
16188      for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
16189             UE = Op.getNode()->use_end(); UI != UE; ++UI) {
16190        // The only case where we'd want to promote LOAD (rather then it being
16191        // promoted as an operand is when it's only use is liveout.
16192        if (UI->getOpcode() != ISD::CopyToReg)
16193          return false;
16194      }
16195    }
16196    Promote = true;
16197    break;
16198  }
16199  case ISD::SIGN_EXTEND:
16200  case ISD::ZERO_EXTEND:
16201  case ISD::ANY_EXTEND:
16202    Promote = true;
16203    break;
16204  case ISD::SHL:
16205  case ISD::SRL: {
16206    SDValue N0 = Op.getOperand(0);
16207    // Look out for (store (shl (load), x)).
16208    if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
16209      return false;
16210    Promote = true;
16211    break;
16212  }
16213  case ISD::ADD:
16214  case ISD::MUL:
16215  case ISD::AND:
16216  case ISD::OR:
16217  case ISD::XOR:
16218    Commute = true;
16219    // fallthrough
16220  case ISD::SUB: {
16221    SDValue N0 = Op.getOperand(0);
16222    SDValue N1 = Op.getOperand(1);
16223    if (!Commute && MayFoldLoad(N1))
16224      return false;
16225    // Avoid disabling potential load folding opportunities.
16226    if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
16227      return false;
16228    if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
16229      return false;
16230    Promote = true;
16231  }
16232  }
16233
16234  PVT = MVT::i32;
16235  return Promote;
16236}
16237
16238//===----------------------------------------------------------------------===//
16239//                           X86 Inline Assembly Support
16240//===----------------------------------------------------------------------===//
16241
16242namespace {
16243  // Helper to match a string separated by whitespace.
16244  bool matchAsmImpl(StringRef s, ArrayRef<const StringRef *> args) {
16245    s = s.substr(s.find_first_not_of(" \t")); // Skip leading whitespace.
16246
16247    for (unsigned i = 0, e = args.size(); i != e; ++i) {
16248      StringRef piece(*args[i]);
16249      if (!s.startswith(piece)) // Check if the piece matches.
16250        return false;
16251
16252      s = s.substr(piece.size());
16253      StringRef::size_type pos = s.find_first_not_of(" \t");
16254      if (pos == 0) // We matched a prefix.
16255        return false;
16256
16257      s = s.substr(pos);
16258    }
16259
16260    return s.empty();
16261  }
16262  const VariadicFunction1<bool, StringRef, StringRef, matchAsmImpl> matchAsm={};
16263}
16264
16265bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
16266  InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
16267
16268  std::string AsmStr = IA->getAsmString();
16269
16270  IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
16271  if (!Ty || Ty->getBitWidth() % 16 != 0)
16272    return false;
16273
16274  // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
16275  SmallVector<StringRef, 4> AsmPieces;
16276  SplitString(AsmStr, AsmPieces, ";\n");
16277
16278  switch (AsmPieces.size()) {
16279  default: return false;
16280  case 1:
16281    // FIXME: this should verify that we are targeting a 486 or better.  If not,
16282    // we will turn this bswap into something that will be lowered to logical
16283    // ops instead of emitting the bswap asm.  For now, we don't support 486 or
16284    // lower so don't worry about this.
16285    // bswap $0
16286    if (matchAsm(AsmPieces[0], "bswap", "$0") ||
16287        matchAsm(AsmPieces[0], "bswapl", "$0") ||
16288        matchAsm(AsmPieces[0], "bswapq", "$0") ||
16289        matchAsm(AsmPieces[0], "bswap", "${0:q}") ||
16290        matchAsm(AsmPieces[0], "bswapl", "${0:q}") ||
16291        matchAsm(AsmPieces[0], "bswapq", "${0:q}")) {
16292      // No need to check constraints, nothing other than the equivalent of
16293      // "=r,0" would be valid here.
16294      return IntrinsicLowering::LowerToByteSwap(CI);
16295    }
16296
16297    // rorw $$8, ${0:w}  -->  llvm.bswap.i16
16298    if (CI->getType()->isIntegerTy(16) &&
16299        IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
16300        (matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") ||
16301         matchAsm(AsmPieces[0], "rolw", "$$8,", "${0:w}"))) {
16302      AsmPieces.clear();
16303      const std::string &ConstraintsStr = IA->getConstraintString();
16304      SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
16305      std::sort(AsmPieces.begin(), AsmPieces.end());
16306      if (AsmPieces.size() == 4 &&
16307          AsmPieces[0] == "~{cc}" &&
16308          AsmPieces[1] == "~{dirflag}" &&
16309          AsmPieces[2] == "~{flags}" &&
16310          AsmPieces[3] == "~{fpsr}")
16311      return IntrinsicLowering::LowerToByteSwap(CI);
16312    }
16313    break;
16314  case 3:
16315    if (CI->getType()->isIntegerTy(32) &&
16316        IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
16317        matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") &&
16318        matchAsm(AsmPieces[1], "rorl", "$$16,", "$0") &&
16319        matchAsm(AsmPieces[2], "rorw", "$$8,", "${0:w}")) {
16320      AsmPieces.clear();
16321      const std::string &ConstraintsStr = IA->getConstraintString();
16322      SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
16323      std::sort(AsmPieces.begin(), AsmPieces.end());
16324      if (AsmPieces.size() == 4 &&
16325          AsmPieces[0] == "~{cc}" &&
16326          AsmPieces[1] == "~{dirflag}" &&
16327          AsmPieces[2] == "~{flags}" &&
16328          AsmPieces[3] == "~{fpsr}")
16329        return IntrinsicLowering::LowerToByteSwap(CI);
16330    }
16331
16332    if (CI->getType()->isIntegerTy(64)) {
16333      InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
16334      if (Constraints.size() >= 2 &&
16335          Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
16336          Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
16337        // bswap %eax / bswap %edx / xchgl %eax, %edx  -> llvm.bswap.i64
16338        if (matchAsm(AsmPieces[0], "bswap", "%eax") &&
16339            matchAsm(AsmPieces[1], "bswap", "%edx") &&
16340            matchAsm(AsmPieces[2], "xchgl", "%eax,", "%edx"))
16341          return IntrinsicLowering::LowerToByteSwap(CI);
16342      }
16343    }
16344    break;
16345  }
16346  return false;
16347}
16348
16349
16350
16351/// getConstraintType - Given a constraint letter, return the type of
16352/// constraint it is for this target.
16353X86TargetLowering::ConstraintType
16354X86TargetLowering::getConstraintType(const std::string &Constraint) const {
16355  if (Constraint.size() == 1) {
16356    switch (Constraint[0]) {
16357    case 'R':
16358    case 'q':
16359    case 'Q':
16360    case 'f':
16361    case 't':
16362    case 'u':
16363    case 'y':
16364    case 'x':
16365    case 'Y':
16366    case 'l':
16367      return C_RegisterClass;
16368    case 'a':
16369    case 'b':
16370    case 'c':
16371    case 'd':
16372    case 'S':
16373    case 'D':
16374    case 'A':
16375      return C_Register;
16376    case 'I':
16377    case 'J':
16378    case 'K':
16379    case 'L':
16380    case 'M':
16381    case 'N':
16382    case 'G':
16383    case 'C':
16384    case 'e':
16385    case 'Z':
16386      return C_Other;
16387    default:
16388      break;
16389    }
16390  }
16391  return TargetLowering::getConstraintType(Constraint);
16392}
16393
16394/// Examine constraint type and operand type and determine a weight value.
16395/// This object must already have been set up with the operand type
16396/// and the current alternative constraint selected.
16397TargetLowering::ConstraintWeight
16398  X86TargetLowering::getSingleConstraintMatchWeight(
16399    AsmOperandInfo &info, const char *constraint) const {
16400  ConstraintWeight weight = CW_Invalid;
16401  Value *CallOperandVal = info.CallOperandVal;
16402    // If we don't have a value, we can't do a match,
16403    // but allow it at the lowest weight.
16404  if (CallOperandVal == NULL)
16405    return CW_Default;
16406  Type *type = CallOperandVal->getType();
16407  // Look at the constraint type.
16408  switch (*constraint) {
16409  default:
16410    weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
16411  case 'R':
16412  case 'q':
16413  case 'Q':
16414  case 'a':
16415  case 'b':
16416  case 'c':
16417  case 'd':
16418  case 'S':
16419  case 'D':
16420  case 'A':
16421    if (CallOperandVal->getType()->isIntegerTy())
16422      weight = CW_SpecificReg;
16423    break;
16424  case 'f':
16425  case 't':
16426  case 'u':
16427      if (type->isFloatingPointTy())
16428        weight = CW_SpecificReg;
16429      break;
16430  case 'y':
16431      if (type->isX86_MMXTy() && Subtarget->hasMMX())
16432        weight = CW_SpecificReg;
16433      break;
16434  case 'x':
16435  case 'Y':
16436    if (((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasSSE1()) ||
16437        ((type->getPrimitiveSizeInBits() == 256) && Subtarget->hasAVX()))
16438      weight = CW_Register;
16439    break;
16440  case 'I':
16441    if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
16442      if (C->getZExtValue() <= 31)
16443        weight = CW_Constant;
16444    }
16445    break;
16446  case 'J':
16447    if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
16448      if (C->getZExtValue() <= 63)
16449        weight = CW_Constant;
16450    }
16451    break;
16452  case 'K':
16453    if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
16454      if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
16455        weight = CW_Constant;
16456    }
16457    break;
16458  case 'L':
16459    if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
16460      if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
16461        weight = CW_Constant;
16462    }
16463    break;
16464  case 'M':
16465    if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
16466      if (C->getZExtValue() <= 3)
16467        weight = CW_Constant;
16468    }
16469    break;
16470  case 'N':
16471    if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
16472      if (C->getZExtValue() <= 0xff)
16473        weight = CW_Constant;
16474    }
16475    break;
16476  case 'G':
16477  case 'C':
16478    if (dyn_cast<ConstantFP>(CallOperandVal)) {
16479      weight = CW_Constant;
16480    }
16481    break;
16482  case 'e':
16483    if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
16484      if ((C->getSExtValue() >= -0x80000000LL) &&
16485          (C->getSExtValue() <= 0x7fffffffLL))
16486        weight = CW_Constant;
16487    }
16488    break;
16489  case 'Z':
16490    if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
16491      if (C->getZExtValue() <= 0xffffffff)
16492        weight = CW_Constant;
16493    }
16494    break;
16495  }
16496  return weight;
16497}
16498
16499/// LowerXConstraint - try to replace an X constraint, which matches anything,
16500/// with another that has more specific requirements based on the type of the
16501/// corresponding operand.
16502const char *X86TargetLowering::
16503LowerXConstraint(EVT ConstraintVT) const {
16504  // FP X constraints get lowered to SSE1/2 registers if available, otherwise
16505  // 'f' like normal targets.
16506  if (ConstraintVT.isFloatingPoint()) {
16507    if (Subtarget->hasSSE2())
16508      return "Y";
16509    if (Subtarget->hasSSE1())
16510      return "x";
16511  }
16512
16513  return TargetLowering::LowerXConstraint(ConstraintVT);
16514}
16515
16516/// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
16517/// vector.  If it is invalid, don't add anything to Ops.
16518void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
16519                                                     std::string &Constraint,
16520                                                     std::vector<SDValue>&Ops,
16521                                                     SelectionDAG &DAG) const {
16522  SDValue Result(0, 0);
16523
16524  // Only support length 1 constraints for now.
16525  if (Constraint.length() > 1) return;
16526
16527  char ConstraintLetter = Constraint[0];
16528  switch (ConstraintLetter) {
16529  default: break;
16530  case 'I':
16531    if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
16532      if (C->getZExtValue() <= 31) {
16533        Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
16534        break;
16535      }
16536    }
16537    return;
16538  case 'J':
16539    if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
16540      if (C->getZExtValue() <= 63) {
16541        Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
16542        break;
16543      }
16544    }
16545    return;
16546  case 'K':
16547    if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
16548      if ((int8_t)C->getSExtValue() == C->getSExtValue()) {
16549        Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
16550        break;
16551      }
16552    }
16553    return;
16554  case 'N':
16555    if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
16556      if (C->getZExtValue() <= 255) {
16557        Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
16558        break;
16559      }
16560    }
16561    return;
16562  case 'e': {
16563    // 32-bit signed value
16564    if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
16565      if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
16566                                           C->getSExtValue())) {
16567        // Widen to 64 bits here to get it sign extended.
16568        Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
16569        break;
16570      }
16571    // FIXME gcc accepts some relocatable values here too, but only in certain
16572    // memory models; it's complicated.
16573    }
16574    return;
16575  }
16576  case 'Z': {
16577    // 32-bit unsigned value
16578    if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
16579      if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
16580                                           C->getZExtValue())) {
16581        Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
16582        break;
16583      }
16584    }
16585    // FIXME gcc accepts some relocatable values here too, but only in certain
16586    // memory models; it's complicated.
16587    return;
16588  }
16589  case 'i': {
16590    // Literal immediates are always ok.
16591    if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
16592      // Widen to 64 bits here to get it sign extended.
16593      Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
16594      break;
16595    }
16596
16597    // In any sort of PIC mode addresses need to be computed at runtime by
16598    // adding in a register or some sort of table lookup.  These can't
16599    // be used as immediates.
16600    if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
16601      return;
16602
16603    // If we are in non-pic codegen mode, we allow the address of a global (with
16604    // an optional displacement) to be used with 'i'.
16605    GlobalAddressSDNode *GA = 0;
16606    int64_t Offset = 0;
16607
16608    // Match either (GA), (GA+C), (GA+C1+C2), etc.
16609    while (1) {
16610      if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
16611        Offset += GA->getOffset();
16612        break;
16613      } else if (Op.getOpcode() == ISD::ADD) {
16614        if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
16615          Offset += C->getZExtValue();
16616          Op = Op.getOperand(0);
16617          continue;
16618        }
16619      } else if (Op.getOpcode() == ISD::SUB) {
16620        if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
16621          Offset += -C->getZExtValue();
16622          Op = Op.getOperand(0);
16623          continue;
16624        }
16625      }
16626
16627      // Otherwise, this isn't something we can handle, reject it.
16628      return;
16629    }
16630
16631    const GlobalValue *GV = GA->getGlobal();
16632    // If we require an extra load to get this address, as in PIC mode, we
16633    // can't accept it.
16634    if (isGlobalStubReference(Subtarget->ClassifyGlobalReference(GV,
16635                                                        getTargetMachine())))
16636      return;
16637
16638    Result = DAG.getTargetGlobalAddress(GV, Op.getDebugLoc(),
16639                                        GA->getValueType(0), Offset);
16640    break;
16641  }
16642  }
16643
16644  if (Result.getNode()) {
16645    Ops.push_back(Result);
16646    return;
16647  }
16648  return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
16649}
16650
16651std::pair<unsigned, const TargetRegisterClass*>
16652X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
16653                                                EVT VT) const {
16654  // First, see if this is a constraint that directly corresponds to an LLVM
16655  // register class.
16656  if (Constraint.size() == 1) {
16657    // GCC Constraint Letters
16658    switch (Constraint[0]) {
16659    default: break;
16660      // TODO: Slight differences here in allocation order and leaving
16661      // RIP in the class. Do they matter any more here than they do
16662      // in the normal allocation?
16663    case 'q':   // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
16664      if (Subtarget->is64Bit()) {
16665        if (VT == MVT::i32 || VT == MVT::f32)
16666          return std::make_pair(0U, &X86::GR32RegClass);
16667        if (VT == MVT::i16)
16668          return std::make_pair(0U, &X86::GR16RegClass);
16669        if (VT == MVT::i8 || VT == MVT::i1)
16670          return std::make_pair(0U, &X86::GR8RegClass);
16671        if (VT == MVT::i64 || VT == MVT::f64)
16672          return std::make_pair(0U, &X86::GR64RegClass);
16673        break;
16674      }
16675      // 32-bit fallthrough
16676    case 'Q':   // Q_REGS
16677      if (VT == MVT::i32 || VT == MVT::f32)
16678        return std::make_pair(0U, &X86::GR32_ABCDRegClass);
16679      if (VT == MVT::i16)
16680        return std::make_pair(0U, &X86::GR16_ABCDRegClass);
16681      if (VT == MVT::i8 || VT == MVT::i1)
16682        return std::make_pair(0U, &X86::GR8_ABCD_LRegClass);
16683      if (VT == MVT::i64)
16684        return std::make_pair(0U, &X86::GR64_ABCDRegClass);
16685      break;
16686    case 'r':   // GENERAL_REGS
16687    case 'l':   // INDEX_REGS
16688      if (VT == MVT::i8 || VT == MVT::i1)
16689        return std::make_pair(0U, &X86::GR8RegClass);
16690      if (VT == MVT::i16)
16691        return std::make_pair(0U, &X86::GR16RegClass);
16692      if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
16693        return std::make_pair(0U, &X86::GR32RegClass);
16694      return std::make_pair(0U, &X86::GR64RegClass);
16695    case 'R':   // LEGACY_REGS
16696      if (VT == MVT::i8 || VT == MVT::i1)
16697        return std::make_pair(0U, &X86::GR8_NOREXRegClass);
16698      if (VT == MVT::i16)
16699        return std::make_pair(0U, &X86::GR16_NOREXRegClass);
16700      if (VT == MVT::i32 || !Subtarget->is64Bit())
16701        return std::make_pair(0U, &X86::GR32_NOREXRegClass);
16702      return std::make_pair(0U, &X86::GR64_NOREXRegClass);
16703    case 'f':  // FP Stack registers.
16704      // If SSE is enabled for this VT, use f80 to ensure the isel moves the
16705      // value to the correct fpstack register class.
16706      if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
16707        return std::make_pair(0U, &X86::RFP32RegClass);
16708      if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
16709        return std::make_pair(0U, &X86::RFP64RegClass);
16710      return std::make_pair(0U, &X86::RFP80RegClass);
16711    case 'y':   // MMX_REGS if MMX allowed.
16712      if (!Subtarget->hasMMX()) break;
16713      return std::make_pair(0U, &X86::VR64RegClass);
16714    case 'Y':   // SSE_REGS if SSE2 allowed
16715      if (!Subtarget->hasSSE2()) break;
16716      // FALL THROUGH.
16717    case 'x':   // SSE_REGS if SSE1 allowed or AVX_REGS if AVX allowed
16718      if (!Subtarget->hasSSE1()) break;
16719
16720      switch (VT.getSimpleVT().SimpleTy) {
16721      default: break;
16722      // Scalar SSE types.
16723      case MVT::f32:
16724      case MVT::i32:
16725        return std::make_pair(0U, &X86::FR32RegClass);
16726      case MVT::f64:
16727      case MVT::i64:
16728        return std::make_pair(0U, &X86::FR64RegClass);
16729      // Vector types.
16730      case MVT::v16i8:
16731      case MVT::v8i16:
16732      case MVT::v4i32:
16733      case MVT::v2i64:
16734      case MVT::v4f32:
16735      case MVT::v2f64:
16736        return std::make_pair(0U, &X86::VR128RegClass);
16737      // AVX types.
16738      case MVT::v32i8:
16739      case MVT::v16i16:
16740      case MVT::v8i32:
16741      case MVT::v4i64:
16742      case MVT::v8f32:
16743      case MVT::v4f64:
16744        return std::make_pair(0U, &X86::VR256RegClass);
16745      }
16746      break;
16747    }
16748  }
16749
16750  // Use the default implementation in TargetLowering to convert the register
16751  // constraint into a member of a register class.
16752  std::pair<unsigned, const TargetRegisterClass*> Res;
16753  Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
16754
16755  // Not found as a standard register?
16756  if (Res.second == 0) {
16757    // Map st(0) -> st(7) -> ST0
16758    if (Constraint.size() == 7 && Constraint[0] == '{' &&
16759        std::tolower(Constraint[1]) == 's' &&
16760        std::tolower(Constraint[2]) == 't' &&
16761        Constraint[3] == '(' &&
16762        (Constraint[4] >= '0' && Constraint[4] <= '7') &&
16763        Constraint[5] == ')' &&
16764        Constraint[6] == '}') {
16765
16766      Res.first = X86::ST0+Constraint[4]-'0';
16767      Res.second = &X86::RFP80RegClass;
16768      return Res;
16769    }
16770
16771    // GCC allows "st(0)" to be called just plain "st".
16772    if (StringRef("{st}").equals_lower(Constraint)) {
16773      Res.first = X86::ST0;
16774      Res.second = &X86::RFP80RegClass;
16775      return Res;
16776    }
16777
16778    // flags -> EFLAGS
16779    if (StringRef("{flags}").equals_lower(Constraint)) {
16780      Res.first = X86::EFLAGS;
16781      Res.second = &X86::CCRRegClass;
16782      return Res;
16783    }
16784
16785    // 'A' means EAX + EDX.
16786    if (Constraint == "A") {
16787      Res.first = X86::EAX;
16788      Res.second = &X86::GR32_ADRegClass;
16789      return Res;
16790    }
16791    return Res;
16792  }
16793
16794  // Otherwise, check to see if this is a register class of the wrong value
16795  // type.  For example, we want to map "{ax},i32" -> {eax}, we don't want it to
16796  // turn into {ax},{dx}.
16797  if (Res.second->hasType(VT))
16798    return Res;   // Correct type already, nothing to do.
16799
16800  // All of the single-register GCC register classes map their values onto
16801  // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp".  If we
16802  // really want an 8-bit or 32-bit register, map to the appropriate register
16803  // class and return the appropriate register.
16804  if (Res.second == &X86::GR16RegClass) {
16805    if (VT == MVT::i8) {
16806      unsigned DestReg = 0;
16807      switch (Res.first) {
16808      default: break;
16809      case X86::AX: DestReg = X86::AL; break;
16810      case X86::DX: DestReg = X86::DL; break;
16811      case X86::CX: DestReg = X86::CL; break;
16812      case X86::BX: DestReg = X86::BL; break;
16813      }
16814      if (DestReg) {
16815        Res.first = DestReg;
16816        Res.second = &X86::GR8RegClass;
16817      }
16818    } else if (VT == MVT::i32) {
16819      unsigned DestReg = 0;
16820      switch (Res.first) {
16821      default: break;
16822      case X86::AX: DestReg = X86::EAX; break;
16823      case X86::DX: DestReg = X86::EDX; break;
16824      case X86::CX: DestReg = X86::ECX; break;
16825      case X86::BX: DestReg = X86::EBX; break;
16826      case X86::SI: DestReg = X86::ESI; break;
16827      case X86::DI: DestReg = X86::EDI; break;
16828      case X86::BP: DestReg = X86::EBP; break;
16829      case X86::SP: DestReg = X86::ESP; break;
16830      }
16831      if (DestReg) {
16832        Res.first = DestReg;
16833        Res.second = &X86::GR32RegClass;
16834      }
16835    } else if (VT == MVT::i64) {
16836      unsigned DestReg = 0;
16837      switch (Res.first) {
16838      default: break;
16839      case X86::AX: DestReg = X86::RAX; break;
16840      case X86::DX: DestReg = X86::RDX; break;
16841      case X86::CX: DestReg = X86::RCX; break;
16842      case X86::BX: DestReg = X86::RBX; break;
16843      case X86::SI: DestReg = X86::RSI; break;
16844      case X86::DI: DestReg = X86::RDI; break;
16845      case X86::BP: DestReg = X86::RBP; break;
16846      case X86::SP: DestReg = X86::RSP; break;
16847      }
16848      if (DestReg) {
16849        Res.first = DestReg;
16850        Res.second = &X86::GR64RegClass;
16851      }
16852    }
16853  } else if (Res.second == &X86::FR32RegClass ||
16854             Res.second == &X86::FR64RegClass ||
16855             Res.second == &X86::VR128RegClass) {
16856    // Handle references to XMM physical registers that got mapped into the
16857    // wrong class.  This can happen with constraints like {xmm0} where the
16858    // target independent register mapper will just pick the first match it can
16859    // find, ignoring the required type.
16860
16861    if (VT == MVT::f32 || VT == MVT::i32)
16862      Res.second = &X86::FR32RegClass;
16863    else if (VT == MVT::f64 || VT == MVT::i64)
16864      Res.second = &X86::FR64RegClass;
16865    else if (X86::VR128RegClass.hasType(VT))
16866      Res.second = &X86::VR128RegClass;
16867    else if (X86::VR256RegClass.hasType(VT))
16868      Res.second = &X86::VR256RegClass;
16869  }
16870
16871  return Res;
16872}
16873