X86ISelLowering.cpp revision 13f8cf55d43980e73d6cbb8f4894607709daa311
1//===-- X86ISelLowering.cpp - X86 DAG Lowering Implementation -------------===//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file defines the interfaces that X86 uses to lower LLVM code into a
11// selection DAG.
12//
13//===----------------------------------------------------------------------===//
14
15#define DEBUG_TYPE "x86-isel"
16#include "X86ISelLowering.h"
17#include "Utils/X86ShuffleDecode.h"
18#include "X86.h"
19#include "X86InstrBuilder.h"
20#include "X86TargetMachine.h"
21#include "X86TargetObjectFile.h"
22#include "llvm/ADT/SmallSet.h"
23#include "llvm/ADT/Statistic.h"
24#include "llvm/ADT/StringExtras.h"
25#include "llvm/ADT/VariadicFunction.h"
26#include "llvm/CodeGen/IntrinsicLowering.h"
27#include "llvm/CodeGen/MachineFrameInfo.h"
28#include "llvm/CodeGen/MachineFunction.h"
29#include "llvm/CodeGen/MachineInstrBuilder.h"
30#include "llvm/CodeGen/MachineJumpTableInfo.h"
31#include "llvm/CodeGen/MachineModuleInfo.h"
32#include "llvm/CodeGen/MachineRegisterInfo.h"
33#include "llvm/IR/CallingConv.h"
34#include "llvm/IR/Constants.h"
35#include "llvm/IR/DerivedTypes.h"
36#include "llvm/IR/Function.h"
37#include "llvm/IR/GlobalAlias.h"
38#include "llvm/IR/GlobalVariable.h"
39#include "llvm/IR/Instructions.h"
40#include "llvm/IR/Intrinsics.h"
41#include "llvm/IR/LLVMContext.h"
42#include "llvm/MC/MCAsmInfo.h"
43#include "llvm/MC/MCContext.h"
44#include "llvm/MC/MCExpr.h"
45#include "llvm/MC/MCSymbol.h"
46#include "llvm/Support/CallSite.h"
47#include "llvm/Support/Debug.h"
48#include "llvm/Support/ErrorHandling.h"
49#include "llvm/Support/MathExtras.h"
50#include "llvm/Target/TargetOptions.h"
51#include <bitset>
52#include <cctype>
53using namespace llvm;
54
55STATISTIC(NumTailCalls, "Number of tail calls");
56
57// Forward declarations.
58static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
59                       SDValue V2);
60
61/// Generate a DAG to grab 128-bits from a vector > 128 bits.  This
62/// sets things up to match to an AVX VEXTRACTF128 instruction or a
63/// simple subregister reference.  Idx is an index in the 128 bits we
64/// want.  It need not be aligned to a 128-bit bounday.  That makes
65/// lowering EXTRACT_VECTOR_ELT operations easier.
66static SDValue Extract128BitVector(SDValue Vec, unsigned IdxVal,
67                                   SelectionDAG &DAG, DebugLoc dl) {
68  EVT VT = Vec.getValueType();
69  assert(VT.is256BitVector() && "Unexpected vector size!");
70  EVT ElVT = VT.getVectorElementType();
71  unsigned Factor = VT.getSizeInBits()/128;
72  EVT ResultVT = EVT::getVectorVT(*DAG.getContext(), ElVT,
73                                  VT.getVectorNumElements()/Factor);
74
75  // Extract from UNDEF is UNDEF.
76  if (Vec.getOpcode() == ISD::UNDEF)
77    return DAG.getUNDEF(ResultVT);
78
79  // Extract the relevant 128 bits.  Generate an EXTRACT_SUBVECTOR
80  // we can match to VEXTRACTF128.
81  unsigned ElemsPerChunk = 128 / ElVT.getSizeInBits();
82
83  // This is the index of the first element of the 128-bit chunk
84  // we want.
85  unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits()) / 128)
86                               * ElemsPerChunk);
87
88  SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal);
89  SDValue Result = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, ResultVT, Vec,
90                               VecIdx);
91
92  return Result;
93}
94
95/// Generate a DAG to put 128-bits into a vector > 128 bits.  This
96/// sets things up to match to an AVX VINSERTF128 instruction or a
97/// simple superregister reference.  Idx is an index in the 128 bits
98/// we want.  It need not be aligned to a 128-bit bounday.  That makes
99/// lowering INSERT_VECTOR_ELT operations easier.
100static SDValue Insert128BitVector(SDValue Result, SDValue Vec,
101                                  unsigned IdxVal, SelectionDAG &DAG,
102                                  DebugLoc dl) {
103  // Inserting UNDEF is Result
104  if (Vec.getOpcode() == ISD::UNDEF)
105    return Result;
106
107  EVT VT = Vec.getValueType();
108  assert(VT.is128BitVector() && "Unexpected vector size!");
109
110  EVT ElVT = VT.getVectorElementType();
111  EVT ResultVT = Result.getValueType();
112
113  // Insert the relevant 128 bits.
114  unsigned ElemsPerChunk = 128/ElVT.getSizeInBits();
115
116  // This is the index of the first element of the 128-bit chunk
117  // we want.
118  unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits())/128)
119                               * ElemsPerChunk);
120
121  SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal);
122  return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Result, Vec,
123                     VecIdx);
124}
125
126/// Concat two 128-bit vectors into a 256 bit vector using VINSERTF128
127/// instructions. This is used because creating CONCAT_VECTOR nodes of
128/// BUILD_VECTORS returns a larger BUILD_VECTOR while we're trying to lower
129/// large BUILD_VECTORS.
130static SDValue Concat128BitVectors(SDValue V1, SDValue V2, EVT VT,
131                                   unsigned NumElems, SelectionDAG &DAG,
132                                   DebugLoc dl) {
133  SDValue V = Insert128BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
134  return Insert128BitVector(V, V2, NumElems/2, DAG, dl);
135}
136
137static TargetLoweringObjectFile *createTLOF(X86TargetMachine &TM) {
138  const X86Subtarget *Subtarget = &TM.getSubtarget<X86Subtarget>();
139  bool is64Bit = Subtarget->is64Bit();
140
141  if (Subtarget->isTargetEnvMacho()) {
142    if (is64Bit)
143      return new X86_64MachoTargetObjectFile();
144    return new TargetLoweringObjectFileMachO();
145  }
146
147  if (Subtarget->isTargetLinux())
148    return new X86LinuxTargetObjectFile();
149  if (Subtarget->isTargetELF())
150    return new TargetLoweringObjectFileELF();
151  if (Subtarget->isTargetCOFF() && !Subtarget->isTargetEnvMacho())
152    return new TargetLoweringObjectFileCOFF();
153  llvm_unreachable("unknown subtarget type");
154}
155
156X86TargetLowering::X86TargetLowering(X86TargetMachine &TM)
157  : TargetLowering(TM, createTLOF(TM)) {
158  Subtarget = &TM.getSubtarget<X86Subtarget>();
159  X86ScalarSSEf64 = Subtarget->hasSSE2();
160  X86ScalarSSEf32 = Subtarget->hasSSE1();
161
162  RegInfo = TM.getRegisterInfo();
163  TD = getDataLayout();
164
165  // Set up the TargetLowering object.
166  static const MVT IntVTs[] = { MVT::i8, MVT::i16, MVT::i32, MVT::i64 };
167
168  // X86 is weird, it always uses i8 for shift amounts and setcc results.
169  setBooleanContents(ZeroOrOneBooleanContent);
170  // X86-SSE is even stranger. It uses -1 or 0 for vector masks.
171  setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
172
173  // For 64-bit since we have so many registers use the ILP scheduler, for
174  // 32-bit code use the register pressure specific scheduling.
175  // For Atom, always use ILP scheduling.
176  if (Subtarget->isAtom())
177    setSchedulingPreference(Sched::ILP);
178  else if (Subtarget->is64Bit())
179    setSchedulingPreference(Sched::ILP);
180  else
181    setSchedulingPreference(Sched::RegPressure);
182  setStackPointerRegisterToSaveRestore(RegInfo->getStackRegister());
183
184  // Bypass i32 with i8 on Atom when compiling with O2
185  if (Subtarget->hasSlowDivide() && TM.getOptLevel() >= CodeGenOpt::Default)
186    addBypassSlowDiv(32, 8);
187
188  if (Subtarget->isTargetWindows() && !Subtarget->isTargetCygMing()) {
189    // Setup Windows compiler runtime calls.
190    setLibcallName(RTLIB::SDIV_I64, "_alldiv");
191    setLibcallName(RTLIB::UDIV_I64, "_aulldiv");
192    setLibcallName(RTLIB::SREM_I64, "_allrem");
193    setLibcallName(RTLIB::UREM_I64, "_aullrem");
194    setLibcallName(RTLIB::MUL_I64, "_allmul");
195    setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::X86_StdCall);
196    setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::X86_StdCall);
197    setLibcallCallingConv(RTLIB::SREM_I64, CallingConv::X86_StdCall);
198    setLibcallCallingConv(RTLIB::UREM_I64, CallingConv::X86_StdCall);
199    setLibcallCallingConv(RTLIB::MUL_I64, CallingConv::X86_StdCall);
200
201    // The _ftol2 runtime function has an unusual calling conv, which
202    // is modeled by a special pseudo-instruction.
203    setLibcallName(RTLIB::FPTOUINT_F64_I64, 0);
204    setLibcallName(RTLIB::FPTOUINT_F32_I64, 0);
205    setLibcallName(RTLIB::FPTOUINT_F64_I32, 0);
206    setLibcallName(RTLIB::FPTOUINT_F32_I32, 0);
207  }
208
209  if (Subtarget->isTargetDarwin()) {
210    // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
211    setUseUnderscoreSetJmp(false);
212    setUseUnderscoreLongJmp(false);
213  } else if (Subtarget->isTargetMingw()) {
214    // MS runtime is weird: it exports _setjmp, but longjmp!
215    setUseUnderscoreSetJmp(true);
216    setUseUnderscoreLongJmp(false);
217  } else {
218    setUseUnderscoreSetJmp(true);
219    setUseUnderscoreLongJmp(true);
220  }
221
222  // Set up the register classes.
223  addRegisterClass(MVT::i8, &X86::GR8RegClass);
224  addRegisterClass(MVT::i16, &X86::GR16RegClass);
225  addRegisterClass(MVT::i32, &X86::GR32RegClass);
226  if (Subtarget->is64Bit())
227    addRegisterClass(MVT::i64, &X86::GR64RegClass);
228
229  setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
230
231  // We don't accept any truncstore of integer registers.
232  setTruncStoreAction(MVT::i64, MVT::i32, Expand);
233  setTruncStoreAction(MVT::i64, MVT::i16, Expand);
234  setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
235  setTruncStoreAction(MVT::i32, MVT::i16, Expand);
236  setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
237  setTruncStoreAction(MVT::i16, MVT::i8,  Expand);
238
239  // SETOEQ and SETUNE require checking two conditions.
240  setCondCodeAction(ISD::SETOEQ, MVT::f32, Expand);
241  setCondCodeAction(ISD::SETOEQ, MVT::f64, Expand);
242  setCondCodeAction(ISD::SETOEQ, MVT::f80, Expand);
243  setCondCodeAction(ISD::SETUNE, MVT::f32, Expand);
244  setCondCodeAction(ISD::SETUNE, MVT::f64, Expand);
245  setCondCodeAction(ISD::SETUNE, MVT::f80, Expand);
246
247  // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
248  // operation.
249  setOperationAction(ISD::UINT_TO_FP       , MVT::i1   , Promote);
250  setOperationAction(ISD::UINT_TO_FP       , MVT::i8   , Promote);
251  setOperationAction(ISD::UINT_TO_FP       , MVT::i16  , Promote);
252
253  if (Subtarget->is64Bit()) {
254    setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Promote);
255    setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Custom);
256  } else if (!TM.Options.UseSoftFloat) {
257    // We have an algorithm for SSE2->double, and we turn this into a
258    // 64-bit FILD followed by conditional FADD for other targets.
259    setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Custom);
260    // We have an algorithm for SSE2, and we turn this into a 64-bit
261    // FILD for other targets.
262    setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Custom);
263  }
264
265  // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
266  // this operation.
267  setOperationAction(ISD::SINT_TO_FP       , MVT::i1   , Promote);
268  setOperationAction(ISD::SINT_TO_FP       , MVT::i8   , Promote);
269
270  if (!TM.Options.UseSoftFloat) {
271    // SSE has no i16 to fp conversion, only i32
272    if (X86ScalarSSEf32) {
273      setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
274      // f32 and f64 cases are Legal, f80 case is not
275      setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
276    } else {
277      setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Custom);
278      setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
279    }
280  } else {
281    setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
282    setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Promote);
283  }
284
285  // In 32-bit mode these are custom lowered.  In 64-bit mode F32 and F64
286  // are Legal, f80 is custom lowered.
287  setOperationAction(ISD::FP_TO_SINT     , MVT::i64  , Custom);
288  setOperationAction(ISD::SINT_TO_FP     , MVT::i64  , Custom);
289
290  // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
291  // this operation.
292  setOperationAction(ISD::FP_TO_SINT       , MVT::i1   , Promote);
293  setOperationAction(ISD::FP_TO_SINT       , MVT::i8   , Promote);
294
295  if (X86ScalarSSEf32) {
296    setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Promote);
297    // f32 and f64 cases are Legal, f80 case is not
298    setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
299  } else {
300    setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Custom);
301    setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
302  }
303
304  // Handle FP_TO_UINT by promoting the destination to a larger signed
305  // conversion.
306  setOperationAction(ISD::FP_TO_UINT       , MVT::i1   , Promote);
307  setOperationAction(ISD::FP_TO_UINT       , MVT::i8   , Promote);
308  setOperationAction(ISD::FP_TO_UINT       , MVT::i16  , Promote);
309
310  if (Subtarget->is64Bit()) {
311    setOperationAction(ISD::FP_TO_UINT     , MVT::i64  , Expand);
312    setOperationAction(ISD::FP_TO_UINT     , MVT::i32  , Promote);
313  } else if (!TM.Options.UseSoftFloat) {
314    // Since AVX is a superset of SSE3, only check for SSE here.
315    if (Subtarget->hasSSE1() && !Subtarget->hasSSE3())
316      // Expand FP_TO_UINT into a select.
317      // FIXME: We would like to use a Custom expander here eventually to do
318      // the optimal thing for SSE vs. the default expansion in the legalizer.
319      setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Expand);
320    else
321      // With SSE3 we can use fisttpll to convert to a signed i64; without
322      // SSE, we're stuck with a fistpll.
323      setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Custom);
324  }
325
326  if (isTargetFTOL()) {
327    // Use the _ftol2 runtime function, which has a pseudo-instruction
328    // to handle its weird calling convention.
329    setOperationAction(ISD::FP_TO_UINT     , MVT::i64  , Custom);
330  }
331
332  // TODO: when we have SSE, these could be more efficient, by using movd/movq.
333  if (!X86ScalarSSEf64) {
334    setOperationAction(ISD::BITCAST        , MVT::f32  , Expand);
335    setOperationAction(ISD::BITCAST        , MVT::i32  , Expand);
336    if (Subtarget->is64Bit()) {
337      setOperationAction(ISD::BITCAST      , MVT::f64  , Expand);
338      // Without SSE, i64->f64 goes through memory.
339      setOperationAction(ISD::BITCAST      , MVT::i64  , Expand);
340    }
341  }
342
343  // Scalar integer divide and remainder are lowered to use operations that
344  // produce two results, to match the available instructions. This exposes
345  // the two-result form to trivial CSE, which is able to combine x/y and x%y
346  // into a single instruction.
347  //
348  // Scalar integer multiply-high is also lowered to use two-result
349  // operations, to match the available instructions. However, plain multiply
350  // (low) operations are left as Legal, as there are single-result
351  // instructions for this in x86. Using the two-result multiply instructions
352  // when both high and low results are needed must be arranged by dagcombine.
353  for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
354    MVT VT = IntVTs[i];
355    setOperationAction(ISD::MULHS, VT, Expand);
356    setOperationAction(ISD::MULHU, VT, Expand);
357    setOperationAction(ISD::SDIV, VT, Expand);
358    setOperationAction(ISD::UDIV, VT, Expand);
359    setOperationAction(ISD::SREM, VT, Expand);
360    setOperationAction(ISD::UREM, VT, Expand);
361
362    // Add/Sub overflow ops with MVT::Glues are lowered to EFLAGS dependences.
363    setOperationAction(ISD::ADDC, VT, Custom);
364    setOperationAction(ISD::ADDE, VT, Custom);
365    setOperationAction(ISD::SUBC, VT, Custom);
366    setOperationAction(ISD::SUBE, VT, Custom);
367  }
368
369  setOperationAction(ISD::BR_JT            , MVT::Other, Expand);
370  setOperationAction(ISD::BRCOND           , MVT::Other, Custom);
371  setOperationAction(ISD::BR_CC            , MVT::Other, Expand);
372  setOperationAction(ISD::SELECT_CC        , MVT::Other, Expand);
373  if (Subtarget->is64Bit())
374    setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
375  setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16  , Legal);
376  setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8   , Legal);
377  setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1   , Expand);
378  setOperationAction(ISD::FP_ROUND_INREG   , MVT::f32  , Expand);
379  setOperationAction(ISD::FREM             , MVT::f32  , Expand);
380  setOperationAction(ISD::FREM             , MVT::f64  , Expand);
381  setOperationAction(ISD::FREM             , MVT::f80  , Expand);
382  setOperationAction(ISD::FLT_ROUNDS_      , MVT::i32  , Custom);
383
384  // Promote the i8 variants and force them on up to i32 which has a shorter
385  // encoding.
386  setOperationAction(ISD::CTTZ             , MVT::i8   , Promote);
387  AddPromotedToType (ISD::CTTZ             , MVT::i8   , MVT::i32);
388  setOperationAction(ISD::CTTZ_ZERO_UNDEF  , MVT::i8   , Promote);
389  AddPromotedToType (ISD::CTTZ_ZERO_UNDEF  , MVT::i8   , MVT::i32);
390  if (Subtarget->hasBMI()) {
391    setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16  , Expand);
392    setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32  , Expand);
393    if (Subtarget->is64Bit())
394      setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
395  } else {
396    setOperationAction(ISD::CTTZ           , MVT::i16  , Custom);
397    setOperationAction(ISD::CTTZ           , MVT::i32  , Custom);
398    if (Subtarget->is64Bit())
399      setOperationAction(ISD::CTTZ         , MVT::i64  , Custom);
400  }
401
402  if (Subtarget->hasLZCNT()) {
403    // When promoting the i8 variants, force them to i32 for a shorter
404    // encoding.
405    setOperationAction(ISD::CTLZ           , MVT::i8   , Promote);
406    AddPromotedToType (ISD::CTLZ           , MVT::i8   , MVT::i32);
407    setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8   , Promote);
408    AddPromotedToType (ISD::CTLZ_ZERO_UNDEF, MVT::i8   , MVT::i32);
409    setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16  , Expand);
410    setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32  , Expand);
411    if (Subtarget->is64Bit())
412      setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
413  } else {
414    setOperationAction(ISD::CTLZ           , MVT::i8   , Custom);
415    setOperationAction(ISD::CTLZ           , MVT::i16  , Custom);
416    setOperationAction(ISD::CTLZ           , MVT::i32  , Custom);
417    setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8   , Custom);
418    setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16  , Custom);
419    setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32  , Custom);
420    if (Subtarget->is64Bit()) {
421      setOperationAction(ISD::CTLZ         , MVT::i64  , Custom);
422      setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Custom);
423    }
424  }
425
426  if (Subtarget->hasPOPCNT()) {
427    setOperationAction(ISD::CTPOP          , MVT::i8   , Promote);
428  } else {
429    setOperationAction(ISD::CTPOP          , MVT::i8   , Expand);
430    setOperationAction(ISD::CTPOP          , MVT::i16  , Expand);
431    setOperationAction(ISD::CTPOP          , MVT::i32  , Expand);
432    if (Subtarget->is64Bit())
433      setOperationAction(ISD::CTPOP        , MVT::i64  , Expand);
434  }
435
436  setOperationAction(ISD::READCYCLECOUNTER , MVT::i64  , Custom);
437  setOperationAction(ISD::BSWAP            , MVT::i16  , Expand);
438
439  // These should be promoted to a larger select which is supported.
440  setOperationAction(ISD::SELECT          , MVT::i1   , Promote);
441  // X86 wants to expand cmov itself.
442  setOperationAction(ISD::SELECT          , MVT::i8   , Custom);
443  setOperationAction(ISD::SELECT          , MVT::i16  , Custom);
444  setOperationAction(ISD::SELECT          , MVT::i32  , Custom);
445  setOperationAction(ISD::SELECT          , MVT::f32  , Custom);
446  setOperationAction(ISD::SELECT          , MVT::f64  , Custom);
447  setOperationAction(ISD::SELECT          , MVT::f80  , Custom);
448  setOperationAction(ISD::SETCC           , MVT::i8   , Custom);
449  setOperationAction(ISD::SETCC           , MVT::i16  , Custom);
450  setOperationAction(ISD::SETCC           , MVT::i32  , Custom);
451  setOperationAction(ISD::SETCC           , MVT::f32  , Custom);
452  setOperationAction(ISD::SETCC           , MVT::f64  , Custom);
453  setOperationAction(ISD::SETCC           , MVT::f80  , Custom);
454  if (Subtarget->is64Bit()) {
455    setOperationAction(ISD::SELECT        , MVT::i64  , Custom);
456    setOperationAction(ISD::SETCC         , MVT::i64  , Custom);
457  }
458  setOperationAction(ISD::EH_RETURN       , MVT::Other, Custom);
459  // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intened to support
460  // SjLj exception handling but a light-weight setjmp/longjmp replacement to
461  // support continuation, user-level threading, and etc.. As a result, no
462  // other SjLj exception interfaces are implemented and please don't build
463  // your own exception handling based on them.
464  // LLVM/Clang supports zero-cost DWARF exception handling.
465  setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
466  setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
467
468  // Darwin ABI issue.
469  setOperationAction(ISD::ConstantPool    , MVT::i32  , Custom);
470  setOperationAction(ISD::JumpTable       , MVT::i32  , Custom);
471  setOperationAction(ISD::GlobalAddress   , MVT::i32  , Custom);
472  setOperationAction(ISD::GlobalTLSAddress, MVT::i32  , Custom);
473  if (Subtarget->is64Bit())
474    setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
475  setOperationAction(ISD::ExternalSymbol  , MVT::i32  , Custom);
476  setOperationAction(ISD::BlockAddress    , MVT::i32  , Custom);
477  if (Subtarget->is64Bit()) {
478    setOperationAction(ISD::ConstantPool  , MVT::i64  , Custom);
479    setOperationAction(ISD::JumpTable     , MVT::i64  , Custom);
480    setOperationAction(ISD::GlobalAddress , MVT::i64  , Custom);
481    setOperationAction(ISD::ExternalSymbol, MVT::i64  , Custom);
482    setOperationAction(ISD::BlockAddress  , MVT::i64  , Custom);
483  }
484  // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
485  setOperationAction(ISD::SHL_PARTS       , MVT::i32  , Custom);
486  setOperationAction(ISD::SRA_PARTS       , MVT::i32  , Custom);
487  setOperationAction(ISD::SRL_PARTS       , MVT::i32  , Custom);
488  if (Subtarget->is64Bit()) {
489    setOperationAction(ISD::SHL_PARTS     , MVT::i64  , Custom);
490    setOperationAction(ISD::SRA_PARTS     , MVT::i64  , Custom);
491    setOperationAction(ISD::SRL_PARTS     , MVT::i64  , Custom);
492  }
493
494  if (Subtarget->hasSSE1())
495    setOperationAction(ISD::PREFETCH      , MVT::Other, Legal);
496
497  setOperationAction(ISD::MEMBARRIER    , MVT::Other, Custom);
498  setOperationAction(ISD::ATOMIC_FENCE  , MVT::Other, Custom);
499
500  // On X86 and X86-64, atomic operations are lowered to locked instructions.
501  // Locked instructions, in turn, have implicit fence semantics (all memory
502  // operations are flushed before issuing the locked instruction, and they
503  // are not buffered), so we can fold away the common pattern of
504  // fence-atomic-fence.
505  setShouldFoldAtomicFences(true);
506
507  // Expand certain atomics
508  for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
509    MVT VT = IntVTs[i];
510    setOperationAction(ISD::ATOMIC_CMP_SWAP, VT, Custom);
511    setOperationAction(ISD::ATOMIC_LOAD_SUB, VT, Custom);
512    setOperationAction(ISD::ATOMIC_STORE, VT, Custom);
513  }
514
515  if (!Subtarget->is64Bit()) {
516    setOperationAction(ISD::ATOMIC_LOAD, MVT::i64, Custom);
517    setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i64, Custom);
518    setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
519    setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i64, Custom);
520    setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i64, Custom);
521    setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i64, Custom);
522    setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i64, Custom);
523    setOperationAction(ISD::ATOMIC_SWAP, MVT::i64, Custom);
524    setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i64, Custom);
525    setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i64, Custom);
526    setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i64, Custom);
527    setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i64, Custom);
528  }
529
530  if (Subtarget->hasCmpxchg16b()) {
531    setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i128, Custom);
532  }
533
534  // FIXME - use subtarget debug flags
535  if (!Subtarget->isTargetDarwin() &&
536      !Subtarget->isTargetELF() &&
537      !Subtarget->isTargetCygMing()) {
538    setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
539  }
540
541  setOperationAction(ISD::EXCEPTIONADDR, MVT::i64, Expand);
542  setOperationAction(ISD::EHSELECTION,   MVT::i64, Expand);
543  setOperationAction(ISD::EXCEPTIONADDR, MVT::i32, Expand);
544  setOperationAction(ISD::EHSELECTION,   MVT::i32, Expand);
545  if (Subtarget->is64Bit()) {
546    setExceptionPointerRegister(X86::RAX);
547    setExceptionSelectorRegister(X86::RDX);
548  } else {
549    setExceptionPointerRegister(X86::EAX);
550    setExceptionSelectorRegister(X86::EDX);
551  }
552  setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
553  setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
554
555  setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
556  setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
557
558  setOperationAction(ISD::TRAP, MVT::Other, Legal);
559  setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal);
560
561  // VASTART needs to be custom lowered to use the VarArgsFrameIndex
562  setOperationAction(ISD::VASTART           , MVT::Other, Custom);
563  setOperationAction(ISD::VAEND             , MVT::Other, Expand);
564  if (Subtarget->is64Bit()) {
565    setOperationAction(ISD::VAARG           , MVT::Other, Custom);
566    setOperationAction(ISD::VACOPY          , MVT::Other, Custom);
567  } else {
568    setOperationAction(ISD::VAARG           , MVT::Other, Expand);
569    setOperationAction(ISD::VACOPY          , MVT::Other, Expand);
570  }
571
572  setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
573  setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
574
575  if (Subtarget->isTargetCOFF() && !Subtarget->isTargetEnvMacho())
576    setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
577                       MVT::i64 : MVT::i32, Custom);
578  else if (TM.Options.EnableSegmentedStacks)
579    setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
580                       MVT::i64 : MVT::i32, Custom);
581  else
582    setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
583                       MVT::i64 : MVT::i32, Expand);
584
585  if (!TM.Options.UseSoftFloat && X86ScalarSSEf64) {
586    // f32 and f64 use SSE.
587    // Set up the FP register classes.
588    addRegisterClass(MVT::f32, &X86::FR32RegClass);
589    addRegisterClass(MVT::f64, &X86::FR64RegClass);
590
591    // Use ANDPD to simulate FABS.
592    setOperationAction(ISD::FABS , MVT::f64, Custom);
593    setOperationAction(ISD::FABS , MVT::f32, Custom);
594
595    // Use XORP to simulate FNEG.
596    setOperationAction(ISD::FNEG , MVT::f64, Custom);
597    setOperationAction(ISD::FNEG , MVT::f32, Custom);
598
599    // Use ANDPD and ORPD to simulate FCOPYSIGN.
600    setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
601    setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
602
603    // Lower this to FGETSIGNx86 plus an AND.
604    setOperationAction(ISD::FGETSIGN, MVT::i64, Custom);
605    setOperationAction(ISD::FGETSIGN, MVT::i32, Custom);
606
607    // We don't support sin/cos/fmod
608    setOperationAction(ISD::FSIN , MVT::f64, Expand);
609    setOperationAction(ISD::FCOS , MVT::f64, Expand);
610    setOperationAction(ISD::FSIN , MVT::f32, Expand);
611    setOperationAction(ISD::FCOS , MVT::f32, Expand);
612
613    // Expand FP immediates into loads from the stack, except for the special
614    // cases we handle.
615    addLegalFPImmediate(APFloat(+0.0)); // xorpd
616    addLegalFPImmediate(APFloat(+0.0f)); // xorps
617  } else if (!TM.Options.UseSoftFloat && X86ScalarSSEf32) {
618    // Use SSE for f32, x87 for f64.
619    // Set up the FP register classes.
620    addRegisterClass(MVT::f32, &X86::FR32RegClass);
621    addRegisterClass(MVT::f64, &X86::RFP64RegClass);
622
623    // Use ANDPS to simulate FABS.
624    setOperationAction(ISD::FABS , MVT::f32, Custom);
625
626    // Use XORP to simulate FNEG.
627    setOperationAction(ISD::FNEG , MVT::f32, Custom);
628
629    setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
630
631    // Use ANDPS and ORPS to simulate FCOPYSIGN.
632    setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
633    setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
634
635    // We don't support sin/cos/fmod
636    setOperationAction(ISD::FSIN , MVT::f32, Expand);
637    setOperationAction(ISD::FCOS , MVT::f32, Expand);
638
639    // Special cases we handle for FP constants.
640    addLegalFPImmediate(APFloat(+0.0f)); // xorps
641    addLegalFPImmediate(APFloat(+0.0)); // FLD0
642    addLegalFPImmediate(APFloat(+1.0)); // FLD1
643    addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
644    addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
645
646    if (!TM.Options.UnsafeFPMath) {
647      setOperationAction(ISD::FSIN           , MVT::f64  , Expand);
648      setOperationAction(ISD::FCOS           , MVT::f64  , Expand);
649    }
650  } else if (!TM.Options.UseSoftFloat) {
651    // f32 and f64 in x87.
652    // Set up the FP register classes.
653    addRegisterClass(MVT::f64, &X86::RFP64RegClass);
654    addRegisterClass(MVT::f32, &X86::RFP32RegClass);
655
656    setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
657    setOperationAction(ISD::UNDEF,     MVT::f32, Expand);
658    setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
659    setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
660
661    if (!TM.Options.UnsafeFPMath) {
662      setOperationAction(ISD::FSIN           , MVT::f32  , Expand);
663      setOperationAction(ISD::FSIN           , MVT::f64  , Expand);
664      setOperationAction(ISD::FCOS           , MVT::f32  , Expand);
665      setOperationAction(ISD::FCOS           , MVT::f64  , Expand);
666    }
667    addLegalFPImmediate(APFloat(+0.0)); // FLD0
668    addLegalFPImmediate(APFloat(+1.0)); // FLD1
669    addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
670    addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
671    addLegalFPImmediate(APFloat(+0.0f)); // FLD0
672    addLegalFPImmediate(APFloat(+1.0f)); // FLD1
673    addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
674    addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
675  }
676
677  // We don't support FMA.
678  setOperationAction(ISD::FMA, MVT::f64, Expand);
679  setOperationAction(ISD::FMA, MVT::f32, Expand);
680
681  // Long double always uses X87.
682  if (!TM.Options.UseSoftFloat) {
683    addRegisterClass(MVT::f80, &X86::RFP80RegClass);
684    setOperationAction(ISD::UNDEF,     MVT::f80, Expand);
685    setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
686    {
687      APFloat TmpFlt = APFloat::getZero(APFloat::x87DoubleExtended);
688      addLegalFPImmediate(TmpFlt);  // FLD0
689      TmpFlt.changeSign();
690      addLegalFPImmediate(TmpFlt);  // FLD0/FCHS
691
692      bool ignored;
693      APFloat TmpFlt2(+1.0);
694      TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
695                      &ignored);
696      addLegalFPImmediate(TmpFlt2);  // FLD1
697      TmpFlt2.changeSign();
698      addLegalFPImmediate(TmpFlt2);  // FLD1/FCHS
699    }
700
701    if (!TM.Options.UnsafeFPMath) {
702      setOperationAction(ISD::FSIN           , MVT::f80  , Expand);
703      setOperationAction(ISD::FCOS           , MVT::f80  , Expand);
704    }
705
706    setOperationAction(ISD::FFLOOR, MVT::f80, Expand);
707    setOperationAction(ISD::FCEIL,  MVT::f80, Expand);
708    setOperationAction(ISD::FTRUNC, MVT::f80, Expand);
709    setOperationAction(ISD::FRINT,  MVT::f80, Expand);
710    setOperationAction(ISD::FNEARBYINT, MVT::f80, Expand);
711    setOperationAction(ISD::FMA, MVT::f80, Expand);
712  }
713
714  // Always use a library call for pow.
715  setOperationAction(ISD::FPOW             , MVT::f32  , Expand);
716  setOperationAction(ISD::FPOW             , MVT::f64  , Expand);
717  setOperationAction(ISD::FPOW             , MVT::f80  , Expand);
718
719  setOperationAction(ISD::FLOG, MVT::f80, Expand);
720  setOperationAction(ISD::FLOG2, MVT::f80, Expand);
721  setOperationAction(ISD::FLOG10, MVT::f80, Expand);
722  setOperationAction(ISD::FEXP, MVT::f80, Expand);
723  setOperationAction(ISD::FEXP2, MVT::f80, Expand);
724
725  // First set operation action for all vector types to either promote
726  // (for widening) or expand (for scalarization). Then we will selectively
727  // turn on ones that can be effectively codegen'd.
728  for (int i = MVT::FIRST_VECTOR_VALUETYPE;
729           i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
730    MVT VT = (MVT::SimpleValueType)i;
731    setOperationAction(ISD::ADD , VT, Expand);
732    setOperationAction(ISD::SUB , VT, Expand);
733    setOperationAction(ISD::FADD, VT, Expand);
734    setOperationAction(ISD::FNEG, VT, Expand);
735    setOperationAction(ISD::FSUB, VT, Expand);
736    setOperationAction(ISD::MUL , VT, Expand);
737    setOperationAction(ISD::FMUL, VT, Expand);
738    setOperationAction(ISD::SDIV, VT, Expand);
739    setOperationAction(ISD::UDIV, VT, Expand);
740    setOperationAction(ISD::FDIV, VT, Expand);
741    setOperationAction(ISD::SREM, VT, Expand);
742    setOperationAction(ISD::UREM, VT, Expand);
743    setOperationAction(ISD::LOAD, VT, Expand);
744    setOperationAction(ISD::VECTOR_SHUFFLE, VT, Expand);
745    setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT,Expand);
746    setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
747    setOperationAction(ISD::EXTRACT_SUBVECTOR, VT,Expand);
748    setOperationAction(ISD::INSERT_SUBVECTOR, VT,Expand);
749    setOperationAction(ISD::FABS, VT, Expand);
750    setOperationAction(ISD::FSIN, VT, Expand);
751    setOperationAction(ISD::FCOS, VT, Expand);
752    setOperationAction(ISD::FREM, VT, Expand);
753    setOperationAction(ISD::FMA,  VT, Expand);
754    setOperationAction(ISD::FPOWI, VT, Expand);
755    setOperationAction(ISD::FSQRT, VT, Expand);
756    setOperationAction(ISD::FCOPYSIGN, VT, Expand);
757    setOperationAction(ISD::FFLOOR, VT, Expand);
758    setOperationAction(ISD::FCEIL, VT, Expand);
759    setOperationAction(ISD::FTRUNC, VT, Expand);
760    setOperationAction(ISD::FRINT, VT, Expand);
761    setOperationAction(ISD::FNEARBYINT, VT, Expand);
762    setOperationAction(ISD::SMUL_LOHI, VT, Expand);
763    setOperationAction(ISD::UMUL_LOHI, VT, Expand);
764    setOperationAction(ISD::SDIVREM, VT, Expand);
765    setOperationAction(ISD::UDIVREM, VT, Expand);
766    setOperationAction(ISD::FPOW, VT, Expand);
767    setOperationAction(ISD::CTPOP, VT, Expand);
768    setOperationAction(ISD::CTTZ, VT, Expand);
769    setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Expand);
770    setOperationAction(ISD::CTLZ, VT, Expand);
771    setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Expand);
772    setOperationAction(ISD::SHL, VT, Expand);
773    setOperationAction(ISD::SRA, VT, Expand);
774    setOperationAction(ISD::SRL, VT, Expand);
775    setOperationAction(ISD::ROTL, VT, Expand);
776    setOperationAction(ISD::ROTR, VT, Expand);
777    setOperationAction(ISD::BSWAP, VT, Expand);
778    setOperationAction(ISD::SETCC, VT, Expand);
779    setOperationAction(ISD::FLOG, VT, Expand);
780    setOperationAction(ISD::FLOG2, VT, Expand);
781    setOperationAction(ISD::FLOG10, VT, Expand);
782    setOperationAction(ISD::FEXP, VT, Expand);
783    setOperationAction(ISD::FEXP2, VT, Expand);
784    setOperationAction(ISD::FP_TO_UINT, VT, Expand);
785    setOperationAction(ISD::FP_TO_SINT, VT, Expand);
786    setOperationAction(ISD::UINT_TO_FP, VT, Expand);
787    setOperationAction(ISD::SINT_TO_FP, VT, Expand);
788    setOperationAction(ISD::SIGN_EXTEND_INREG, VT,Expand);
789    setOperationAction(ISD::TRUNCATE, VT, Expand);
790    setOperationAction(ISD::SIGN_EXTEND, VT, Expand);
791    setOperationAction(ISD::ZERO_EXTEND, VT, Expand);
792    setOperationAction(ISD::ANY_EXTEND, VT, Expand);
793    setOperationAction(ISD::VSELECT, VT, Expand);
794    for (int InnerVT = MVT::FIRST_VECTOR_VALUETYPE;
795             InnerVT <= MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
796      setTruncStoreAction(VT,
797                          (MVT::SimpleValueType)InnerVT, Expand);
798    setLoadExtAction(ISD::SEXTLOAD, VT, Expand);
799    setLoadExtAction(ISD::ZEXTLOAD, VT, Expand);
800    setLoadExtAction(ISD::EXTLOAD, VT, Expand);
801  }
802
803  // FIXME: In order to prevent SSE instructions being expanded to MMX ones
804  // with -msoft-float, disable use of MMX as well.
805  if (!TM.Options.UseSoftFloat && Subtarget->hasMMX()) {
806    addRegisterClass(MVT::x86mmx, &X86::VR64RegClass);
807    // No operations on x86mmx supported, everything uses intrinsics.
808  }
809
810  // MMX-sized vectors (other than x86mmx) are expected to be expanded
811  // into smaller operations.
812  setOperationAction(ISD::MULHS,              MVT::v8i8,  Expand);
813  setOperationAction(ISD::MULHS,              MVT::v4i16, Expand);
814  setOperationAction(ISD::MULHS,              MVT::v2i32, Expand);
815  setOperationAction(ISD::MULHS,              MVT::v1i64, Expand);
816  setOperationAction(ISD::AND,                MVT::v8i8,  Expand);
817  setOperationAction(ISD::AND,                MVT::v4i16, Expand);
818  setOperationAction(ISD::AND,                MVT::v2i32, Expand);
819  setOperationAction(ISD::AND,                MVT::v1i64, Expand);
820  setOperationAction(ISD::OR,                 MVT::v8i8,  Expand);
821  setOperationAction(ISD::OR,                 MVT::v4i16, Expand);
822  setOperationAction(ISD::OR,                 MVT::v2i32, Expand);
823  setOperationAction(ISD::OR,                 MVT::v1i64, Expand);
824  setOperationAction(ISD::XOR,                MVT::v8i8,  Expand);
825  setOperationAction(ISD::XOR,                MVT::v4i16, Expand);
826  setOperationAction(ISD::XOR,                MVT::v2i32, Expand);
827  setOperationAction(ISD::XOR,                MVT::v1i64, Expand);
828  setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i8,  Expand);
829  setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v4i16, Expand);
830  setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v2i32, Expand);
831  setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v1i64, Expand);
832  setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v1i64, Expand);
833  setOperationAction(ISD::SELECT,             MVT::v8i8,  Expand);
834  setOperationAction(ISD::SELECT,             MVT::v4i16, Expand);
835  setOperationAction(ISD::SELECT,             MVT::v2i32, Expand);
836  setOperationAction(ISD::SELECT,             MVT::v1i64, Expand);
837  setOperationAction(ISD::BITCAST,            MVT::v8i8,  Expand);
838  setOperationAction(ISD::BITCAST,            MVT::v4i16, Expand);
839  setOperationAction(ISD::BITCAST,            MVT::v2i32, Expand);
840  setOperationAction(ISD::BITCAST,            MVT::v1i64, Expand);
841
842  if (!TM.Options.UseSoftFloat && Subtarget->hasSSE1()) {
843    addRegisterClass(MVT::v4f32, &X86::VR128RegClass);
844
845    setOperationAction(ISD::FADD,               MVT::v4f32, Legal);
846    setOperationAction(ISD::FSUB,               MVT::v4f32, Legal);
847    setOperationAction(ISD::FMUL,               MVT::v4f32, Legal);
848    setOperationAction(ISD::FDIV,               MVT::v4f32, Legal);
849    setOperationAction(ISD::FSQRT,              MVT::v4f32, Legal);
850    setOperationAction(ISD::FNEG,               MVT::v4f32, Custom);
851    setOperationAction(ISD::FABS,               MVT::v4f32, Custom);
852    setOperationAction(ISD::LOAD,               MVT::v4f32, Legal);
853    setOperationAction(ISD::BUILD_VECTOR,       MVT::v4f32, Custom);
854    setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4f32, Custom);
855    setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
856    setOperationAction(ISD::SELECT,             MVT::v4f32, Custom);
857  }
858
859  if (!TM.Options.UseSoftFloat && Subtarget->hasSSE2()) {
860    addRegisterClass(MVT::v2f64, &X86::VR128RegClass);
861
862    // FIXME: Unfortunately -soft-float and -no-implicit-float means XMM
863    // registers cannot be used even for integer operations.
864    addRegisterClass(MVT::v16i8, &X86::VR128RegClass);
865    addRegisterClass(MVT::v8i16, &X86::VR128RegClass);
866    addRegisterClass(MVT::v4i32, &X86::VR128RegClass);
867    addRegisterClass(MVT::v2i64, &X86::VR128RegClass);
868
869    setOperationAction(ISD::ADD,                MVT::v16i8, Legal);
870    setOperationAction(ISD::ADD,                MVT::v8i16, Legal);
871    setOperationAction(ISD::ADD,                MVT::v4i32, Legal);
872    setOperationAction(ISD::ADD,                MVT::v2i64, Legal);
873    setOperationAction(ISD::MUL,                MVT::v4i32, Custom);
874    setOperationAction(ISD::MUL,                MVT::v2i64, Custom);
875    setOperationAction(ISD::SUB,                MVT::v16i8, Legal);
876    setOperationAction(ISD::SUB,                MVT::v8i16, Legal);
877    setOperationAction(ISD::SUB,                MVT::v4i32, Legal);
878    setOperationAction(ISD::SUB,                MVT::v2i64, Legal);
879    setOperationAction(ISD::MUL,                MVT::v8i16, Legal);
880    setOperationAction(ISD::FADD,               MVT::v2f64, Legal);
881    setOperationAction(ISD::FSUB,               MVT::v2f64, Legal);
882    setOperationAction(ISD::FMUL,               MVT::v2f64, Legal);
883    setOperationAction(ISD::FDIV,               MVT::v2f64, Legal);
884    setOperationAction(ISD::FSQRT,              MVT::v2f64, Legal);
885    setOperationAction(ISD::FNEG,               MVT::v2f64, Custom);
886    setOperationAction(ISD::FABS,               MVT::v2f64, Custom);
887
888    setOperationAction(ISD::SETCC,              MVT::v2i64, Custom);
889    setOperationAction(ISD::SETCC,              MVT::v16i8, Custom);
890    setOperationAction(ISD::SETCC,              MVT::v8i16, Custom);
891    setOperationAction(ISD::SETCC,              MVT::v4i32, Custom);
892
893    setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v16i8, Custom);
894    setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i16, Custom);
895    setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
896    setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
897    setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
898
899    // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
900    for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
901      MVT VT = (MVT::SimpleValueType)i;
902      // Do not attempt to custom lower non-power-of-2 vectors
903      if (!isPowerOf2_32(VT.getVectorNumElements()))
904        continue;
905      // Do not attempt to custom lower non-128-bit vectors
906      if (!VT.is128BitVector())
907        continue;
908      setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
909      setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
910      setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
911    }
912
913    setOperationAction(ISD::BUILD_VECTOR,       MVT::v2f64, Custom);
914    setOperationAction(ISD::BUILD_VECTOR,       MVT::v2i64, Custom);
915    setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2f64, Custom);
916    setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2i64, Custom);
917    setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2f64, Custom);
918    setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
919
920    if (Subtarget->is64Bit()) {
921      setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
922      setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
923    }
924
925    // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
926    for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
927      MVT VT = (MVT::SimpleValueType)i;
928
929      // Do not attempt to promote non-128-bit vectors
930      if (!VT.is128BitVector())
931        continue;
932
933      setOperationAction(ISD::AND,    VT, Promote);
934      AddPromotedToType (ISD::AND,    VT, MVT::v2i64);
935      setOperationAction(ISD::OR,     VT, Promote);
936      AddPromotedToType (ISD::OR,     VT, MVT::v2i64);
937      setOperationAction(ISD::XOR,    VT, Promote);
938      AddPromotedToType (ISD::XOR,    VT, MVT::v2i64);
939      setOperationAction(ISD::LOAD,   VT, Promote);
940      AddPromotedToType (ISD::LOAD,   VT, MVT::v2i64);
941      setOperationAction(ISD::SELECT, VT, Promote);
942      AddPromotedToType (ISD::SELECT, VT, MVT::v2i64);
943    }
944
945    setTruncStoreAction(MVT::f64, MVT::f32, Expand);
946
947    // Custom lower v2i64 and v2f64 selects.
948    setOperationAction(ISD::LOAD,               MVT::v2f64, Legal);
949    setOperationAction(ISD::LOAD,               MVT::v2i64, Legal);
950    setOperationAction(ISD::SELECT,             MVT::v2f64, Custom);
951    setOperationAction(ISD::SELECT,             MVT::v2i64, Custom);
952
953    setOperationAction(ISD::FP_TO_SINT,         MVT::v4i32, Legal);
954    setOperationAction(ISD::SINT_TO_FP,         MVT::v4i32, Legal);
955
956    setOperationAction(ISD::UINT_TO_FP,         MVT::v4i8,  Custom);
957    setOperationAction(ISD::UINT_TO_FP,         MVT::v4i16, Custom);
958    // As there is no 64-bit GPR available, we need build a special custom
959    // sequence to convert from v2i32 to v2f32.
960    if (!Subtarget->is64Bit())
961      setOperationAction(ISD::UINT_TO_FP,       MVT::v2f32, Custom);
962
963    setOperationAction(ISD::FP_EXTEND,          MVT::v2f32, Custom);
964    setOperationAction(ISD::FP_ROUND,           MVT::v2f32, Custom);
965
966    setLoadExtAction(ISD::EXTLOAD,              MVT::v2f32, Legal);
967  }
968
969  if (Subtarget->hasSSE41()) {
970    setOperationAction(ISD::FFLOOR,             MVT::f32,   Legal);
971    setOperationAction(ISD::FCEIL,              MVT::f32,   Legal);
972    setOperationAction(ISD::FTRUNC,             MVT::f32,   Legal);
973    setOperationAction(ISD::FRINT,              MVT::f32,   Legal);
974    setOperationAction(ISD::FNEARBYINT,         MVT::f32,   Legal);
975    setOperationAction(ISD::FFLOOR,             MVT::f64,   Legal);
976    setOperationAction(ISD::FCEIL,              MVT::f64,   Legal);
977    setOperationAction(ISD::FTRUNC,             MVT::f64,   Legal);
978    setOperationAction(ISD::FRINT,              MVT::f64,   Legal);
979    setOperationAction(ISD::FNEARBYINT,         MVT::f64,   Legal);
980
981    setOperationAction(ISD::FFLOOR,             MVT::v4f32, Legal);
982    setOperationAction(ISD::FCEIL,              MVT::v4f32, Legal);
983    setOperationAction(ISD::FTRUNC,             MVT::v4f32, Legal);
984    setOperationAction(ISD::FRINT,              MVT::v4f32, Legal);
985    setOperationAction(ISD::FNEARBYINT,         MVT::v4f32, Legal);
986    setOperationAction(ISD::FFLOOR,             MVT::v2f64, Legal);
987    setOperationAction(ISD::FCEIL,              MVT::v2f64, Legal);
988    setOperationAction(ISD::FTRUNC,             MVT::v2f64, Legal);
989    setOperationAction(ISD::FRINT,              MVT::v2f64, Legal);
990    setOperationAction(ISD::FNEARBYINT,         MVT::v2f64, Legal);
991
992    // FIXME: Do we need to handle scalar-to-vector here?
993    setOperationAction(ISD::MUL,                MVT::v4i32, Legal);
994
995    setOperationAction(ISD::VSELECT,            MVT::v2f64, Legal);
996    setOperationAction(ISD::VSELECT,            MVT::v2i64, Legal);
997    setOperationAction(ISD::VSELECT,            MVT::v16i8, Legal);
998    setOperationAction(ISD::VSELECT,            MVT::v4i32, Legal);
999    setOperationAction(ISD::VSELECT,            MVT::v4f32, Legal);
1000
1001    // i8 and i16 vectors are custom , because the source register and source
1002    // source memory operand types are not the same width.  f32 vectors are
1003    // custom since the immediate controlling the insert encodes additional
1004    // information.
1005    setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i8, Custom);
1006    setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
1007    setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
1008    setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
1009
1010    setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
1011    setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
1012    setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
1013    setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
1014
1015    // FIXME: these should be Legal but thats only for the case where
1016    // the index is constant.  For now custom expand to deal with that.
1017    if (Subtarget->is64Bit()) {
1018      setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
1019      setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
1020    }
1021  }
1022
1023  if (Subtarget->hasSSE2()) {
1024    setOperationAction(ISD::SRL,               MVT::v8i16, Custom);
1025    setOperationAction(ISD::SRL,               MVT::v16i8, Custom);
1026
1027    setOperationAction(ISD::SHL,               MVT::v8i16, Custom);
1028    setOperationAction(ISD::SHL,               MVT::v16i8, Custom);
1029
1030    setOperationAction(ISD::SRA,               MVT::v8i16, Custom);
1031    setOperationAction(ISD::SRA,               MVT::v16i8, Custom);
1032
1033    if (Subtarget->hasInt256()) {
1034      setOperationAction(ISD::SRL,             MVT::v2i64, Legal);
1035      setOperationAction(ISD::SRL,             MVT::v4i32, Legal);
1036
1037      setOperationAction(ISD::SHL,             MVT::v2i64, Legal);
1038      setOperationAction(ISD::SHL,             MVT::v4i32, Legal);
1039
1040      setOperationAction(ISD::SRA,             MVT::v4i32, Legal);
1041    } else {
1042      setOperationAction(ISD::SRL,             MVT::v2i64, Custom);
1043      setOperationAction(ISD::SRL,             MVT::v4i32, Custom);
1044
1045      setOperationAction(ISD::SHL,             MVT::v2i64, Custom);
1046      setOperationAction(ISD::SHL,             MVT::v4i32, Custom);
1047
1048      setOperationAction(ISD::SRA,             MVT::v4i32, Custom);
1049    }
1050    setOperationAction(ISD::SDIV,              MVT::v8i16, Custom);
1051    setOperationAction(ISD::SDIV,              MVT::v4i32, Custom);
1052  }
1053
1054  if (!TM.Options.UseSoftFloat && Subtarget->hasFp256()) {
1055    addRegisterClass(MVT::v32i8,  &X86::VR256RegClass);
1056    addRegisterClass(MVT::v16i16, &X86::VR256RegClass);
1057    addRegisterClass(MVT::v8i32,  &X86::VR256RegClass);
1058    addRegisterClass(MVT::v8f32,  &X86::VR256RegClass);
1059    addRegisterClass(MVT::v4i64,  &X86::VR256RegClass);
1060    addRegisterClass(MVT::v4f64,  &X86::VR256RegClass);
1061
1062    setOperationAction(ISD::LOAD,               MVT::v8f32, Legal);
1063    setOperationAction(ISD::LOAD,               MVT::v4f64, Legal);
1064    setOperationAction(ISD::LOAD,               MVT::v4i64, Legal);
1065
1066    setOperationAction(ISD::FADD,               MVT::v8f32, Legal);
1067    setOperationAction(ISD::FSUB,               MVT::v8f32, Legal);
1068    setOperationAction(ISD::FMUL,               MVT::v8f32, Legal);
1069    setOperationAction(ISD::FDIV,               MVT::v8f32, Legal);
1070    setOperationAction(ISD::FSQRT,              MVT::v8f32, Legal);
1071    setOperationAction(ISD::FFLOOR,             MVT::v8f32, Legal);
1072    setOperationAction(ISD::FCEIL,              MVT::v8f32, Legal);
1073    setOperationAction(ISD::FTRUNC,             MVT::v8f32, Legal);
1074    setOperationAction(ISD::FRINT,              MVT::v8f32, Legal);
1075    setOperationAction(ISD::FNEARBYINT,         MVT::v8f32, Legal);
1076    setOperationAction(ISD::FNEG,               MVT::v8f32, Custom);
1077    setOperationAction(ISD::FABS,               MVT::v8f32, Custom);
1078
1079    setOperationAction(ISD::FADD,               MVT::v4f64, Legal);
1080    setOperationAction(ISD::FSUB,               MVT::v4f64, Legal);
1081    setOperationAction(ISD::FMUL,               MVT::v4f64, Legal);
1082    setOperationAction(ISD::FDIV,               MVT::v4f64, Legal);
1083    setOperationAction(ISD::FSQRT,              MVT::v4f64, Legal);
1084    setOperationAction(ISD::FFLOOR,             MVT::v4f64, Legal);
1085    setOperationAction(ISD::FCEIL,              MVT::v4f64, Legal);
1086    setOperationAction(ISD::FTRUNC,             MVT::v4f64, Legal);
1087    setOperationAction(ISD::FRINT,              MVT::v4f64, Legal);
1088    setOperationAction(ISD::FNEARBYINT,         MVT::v4f64, Legal);
1089    setOperationAction(ISD::FNEG,               MVT::v4f64, Custom);
1090    setOperationAction(ISD::FABS,               MVT::v4f64, Custom);
1091
1092    setOperationAction(ISD::TRUNCATE,           MVT::v8i16, Custom);
1093    setOperationAction(ISD::TRUNCATE,           MVT::v4i32, Custom);
1094
1095    setOperationAction(ISD::FP_TO_SINT,         MVT::v8i16, Custom);
1096
1097    setOperationAction(ISD::FP_TO_SINT,         MVT::v8i32, Legal);
1098    setOperationAction(ISD::SINT_TO_FP,         MVT::v8i32, Legal);
1099    setOperationAction(ISD::FP_ROUND,           MVT::v4f32, Legal);
1100
1101    setOperationAction(ISD::ZERO_EXTEND,        MVT::v8i32, Custom);
1102    setOperationAction(ISD::UINT_TO_FP,         MVT::v8i8,  Custom);
1103    setOperationAction(ISD::UINT_TO_FP,         MVT::v8i16, Custom);
1104
1105    setLoadExtAction(ISD::EXTLOAD,              MVT::v4f32, Legal);
1106
1107    setOperationAction(ISD::SRL,               MVT::v16i16, Custom);
1108    setOperationAction(ISD::SRL,               MVT::v32i8, Custom);
1109
1110    setOperationAction(ISD::SHL,               MVT::v16i16, Custom);
1111    setOperationAction(ISD::SHL,               MVT::v32i8, Custom);
1112
1113    setOperationAction(ISD::SRA,               MVT::v16i16, Custom);
1114    setOperationAction(ISD::SRA,               MVT::v32i8, Custom);
1115
1116    setOperationAction(ISD::SDIV,              MVT::v16i16, Custom);
1117
1118    setOperationAction(ISD::SETCC,             MVT::v32i8, Custom);
1119    setOperationAction(ISD::SETCC,             MVT::v16i16, Custom);
1120    setOperationAction(ISD::SETCC,             MVT::v8i32, Custom);
1121    setOperationAction(ISD::SETCC,             MVT::v4i64, Custom);
1122
1123    setOperationAction(ISD::SELECT,            MVT::v4f64, Custom);
1124    setOperationAction(ISD::SELECT,            MVT::v4i64, Custom);
1125    setOperationAction(ISD::SELECT,            MVT::v8f32, Custom);
1126
1127    setOperationAction(ISD::VSELECT,           MVT::v4f64, Legal);
1128    setOperationAction(ISD::VSELECT,           MVT::v4i64, Legal);
1129    setOperationAction(ISD::VSELECT,           MVT::v8i32, Legal);
1130    setOperationAction(ISD::VSELECT,           MVT::v8f32, Legal);
1131
1132    setOperationAction(ISD::SIGN_EXTEND,       MVT::v4i64, Custom);
1133    setOperationAction(ISD::SIGN_EXTEND,       MVT::v8i32, Custom);
1134    setOperationAction(ISD::ZERO_EXTEND,       MVT::v4i64, Custom);
1135    setOperationAction(ISD::ZERO_EXTEND,       MVT::v8i32, Custom);
1136    setOperationAction(ISD::ANY_EXTEND,        MVT::v4i64, Custom);
1137    setOperationAction(ISD::ANY_EXTEND,        MVT::v8i32, Custom);
1138
1139    if (Subtarget->hasFMA() || Subtarget->hasFMA4()) {
1140      setOperationAction(ISD::FMA,             MVT::v8f32, Legal);
1141      setOperationAction(ISD::FMA,             MVT::v4f64, Legal);
1142      setOperationAction(ISD::FMA,             MVT::v4f32, Legal);
1143      setOperationAction(ISD::FMA,             MVT::v2f64, Legal);
1144      setOperationAction(ISD::FMA,             MVT::f32, Legal);
1145      setOperationAction(ISD::FMA,             MVT::f64, Legal);
1146    }
1147
1148    if (Subtarget->hasInt256()) {
1149      setOperationAction(ISD::ADD,             MVT::v4i64, Legal);
1150      setOperationAction(ISD::ADD,             MVT::v8i32, Legal);
1151      setOperationAction(ISD::ADD,             MVT::v16i16, Legal);
1152      setOperationAction(ISD::ADD,             MVT::v32i8, Legal);
1153
1154      setOperationAction(ISD::SUB,             MVT::v4i64, Legal);
1155      setOperationAction(ISD::SUB,             MVT::v8i32, Legal);
1156      setOperationAction(ISD::SUB,             MVT::v16i16, Legal);
1157      setOperationAction(ISD::SUB,             MVT::v32i8, Legal);
1158
1159      setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1160      setOperationAction(ISD::MUL,             MVT::v8i32, Legal);
1161      setOperationAction(ISD::MUL,             MVT::v16i16, Legal);
1162      // Don't lower v32i8 because there is no 128-bit byte mul
1163
1164      setOperationAction(ISD::VSELECT,         MVT::v32i8, Legal);
1165
1166      setOperationAction(ISD::SRL,             MVT::v4i64, Legal);
1167      setOperationAction(ISD::SRL,             MVT::v8i32, Legal);
1168
1169      setOperationAction(ISD::SHL,             MVT::v4i64, Legal);
1170      setOperationAction(ISD::SHL,             MVT::v8i32, Legal);
1171
1172      setOperationAction(ISD::SRA,             MVT::v8i32, Legal);
1173
1174      setOperationAction(ISD::SDIV,            MVT::v8i32, Custom);
1175    } else {
1176      setOperationAction(ISD::ADD,             MVT::v4i64, Custom);
1177      setOperationAction(ISD::ADD,             MVT::v8i32, Custom);
1178      setOperationAction(ISD::ADD,             MVT::v16i16, Custom);
1179      setOperationAction(ISD::ADD,             MVT::v32i8, Custom);
1180
1181      setOperationAction(ISD::SUB,             MVT::v4i64, Custom);
1182      setOperationAction(ISD::SUB,             MVT::v8i32, Custom);
1183      setOperationAction(ISD::SUB,             MVT::v16i16, Custom);
1184      setOperationAction(ISD::SUB,             MVT::v32i8, Custom);
1185
1186      setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1187      setOperationAction(ISD::MUL,             MVT::v8i32, Custom);
1188      setOperationAction(ISD::MUL,             MVT::v16i16, Custom);
1189      // Don't lower v32i8 because there is no 128-bit byte mul
1190
1191      setOperationAction(ISD::SRL,             MVT::v4i64, Custom);
1192      setOperationAction(ISD::SRL,             MVT::v8i32, Custom);
1193
1194      setOperationAction(ISD::SHL,             MVT::v4i64, Custom);
1195      setOperationAction(ISD::SHL,             MVT::v8i32, Custom);
1196
1197      setOperationAction(ISD::SRA,             MVT::v8i32, Custom);
1198    }
1199
1200    // Custom lower several nodes for 256-bit types.
1201    for (int i = MVT::FIRST_VECTOR_VALUETYPE;
1202             i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
1203      MVT VT = (MVT::SimpleValueType)i;
1204
1205      // Extract subvector is special because the value type
1206      // (result) is 128-bit but the source is 256-bit wide.
1207      if (VT.is128BitVector())
1208        setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1209
1210      // Do not attempt to custom lower other non-256-bit vectors
1211      if (!VT.is256BitVector())
1212        continue;
1213
1214      setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
1215      setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
1216      setOperationAction(ISD::INSERT_VECTOR_ELT,  VT, Custom);
1217      setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1218      setOperationAction(ISD::SCALAR_TO_VECTOR,   VT, Custom);
1219      setOperationAction(ISD::INSERT_SUBVECTOR,   VT, Custom);
1220      setOperationAction(ISD::CONCAT_VECTORS,     VT, Custom);
1221    }
1222
1223    // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
1224    for (int i = MVT::v32i8; i != MVT::v4i64; ++i) {
1225      MVT VT = (MVT::SimpleValueType)i;
1226
1227      // Do not attempt to promote non-256-bit vectors
1228      if (!VT.is256BitVector())
1229        continue;
1230
1231      setOperationAction(ISD::AND,    VT, Promote);
1232      AddPromotedToType (ISD::AND,    VT, MVT::v4i64);
1233      setOperationAction(ISD::OR,     VT, Promote);
1234      AddPromotedToType (ISD::OR,     VT, MVT::v4i64);
1235      setOperationAction(ISD::XOR,    VT, Promote);
1236      AddPromotedToType (ISD::XOR,    VT, MVT::v4i64);
1237      setOperationAction(ISD::LOAD,   VT, Promote);
1238      AddPromotedToType (ISD::LOAD,   VT, MVT::v4i64);
1239      setOperationAction(ISD::SELECT, VT, Promote);
1240      AddPromotedToType (ISD::SELECT, VT, MVT::v4i64);
1241    }
1242  }
1243
1244  // SIGN_EXTEND_INREGs are evaluated by the extend type. Handle the expansion
1245  // of this type with custom code.
1246  for (int VT = MVT::FIRST_VECTOR_VALUETYPE;
1247           VT != MVT::LAST_VECTOR_VALUETYPE; VT++) {
1248    setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,
1249                       Custom);
1250  }
1251
1252  // We want to custom lower some of our intrinsics.
1253  setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1254  setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
1255
1256  // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1257  // handle type legalization for these operations here.
1258  //
1259  // FIXME: We really should do custom legalization for addition and
1260  // subtraction on x86-32 once PR3203 is fixed.  We really can't do much better
1261  // than generic legalization for 64-bit multiplication-with-overflow, though.
1262  for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) {
1263    // Add/Sub/Mul with overflow operations are custom lowered.
1264    MVT VT = IntVTs[i];
1265    setOperationAction(ISD::SADDO, VT, Custom);
1266    setOperationAction(ISD::UADDO, VT, Custom);
1267    setOperationAction(ISD::SSUBO, VT, Custom);
1268    setOperationAction(ISD::USUBO, VT, Custom);
1269    setOperationAction(ISD::SMULO, VT, Custom);
1270    setOperationAction(ISD::UMULO, VT, Custom);
1271  }
1272
1273  // There are no 8-bit 3-address imul/mul instructions
1274  setOperationAction(ISD::SMULO, MVT::i8, Expand);
1275  setOperationAction(ISD::UMULO, MVT::i8, Expand);
1276
1277  if (!Subtarget->is64Bit()) {
1278    // These libcalls are not available in 32-bit.
1279    setLibcallName(RTLIB::SHL_I128, 0);
1280    setLibcallName(RTLIB::SRL_I128, 0);
1281    setLibcallName(RTLIB::SRA_I128, 0);
1282  }
1283
1284  // We have target-specific dag combine patterns for the following nodes:
1285  setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1286  setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1287  setTargetDAGCombine(ISD::VSELECT);
1288  setTargetDAGCombine(ISD::SELECT);
1289  setTargetDAGCombine(ISD::SHL);
1290  setTargetDAGCombine(ISD::SRA);
1291  setTargetDAGCombine(ISD::SRL);
1292  setTargetDAGCombine(ISD::OR);
1293  setTargetDAGCombine(ISD::AND);
1294  setTargetDAGCombine(ISD::ADD);
1295  setTargetDAGCombine(ISD::FADD);
1296  setTargetDAGCombine(ISD::FSUB);
1297  setTargetDAGCombine(ISD::FMA);
1298  setTargetDAGCombine(ISD::SUB);
1299  setTargetDAGCombine(ISD::LOAD);
1300  setTargetDAGCombine(ISD::STORE);
1301  setTargetDAGCombine(ISD::ZERO_EXTEND);
1302  setTargetDAGCombine(ISD::ANY_EXTEND);
1303  setTargetDAGCombine(ISD::SIGN_EXTEND);
1304  setTargetDAGCombine(ISD::TRUNCATE);
1305  setTargetDAGCombine(ISD::SINT_TO_FP);
1306  setTargetDAGCombine(ISD::SETCC);
1307  if (Subtarget->is64Bit())
1308    setTargetDAGCombine(ISD::MUL);
1309  setTargetDAGCombine(ISD::XOR);
1310
1311  computeRegisterProperties();
1312
1313  // On Darwin, -Os means optimize for size without hurting performance,
1314  // do not reduce the limit.
1315  maxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1316  maxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 16 : 8;
1317  maxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1318  maxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1319  maxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1320  maxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1321  setPrefLoopAlignment(4); // 2^4 bytes.
1322  benefitFromCodePlacementOpt = true;
1323
1324  // Predictable cmov don't hurt on atom because it's in-order.
1325  predictableSelectIsExpensive = !Subtarget->isAtom();
1326
1327  setPrefFunctionAlignment(4); // 2^4 bytes.
1328}
1329
1330EVT X86TargetLowering::getSetCCResultType(EVT VT) const {
1331  if (!VT.isVector()) return MVT::i8;
1332  return VT.changeVectorElementTypeToInteger();
1333}
1334
1335/// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1336/// the desired ByVal argument alignment.
1337static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
1338  if (MaxAlign == 16)
1339    return;
1340  if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1341    if (VTy->getBitWidth() == 128)
1342      MaxAlign = 16;
1343  } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1344    unsigned EltAlign = 0;
1345    getMaxByValAlign(ATy->getElementType(), EltAlign);
1346    if (EltAlign > MaxAlign)
1347      MaxAlign = EltAlign;
1348  } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1349    for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1350      unsigned EltAlign = 0;
1351      getMaxByValAlign(STy->getElementType(i), EltAlign);
1352      if (EltAlign > MaxAlign)
1353        MaxAlign = EltAlign;
1354      if (MaxAlign == 16)
1355        break;
1356    }
1357  }
1358}
1359
1360/// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1361/// function arguments in the caller parameter area. For X86, aggregates
1362/// that contain SSE vectors are placed at 16-byte boundaries while the rest
1363/// are at 4-byte boundaries.
1364unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty) const {
1365  if (Subtarget->is64Bit()) {
1366    // Max of 8 and alignment of type.
1367    unsigned TyAlign = TD->getABITypeAlignment(Ty);
1368    if (TyAlign > 8)
1369      return TyAlign;
1370    return 8;
1371  }
1372
1373  unsigned Align = 4;
1374  if (Subtarget->hasSSE1())
1375    getMaxByValAlign(Ty, Align);
1376  return Align;
1377}
1378
1379/// getOptimalMemOpType - Returns the target specific optimal type for load
1380/// and store operations as a result of memset, memcpy, and memmove
1381/// lowering. If DstAlign is zero that means it's safe to destination
1382/// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1383/// means there isn't a need to check it against alignment requirement,
1384/// probably because the source does not need to be loaded. If 'IsMemset' is
1385/// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
1386/// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
1387/// source is constant so it does not need to be loaded.
1388/// It returns EVT::Other if the type should be determined using generic
1389/// target-independent logic.
1390EVT
1391X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1392                                       unsigned DstAlign, unsigned SrcAlign,
1393                                       bool IsMemset, bool ZeroMemset,
1394                                       bool MemcpyStrSrc,
1395                                       MachineFunction &MF) const {
1396  const Function *F = MF.getFunction();
1397  if ((!IsMemset || ZeroMemset) &&
1398      !F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
1399                                       Attribute::NoImplicitFloat)) {
1400    if (Size >= 16 &&
1401        (Subtarget->isUnalignedMemAccessFast() ||
1402         ((DstAlign == 0 || DstAlign >= 16) &&
1403          (SrcAlign == 0 || SrcAlign >= 16)))) {
1404      if (Size >= 32) {
1405        if (Subtarget->hasInt256())
1406          return MVT::v8i32;
1407        if (Subtarget->hasFp256())
1408          return MVT::v8f32;
1409      }
1410      if (Subtarget->hasSSE2())
1411        return MVT::v4i32;
1412      if (Subtarget->hasSSE1())
1413        return MVT::v4f32;
1414    } else if (!MemcpyStrSrc && Size >= 8 &&
1415               !Subtarget->is64Bit() &&
1416               Subtarget->hasSSE2()) {
1417      // Do not use f64 to lower memcpy if source is string constant. It's
1418      // better to use i32 to avoid the loads.
1419      return MVT::f64;
1420    }
1421  }
1422  if (Subtarget->is64Bit() && Size >= 8)
1423    return MVT::i64;
1424  return MVT::i32;
1425}
1426
1427bool X86TargetLowering::isSafeMemOpType(MVT VT) const {
1428  if (VT == MVT::f32)
1429    return X86ScalarSSEf32;
1430  else if (VT == MVT::f64)
1431    return X86ScalarSSEf64;
1432  return true;
1433}
1434
1435bool
1436X86TargetLowering::allowsUnalignedMemoryAccesses(EVT VT, bool *Fast) const {
1437  if (Fast)
1438    *Fast = Subtarget->isUnalignedMemAccessFast();
1439  return true;
1440}
1441
1442/// getJumpTableEncoding - Return the entry encoding for a jump table in the
1443/// current function.  The returned value is a member of the
1444/// MachineJumpTableInfo::JTEntryKind enum.
1445unsigned X86TargetLowering::getJumpTableEncoding() const {
1446  // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1447  // symbol.
1448  if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1449      Subtarget->isPICStyleGOT())
1450    return MachineJumpTableInfo::EK_Custom32;
1451
1452  // Otherwise, use the normal jump table encoding heuristics.
1453  return TargetLowering::getJumpTableEncoding();
1454}
1455
1456const MCExpr *
1457X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1458                                             const MachineBasicBlock *MBB,
1459                                             unsigned uid,MCContext &Ctx) const{
1460  assert(getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1461         Subtarget->isPICStyleGOT());
1462  // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1463  // entries.
1464  return MCSymbolRefExpr::Create(MBB->getSymbol(),
1465                                 MCSymbolRefExpr::VK_GOTOFF, Ctx);
1466}
1467
1468/// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
1469/// jumptable.
1470SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1471                                                    SelectionDAG &DAG) const {
1472  if (!Subtarget->is64Bit())
1473    // This doesn't have DebugLoc associated with it, but is not really the
1474    // same as a Register.
1475    return DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), getPointerTy());
1476  return Table;
1477}
1478
1479/// getPICJumpTableRelocBaseExpr - This returns the relocation base for the
1480/// given PIC jumptable, the same as getPICJumpTableRelocBase, but as an
1481/// MCExpr.
1482const MCExpr *X86TargetLowering::
1483getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1484                             MCContext &Ctx) const {
1485  // X86-64 uses RIP relative addressing based on the jump table label.
1486  if (Subtarget->isPICStyleRIPRel())
1487    return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1488
1489  // Otherwise, the reference is relative to the PIC base.
1490  return MCSymbolRefExpr::Create(MF->getPICBaseSymbol(), Ctx);
1491}
1492
1493// FIXME: Why this routine is here? Move to RegInfo!
1494std::pair<const TargetRegisterClass*, uint8_t>
1495X86TargetLowering::findRepresentativeClass(MVT VT) const{
1496  const TargetRegisterClass *RRC = 0;
1497  uint8_t Cost = 1;
1498  switch (VT.SimpleTy) {
1499  default:
1500    return TargetLowering::findRepresentativeClass(VT);
1501  case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1502    RRC = Subtarget->is64Bit() ?
1503      (const TargetRegisterClass*)&X86::GR64RegClass :
1504      (const TargetRegisterClass*)&X86::GR32RegClass;
1505    break;
1506  case MVT::x86mmx:
1507    RRC = &X86::VR64RegClass;
1508    break;
1509  case MVT::f32: case MVT::f64:
1510  case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1511  case MVT::v4f32: case MVT::v2f64:
1512  case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
1513  case MVT::v4f64:
1514    RRC = &X86::VR128RegClass;
1515    break;
1516  }
1517  return std::make_pair(RRC, Cost);
1518}
1519
1520bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
1521                                               unsigned &Offset) const {
1522  if (!Subtarget->isTargetLinux())
1523    return false;
1524
1525  if (Subtarget->is64Bit()) {
1526    // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
1527    Offset = 0x28;
1528    if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
1529      AddressSpace = 256;
1530    else
1531      AddressSpace = 257;
1532  } else {
1533    // %gs:0x14 on i386
1534    Offset = 0x14;
1535    AddressSpace = 256;
1536  }
1537  return true;
1538}
1539
1540//===----------------------------------------------------------------------===//
1541//               Return Value Calling Convention Implementation
1542//===----------------------------------------------------------------------===//
1543
1544#include "X86GenCallingConv.inc"
1545
1546bool
1547X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv,
1548                                  MachineFunction &MF, bool isVarArg,
1549                        const SmallVectorImpl<ISD::OutputArg> &Outs,
1550                        LLVMContext &Context) const {
1551  SmallVector<CCValAssign, 16> RVLocs;
1552  CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1553                 RVLocs, Context);
1554  return CCInfo.CheckReturn(Outs, RetCC_X86);
1555}
1556
1557SDValue
1558X86TargetLowering::LowerReturn(SDValue Chain,
1559                               CallingConv::ID CallConv, bool isVarArg,
1560                               const SmallVectorImpl<ISD::OutputArg> &Outs,
1561                               const SmallVectorImpl<SDValue> &OutVals,
1562                               DebugLoc dl, SelectionDAG &DAG) const {
1563  MachineFunction &MF = DAG.getMachineFunction();
1564  X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1565
1566  SmallVector<CCValAssign, 16> RVLocs;
1567  CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1568                 RVLocs, *DAG.getContext());
1569  CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1570
1571  // Add the regs to the liveout set for the function.
1572  MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
1573  for (unsigned i = 0; i != RVLocs.size(); ++i)
1574    if (RVLocs[i].isRegLoc() && !MRI.isLiveOut(RVLocs[i].getLocReg()))
1575      MRI.addLiveOut(RVLocs[i].getLocReg());
1576
1577  SDValue Flag;
1578
1579  SmallVector<SDValue, 6> RetOps;
1580  RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1581  // Operand #1 = Bytes To Pop
1582  RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(),
1583                   MVT::i16));
1584
1585  // Copy the result values into the output registers.
1586  for (unsigned i = 0; i != RVLocs.size(); ++i) {
1587    CCValAssign &VA = RVLocs[i];
1588    assert(VA.isRegLoc() && "Can only return in registers!");
1589    SDValue ValToCopy = OutVals[i];
1590    EVT ValVT = ValToCopy.getValueType();
1591
1592    // Promote values to the appropriate types
1593    if (VA.getLocInfo() == CCValAssign::SExt)
1594      ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
1595    else if (VA.getLocInfo() == CCValAssign::ZExt)
1596      ValToCopy = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), ValToCopy);
1597    else if (VA.getLocInfo() == CCValAssign::AExt)
1598      ValToCopy = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), ValToCopy);
1599    else if (VA.getLocInfo() == CCValAssign::BCvt)
1600      ValToCopy = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), ValToCopy);
1601
1602    // If this is x86-64, and we disabled SSE, we can't return FP values,
1603    // or SSE or MMX vectors.
1604    if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
1605         VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
1606          (Subtarget->is64Bit() && !Subtarget->hasSSE1())) {
1607      report_fatal_error("SSE register return with SSE disabled");
1608    }
1609    // Likewise we can't return F64 values with SSE1 only.  gcc does so, but
1610    // llvm-gcc has never done it right and no one has noticed, so this
1611    // should be OK for now.
1612    if (ValVT == MVT::f64 &&
1613        (Subtarget->is64Bit() && !Subtarget->hasSSE2()))
1614      report_fatal_error("SSE2 register return with SSE2 disabled");
1615
1616    // Returns in ST0/ST1 are handled specially: these are pushed as operands to
1617    // the RET instruction and handled by the FP Stackifier.
1618    if (VA.getLocReg() == X86::ST0 ||
1619        VA.getLocReg() == X86::ST1) {
1620      // If this is a copy from an xmm register to ST(0), use an FPExtend to
1621      // change the value to the FP stack register class.
1622      if (isScalarFPTypeInSSEReg(VA.getValVT()))
1623        ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
1624      RetOps.push_back(ValToCopy);
1625      // Don't emit a copytoreg.
1626      continue;
1627    }
1628
1629    // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
1630    // which is returned in RAX / RDX.
1631    if (Subtarget->is64Bit()) {
1632      if (ValVT == MVT::x86mmx) {
1633        if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1634          ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ValToCopy);
1635          ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
1636                                  ValToCopy);
1637          // If we don't have SSE2 available, convert to v4f32 so the generated
1638          // register is legal.
1639          if (!Subtarget->hasSSE2())
1640            ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32,ValToCopy);
1641        }
1642      }
1643    }
1644
1645    Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
1646    Flag = Chain.getValue(1);
1647  }
1648
1649  // The x86-64 ABI for returning structs by value requires that we copy
1650  // the sret argument into %rax for the return. We saved the argument into
1651  // a virtual register in the entry block, so now we copy the value out
1652  // and into %rax.
1653  if (Subtarget->is64Bit() &&
1654      DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
1655    MachineFunction &MF = DAG.getMachineFunction();
1656    X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1657    unsigned Reg = FuncInfo->getSRetReturnReg();
1658    assert(Reg &&
1659           "SRetReturnReg should have been set in LowerFormalArguments().");
1660    SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
1661
1662    Chain = DAG.getCopyToReg(Chain, dl, X86::RAX, Val, Flag);
1663    Flag = Chain.getValue(1);
1664
1665    // RAX now acts like a return value.
1666    MRI.addLiveOut(X86::RAX);
1667  }
1668
1669  RetOps[0] = Chain;  // Update chain.
1670
1671  // Add the flag if we have it.
1672  if (Flag.getNode())
1673    RetOps.push_back(Flag);
1674
1675  return DAG.getNode(X86ISD::RET_FLAG, dl,
1676                     MVT::Other, &RetOps[0], RetOps.size());
1677}
1678
1679bool X86TargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
1680  if (N->getNumValues() != 1)
1681    return false;
1682  if (!N->hasNUsesOfValue(1, 0))
1683    return false;
1684
1685  SDValue TCChain = Chain;
1686  SDNode *Copy = *N->use_begin();
1687  if (Copy->getOpcode() == ISD::CopyToReg) {
1688    // If the copy has a glue operand, we conservatively assume it isn't safe to
1689    // perform a tail call.
1690    if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
1691      return false;
1692    TCChain = Copy->getOperand(0);
1693  } else if (Copy->getOpcode() != ISD::FP_EXTEND)
1694    return false;
1695
1696  bool HasRet = false;
1697  for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
1698       UI != UE; ++UI) {
1699    if (UI->getOpcode() != X86ISD::RET_FLAG)
1700      return false;
1701    HasRet = true;
1702  }
1703
1704  if (!HasRet)
1705    return false;
1706
1707  Chain = TCChain;
1708  return true;
1709}
1710
1711MVT
1712X86TargetLowering::getTypeForExtArgOrReturn(MVT VT,
1713                                            ISD::NodeType ExtendKind) const {
1714  MVT ReturnMVT;
1715  // TODO: Is this also valid on 32-bit?
1716  if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
1717    ReturnMVT = MVT::i8;
1718  else
1719    ReturnMVT = MVT::i32;
1720
1721  MVT MinVT = getRegisterType(ReturnMVT);
1722  return VT.bitsLT(MinVT) ? MinVT : VT;
1723}
1724
1725/// LowerCallResult - Lower the result values of a call into the
1726/// appropriate copies out of appropriate physical registers.
1727///
1728SDValue
1729X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1730                                   CallingConv::ID CallConv, bool isVarArg,
1731                                   const SmallVectorImpl<ISD::InputArg> &Ins,
1732                                   DebugLoc dl, SelectionDAG &DAG,
1733                                   SmallVectorImpl<SDValue> &InVals) const {
1734
1735  // Assign locations to each value returned by this call.
1736  SmallVector<CCValAssign, 16> RVLocs;
1737  bool Is64Bit = Subtarget->is64Bit();
1738  CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1739                 getTargetMachine(), RVLocs, *DAG.getContext());
1740  CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
1741
1742  // Copy all of the result registers out of their specified physreg.
1743  for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
1744    CCValAssign &VA = RVLocs[i];
1745    EVT CopyVT = VA.getValVT();
1746
1747    // If this is x86-64, and we disabled SSE, we can't return FP values
1748    if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
1749        ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
1750      report_fatal_error("SSE register return with SSE disabled");
1751    }
1752
1753    SDValue Val;
1754
1755    // If this is a call to a function that returns an fp value on the floating
1756    // point stack, we must guarantee the value is popped from the stack, so
1757    // a CopyFromReg is not good enough - the copy instruction may be eliminated
1758    // if the return value is not used. We use the FpPOP_RETVAL instruction
1759    // instead.
1760    if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1) {
1761      // If we prefer to use the value in xmm registers, copy it out as f80 and
1762      // use a truncate to move it from fp stack reg to xmm reg.
1763      if (isScalarFPTypeInSSEReg(VA.getValVT())) CopyVT = MVT::f80;
1764      SDValue Ops[] = { Chain, InFlag };
1765      Chain = SDValue(DAG.getMachineNode(X86::FpPOP_RETVAL, dl, CopyVT,
1766                                         MVT::Other, MVT::Glue, Ops, 2), 1);
1767      Val = Chain.getValue(0);
1768
1769      // Round the f80 to the right size, which also moves it to the appropriate
1770      // xmm register.
1771      if (CopyVT != VA.getValVT())
1772        Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
1773                          // This truncation won't change the value.
1774                          DAG.getIntPtrConstant(1));
1775    } else {
1776      Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1777                                 CopyVT, InFlag).getValue(1);
1778      Val = Chain.getValue(0);
1779    }
1780    InFlag = Chain.getValue(2);
1781    InVals.push_back(Val);
1782  }
1783
1784  return Chain;
1785}
1786
1787//===----------------------------------------------------------------------===//
1788//                C & StdCall & Fast Calling Convention implementation
1789//===----------------------------------------------------------------------===//
1790//  StdCall calling convention seems to be standard for many Windows' API
1791//  routines and around. It differs from C calling convention just a little:
1792//  callee should clean up the stack, not caller. Symbols should be also
1793//  decorated in some fancy way :) It doesn't support any vector arguments.
1794//  For info on fast calling convention see Fast Calling Convention (tail call)
1795//  implementation LowerX86_32FastCCCallTo.
1796
1797/// CallIsStructReturn - Determines whether a call uses struct return
1798/// semantics.
1799enum StructReturnType {
1800  NotStructReturn,
1801  RegStructReturn,
1802  StackStructReturn
1803};
1804static StructReturnType
1805callIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
1806  if (Outs.empty())
1807    return NotStructReturn;
1808
1809  const ISD::ArgFlagsTy &Flags = Outs[0].Flags;
1810  if (!Flags.isSRet())
1811    return NotStructReturn;
1812  if (Flags.isInReg())
1813    return RegStructReturn;
1814  return StackStructReturn;
1815}
1816
1817/// ArgsAreStructReturn - Determines whether a function uses struct
1818/// return semantics.
1819static StructReturnType
1820argsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
1821  if (Ins.empty())
1822    return NotStructReturn;
1823
1824  const ISD::ArgFlagsTy &Flags = Ins[0].Flags;
1825  if (!Flags.isSRet())
1826    return NotStructReturn;
1827  if (Flags.isInReg())
1828    return RegStructReturn;
1829  return StackStructReturn;
1830}
1831
1832/// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
1833/// by "Src" to address "Dst" with size and alignment information specified by
1834/// the specific parameter attribute. The copy will be passed as a byval
1835/// function parameter.
1836static SDValue
1837CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
1838                          ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
1839                          DebugLoc dl) {
1840  SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
1841
1842  return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
1843                       /*isVolatile*/false, /*AlwaysInline=*/true,
1844                       MachinePointerInfo(), MachinePointerInfo());
1845}
1846
1847/// IsTailCallConvention - Return true if the calling convention is one that
1848/// supports tail call optimization.
1849static bool IsTailCallConvention(CallingConv::ID CC) {
1850  return (CC == CallingConv::Fast || CC == CallingConv::GHC ||
1851          CC == CallingConv::HiPE);
1852}
1853
1854bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
1855  if (!CI->isTailCall() || getTargetMachine().Options.DisableTailCalls)
1856    return false;
1857
1858  CallSite CS(CI);
1859  CallingConv::ID CalleeCC = CS.getCallingConv();
1860  if (!IsTailCallConvention(CalleeCC) && CalleeCC != CallingConv::C)
1861    return false;
1862
1863  return true;
1864}
1865
1866/// FuncIsMadeTailCallSafe - Return true if the function is being made into
1867/// a tailcall target by changing its ABI.
1868static bool FuncIsMadeTailCallSafe(CallingConv::ID CC,
1869                                   bool GuaranteedTailCallOpt) {
1870  return GuaranteedTailCallOpt && IsTailCallConvention(CC);
1871}
1872
1873SDValue
1874X86TargetLowering::LowerMemArgument(SDValue Chain,
1875                                    CallingConv::ID CallConv,
1876                                    const SmallVectorImpl<ISD::InputArg> &Ins,
1877                                    DebugLoc dl, SelectionDAG &DAG,
1878                                    const CCValAssign &VA,
1879                                    MachineFrameInfo *MFI,
1880                                    unsigned i) const {
1881  // Create the nodes corresponding to a load from this parameter slot.
1882  ISD::ArgFlagsTy Flags = Ins[i].Flags;
1883  bool AlwaysUseMutable = FuncIsMadeTailCallSafe(CallConv,
1884                              getTargetMachine().Options.GuaranteedTailCallOpt);
1885  bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
1886  EVT ValVT;
1887
1888  // If value is passed by pointer we have address passed instead of the value
1889  // itself.
1890  if (VA.getLocInfo() == CCValAssign::Indirect)
1891    ValVT = VA.getLocVT();
1892  else
1893    ValVT = VA.getValVT();
1894
1895  // FIXME: For now, all byval parameter objects are marked mutable. This can be
1896  // changed with more analysis.
1897  // In case of tail call optimization mark all arguments mutable. Since they
1898  // could be overwritten by lowering of arguments in case of a tail call.
1899  if (Flags.isByVal()) {
1900    unsigned Bytes = Flags.getByValSize();
1901    if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
1902    int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
1903    return DAG.getFrameIndex(FI, getPointerTy());
1904  } else {
1905    int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
1906                                    VA.getLocMemOffset(), isImmutable);
1907    SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
1908    return DAG.getLoad(ValVT, dl, Chain, FIN,
1909                       MachinePointerInfo::getFixedStack(FI),
1910                       false, false, false, 0);
1911  }
1912}
1913
1914SDValue
1915X86TargetLowering::LowerFormalArguments(SDValue Chain,
1916                                        CallingConv::ID CallConv,
1917                                        bool isVarArg,
1918                                      const SmallVectorImpl<ISD::InputArg> &Ins,
1919                                        DebugLoc dl,
1920                                        SelectionDAG &DAG,
1921                                        SmallVectorImpl<SDValue> &InVals)
1922                                          const {
1923  MachineFunction &MF = DAG.getMachineFunction();
1924  X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1925
1926  const Function* Fn = MF.getFunction();
1927  if (Fn->hasExternalLinkage() &&
1928      Subtarget->isTargetCygMing() &&
1929      Fn->getName() == "main")
1930    FuncInfo->setForceFramePointer(true);
1931
1932  MachineFrameInfo *MFI = MF.getFrameInfo();
1933  bool Is64Bit = Subtarget->is64Bit();
1934  bool IsWindows = Subtarget->isTargetWindows();
1935  bool IsWin64 = Subtarget->isTargetWin64();
1936
1937  assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
1938         "Var args not supported with calling convention fastcc, ghc or hipe");
1939
1940  // Assign locations to all of the incoming arguments.
1941  SmallVector<CCValAssign, 16> ArgLocs;
1942  CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1943                 ArgLocs, *DAG.getContext());
1944
1945  // Allocate shadow area for Win64
1946  if (IsWin64) {
1947    CCInfo.AllocateStack(32, 8);
1948  }
1949
1950  CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
1951
1952  unsigned LastVal = ~0U;
1953  SDValue ArgValue;
1954  for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1955    CCValAssign &VA = ArgLocs[i];
1956    // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
1957    // places.
1958    assert(VA.getValNo() != LastVal &&
1959           "Don't support value assigned to multiple locs yet");
1960    (void)LastVal;
1961    LastVal = VA.getValNo();
1962
1963    if (VA.isRegLoc()) {
1964      EVT RegVT = VA.getLocVT();
1965      const TargetRegisterClass *RC;
1966      if (RegVT == MVT::i32)
1967        RC = &X86::GR32RegClass;
1968      else if (Is64Bit && RegVT == MVT::i64)
1969        RC = &X86::GR64RegClass;
1970      else if (RegVT == MVT::f32)
1971        RC = &X86::FR32RegClass;
1972      else if (RegVT == MVT::f64)
1973        RC = &X86::FR64RegClass;
1974      else if (RegVT.is256BitVector())
1975        RC = &X86::VR256RegClass;
1976      else if (RegVT.is128BitVector())
1977        RC = &X86::VR128RegClass;
1978      else if (RegVT == MVT::x86mmx)
1979        RC = &X86::VR64RegClass;
1980      else
1981        llvm_unreachable("Unknown argument type!");
1982
1983      unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
1984      ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
1985
1986      // If this is an 8 or 16-bit value, it is really passed promoted to 32
1987      // bits.  Insert an assert[sz]ext to capture this, then truncate to the
1988      // right size.
1989      if (VA.getLocInfo() == CCValAssign::SExt)
1990        ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
1991                               DAG.getValueType(VA.getValVT()));
1992      else if (VA.getLocInfo() == CCValAssign::ZExt)
1993        ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
1994                               DAG.getValueType(VA.getValVT()));
1995      else if (VA.getLocInfo() == CCValAssign::BCvt)
1996        ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
1997
1998      if (VA.isExtInLoc()) {
1999        // Handle MMX values passed in XMM regs.
2000        if (RegVT.isVector())
2001          ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(), ArgValue);
2002        else
2003          ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2004      }
2005    } else {
2006      assert(VA.isMemLoc());
2007      ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
2008    }
2009
2010    // If value is passed via pointer - do a load.
2011    if (VA.getLocInfo() == CCValAssign::Indirect)
2012      ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
2013                             MachinePointerInfo(), false, false, false, 0);
2014
2015    InVals.push_back(ArgValue);
2016  }
2017
2018  // The x86-64 ABI for returning structs by value requires that we copy
2019  // the sret argument into %rax for the return. Save the argument into
2020  // a virtual register so that we can access it from the return points.
2021  if (Is64Bit && MF.getFunction()->hasStructRetAttr()) {
2022    X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2023    unsigned Reg = FuncInfo->getSRetReturnReg();
2024    if (!Reg) {
2025      Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(MVT::i64));
2026      FuncInfo->setSRetReturnReg(Reg);
2027    }
2028    SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[0]);
2029    Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
2030  }
2031
2032  unsigned StackSize = CCInfo.getNextStackOffset();
2033  // Align stack specially for tail calls.
2034  if (FuncIsMadeTailCallSafe(CallConv,
2035                             MF.getTarget().Options.GuaranteedTailCallOpt))
2036    StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
2037
2038  // If the function takes variable number of arguments, make a frame index for
2039  // the start of the first vararg value... for expansion of llvm.va_start.
2040  if (isVarArg) {
2041    if (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
2042                    CallConv != CallingConv::X86_ThisCall)) {
2043      FuncInfo->setVarArgsFrameIndex(MFI->CreateFixedObject(1, StackSize,true));
2044    }
2045    if (Is64Bit) {
2046      unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
2047
2048      // FIXME: We should really autogenerate these arrays
2049      static const uint16_t GPR64ArgRegsWin64[] = {
2050        X86::RCX, X86::RDX, X86::R8,  X86::R9
2051      };
2052      static const uint16_t GPR64ArgRegs64Bit[] = {
2053        X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
2054      };
2055      static const uint16_t XMMArgRegs64Bit[] = {
2056        X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2057        X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2058      };
2059      const uint16_t *GPR64ArgRegs;
2060      unsigned NumXMMRegs = 0;
2061
2062      if (IsWin64) {
2063        // The XMM registers which might contain var arg parameters are shadowed
2064        // in their paired GPR.  So we only need to save the GPR to their home
2065        // slots.
2066        TotalNumIntRegs = 4;
2067        GPR64ArgRegs = GPR64ArgRegsWin64;
2068      } else {
2069        TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
2070        GPR64ArgRegs = GPR64ArgRegs64Bit;
2071
2072        NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs64Bit,
2073                                                TotalNumXMMRegs);
2074      }
2075      unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
2076                                                       TotalNumIntRegs);
2077
2078      bool NoImplicitFloatOps = Fn->getAttributes().
2079        hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
2080      assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
2081             "SSE register cannot be used when SSE is disabled!");
2082      assert(!(NumXMMRegs && MF.getTarget().Options.UseSoftFloat &&
2083               NoImplicitFloatOps) &&
2084             "SSE register cannot be used when SSE is disabled!");
2085      if (MF.getTarget().Options.UseSoftFloat || NoImplicitFloatOps ||
2086          !Subtarget->hasSSE1())
2087        // Kernel mode asks for SSE to be disabled, so don't push them
2088        // on the stack.
2089        TotalNumXMMRegs = 0;
2090
2091      if (IsWin64) {
2092        const TargetFrameLowering &TFI = *getTargetMachine().getFrameLowering();
2093        // Get to the caller-allocated home save location.  Add 8 to account
2094        // for the return address.
2095        int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2096        FuncInfo->setRegSaveFrameIndex(
2097          MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
2098        // Fixup to set vararg frame on shadow area (4 x i64).
2099        if (NumIntRegs < 4)
2100          FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
2101      } else {
2102        // For X86-64, if there are vararg parameters that are passed via
2103        // registers, then we must store them to their spots on the stack so
2104        // they may be loaded by deferencing the result of va_next.
2105        FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
2106        FuncInfo->setVarArgsFPOffset(TotalNumIntRegs * 8 + NumXMMRegs * 16);
2107        FuncInfo->setRegSaveFrameIndex(
2108          MFI->CreateStackObject(TotalNumIntRegs * 8 + TotalNumXMMRegs * 16, 16,
2109                               false));
2110      }
2111
2112      // Store the integer parameter registers.
2113      SmallVector<SDValue, 8> MemOps;
2114      SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
2115                                        getPointerTy());
2116      unsigned Offset = FuncInfo->getVarArgsGPOffset();
2117      for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
2118        SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
2119                                  DAG.getIntPtrConstant(Offset));
2120        unsigned VReg = MF.addLiveIn(GPR64ArgRegs[NumIntRegs],
2121                                     &X86::GR64RegClass);
2122        SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
2123        SDValue Store =
2124          DAG.getStore(Val.getValue(1), dl, Val, FIN,
2125                       MachinePointerInfo::getFixedStack(
2126                         FuncInfo->getRegSaveFrameIndex(), Offset),
2127                       false, false, 0);
2128        MemOps.push_back(Store);
2129        Offset += 8;
2130      }
2131
2132      if (TotalNumXMMRegs != 0 && NumXMMRegs != TotalNumXMMRegs) {
2133        // Now store the XMM (fp + vector) parameter registers.
2134        SmallVector<SDValue, 11> SaveXMMOps;
2135        SaveXMMOps.push_back(Chain);
2136
2137        unsigned AL = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2138        SDValue ALVal = DAG.getCopyFromReg(DAG.getEntryNode(), dl, AL, MVT::i8);
2139        SaveXMMOps.push_back(ALVal);
2140
2141        SaveXMMOps.push_back(DAG.getIntPtrConstant(
2142                               FuncInfo->getRegSaveFrameIndex()));
2143        SaveXMMOps.push_back(DAG.getIntPtrConstant(
2144                               FuncInfo->getVarArgsFPOffset()));
2145
2146        for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
2147          unsigned VReg = MF.addLiveIn(XMMArgRegs64Bit[NumXMMRegs],
2148                                       &X86::VR128RegClass);
2149          SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::v4f32);
2150          SaveXMMOps.push_back(Val);
2151        }
2152        MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
2153                                     MVT::Other,
2154                                     &SaveXMMOps[0], SaveXMMOps.size()));
2155      }
2156
2157      if (!MemOps.empty())
2158        Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2159                            &MemOps[0], MemOps.size());
2160    }
2161  }
2162
2163  // Some CCs need callee pop.
2164  if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2165                       MF.getTarget().Options.GuaranteedTailCallOpt)) {
2166    FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
2167  } else {
2168    FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
2169    // If this is an sret function, the return should pop the hidden pointer.
2170    if (!Is64Bit && !IsTailCallConvention(CallConv) && !IsWindows &&
2171        argsAreStructReturn(Ins) == StackStructReturn)
2172      FuncInfo->setBytesToPopOnReturn(4);
2173  }
2174
2175  if (!Is64Bit) {
2176    // RegSaveFrameIndex is X86-64 only.
2177    FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
2178    if (CallConv == CallingConv::X86_FastCall ||
2179        CallConv == CallingConv::X86_ThisCall)
2180      // fastcc functions can't have varargs.
2181      FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
2182  }
2183
2184  FuncInfo->setArgumentStackSize(StackSize);
2185
2186  return Chain;
2187}
2188
2189SDValue
2190X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
2191                                    SDValue StackPtr, SDValue Arg,
2192                                    DebugLoc dl, SelectionDAG &DAG,
2193                                    const CCValAssign &VA,
2194                                    ISD::ArgFlagsTy Flags) const {
2195  unsigned LocMemOffset = VA.getLocMemOffset();
2196  SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
2197  PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
2198  if (Flags.isByVal())
2199    return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
2200
2201  return DAG.getStore(Chain, dl, Arg, PtrOff,
2202                      MachinePointerInfo::getStack(LocMemOffset),
2203                      false, false, 0);
2204}
2205
2206/// EmitTailCallLoadRetAddr - Emit a load of return address if tail call
2207/// optimization is performed and it is required.
2208SDValue
2209X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
2210                                           SDValue &OutRetAddr, SDValue Chain,
2211                                           bool IsTailCall, bool Is64Bit,
2212                                           int FPDiff, DebugLoc dl) const {
2213  // Adjust the Return address stack slot.
2214  EVT VT = getPointerTy();
2215  OutRetAddr = getReturnAddressFrameIndex(DAG);
2216
2217  // Load the "old" Return address.
2218  OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
2219                           false, false, false, 0);
2220  return SDValue(OutRetAddr.getNode(), 1);
2221}
2222
2223/// EmitTailCallStoreRetAddr - Emit a store of the return address if tail call
2224/// optimization is performed and it is required (FPDiff!=0).
2225static SDValue
2226EmitTailCallStoreRetAddr(SelectionDAG & DAG, MachineFunction &MF,
2227                         SDValue Chain, SDValue RetAddrFrIdx, EVT PtrVT,
2228                         unsigned SlotSize, int FPDiff, DebugLoc dl) {
2229  // Store the return address to the appropriate stack slot.
2230  if (!FPDiff) return Chain;
2231  // Calculate the new stack slot for the return address.
2232  int NewReturnAddrFI =
2233    MF.getFrameInfo()->CreateFixedObject(SlotSize, FPDiff-SlotSize, false);
2234  SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, PtrVT);
2235  Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
2236                       MachinePointerInfo::getFixedStack(NewReturnAddrFI),
2237                       false, false, 0);
2238  return Chain;
2239}
2240
2241SDValue
2242X86TargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2243                             SmallVectorImpl<SDValue> &InVals) const {
2244  SelectionDAG &DAG                     = CLI.DAG;
2245  DebugLoc &dl                          = CLI.DL;
2246  SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs;
2247  SmallVector<SDValue, 32> &OutVals     = CLI.OutVals;
2248  SmallVector<ISD::InputArg, 32> &Ins   = CLI.Ins;
2249  SDValue Chain                         = CLI.Chain;
2250  SDValue Callee                        = CLI.Callee;
2251  CallingConv::ID CallConv              = CLI.CallConv;
2252  bool &isTailCall                      = CLI.IsTailCall;
2253  bool isVarArg                         = CLI.IsVarArg;
2254
2255  MachineFunction &MF = DAG.getMachineFunction();
2256  bool Is64Bit        = Subtarget->is64Bit();
2257  bool IsWin64        = Subtarget->isTargetWin64();
2258  bool IsWindows      = Subtarget->isTargetWindows();
2259  StructReturnType SR = callIsStructReturn(Outs);
2260  bool IsSibcall      = false;
2261
2262  if (MF.getTarget().Options.DisableTailCalls)
2263    isTailCall = false;
2264
2265  if (isTailCall) {
2266    // Check if it's really possible to do a tail call.
2267    isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
2268                    isVarArg, SR != NotStructReturn,
2269                    MF.getFunction()->hasStructRetAttr(), CLI.RetTy,
2270                    Outs, OutVals, Ins, DAG);
2271
2272    // Sibcalls are automatically detected tailcalls which do not require
2273    // ABI changes.
2274    if (!MF.getTarget().Options.GuaranteedTailCallOpt && isTailCall)
2275      IsSibcall = true;
2276
2277    if (isTailCall)
2278      ++NumTailCalls;
2279  }
2280
2281  assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2282         "Var args not supported with calling convention fastcc, ghc or hipe");
2283
2284  // Analyze operands of the call, assigning locations to each operand.
2285  SmallVector<CCValAssign, 16> ArgLocs;
2286  CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
2287                 ArgLocs, *DAG.getContext());
2288
2289  // Allocate shadow area for Win64
2290  if (IsWin64) {
2291    CCInfo.AllocateStack(32, 8);
2292  }
2293
2294  CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2295
2296  // Get a count of how many bytes are to be pushed on the stack.
2297  unsigned NumBytes = CCInfo.getNextStackOffset();
2298  if (IsSibcall)
2299    // This is a sibcall. The memory operands are available in caller's
2300    // own caller's stack.
2301    NumBytes = 0;
2302  else if (getTargetMachine().Options.GuaranteedTailCallOpt &&
2303           IsTailCallConvention(CallConv))
2304    NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
2305
2306  int FPDiff = 0;
2307  if (isTailCall && !IsSibcall) {
2308    // Lower arguments at fp - stackoffset + fpdiff.
2309    X86MachineFunctionInfo *X86Info = MF.getInfo<X86MachineFunctionInfo>();
2310    unsigned NumBytesCallerPushed = X86Info->getBytesToPopOnReturn();
2311
2312    FPDiff = NumBytesCallerPushed - NumBytes;
2313
2314    // Set the delta of movement of the returnaddr stackslot.
2315    // But only set if delta is greater than previous delta.
2316    if (FPDiff < X86Info->getTCReturnAddrDelta())
2317      X86Info->setTCReturnAddrDelta(FPDiff);
2318  }
2319
2320  if (!IsSibcall)
2321    Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true));
2322
2323  SDValue RetAddrFrIdx;
2324  // Load return address for tail calls.
2325  if (isTailCall && FPDiff)
2326    Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
2327                                    Is64Bit, FPDiff, dl);
2328
2329  SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2330  SmallVector<SDValue, 8> MemOpChains;
2331  SDValue StackPtr;
2332
2333  // Walk the register/memloc assignments, inserting copies/loads.  In the case
2334  // of tail call optimization arguments are handle later.
2335  for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2336    CCValAssign &VA = ArgLocs[i];
2337    EVT RegVT = VA.getLocVT();
2338    SDValue Arg = OutVals[i];
2339    ISD::ArgFlagsTy Flags = Outs[i].Flags;
2340    bool isByVal = Flags.isByVal();
2341
2342    // Promote the value if needed.
2343    switch (VA.getLocInfo()) {
2344    default: llvm_unreachable("Unknown loc info!");
2345    case CCValAssign::Full: break;
2346    case CCValAssign::SExt:
2347      Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
2348      break;
2349    case CCValAssign::ZExt:
2350      Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
2351      break;
2352    case CCValAssign::AExt:
2353      if (RegVT.is128BitVector()) {
2354        // Special case: passing MMX values in XMM registers.
2355        Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
2356        Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
2357        Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
2358      } else
2359        Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
2360      break;
2361    case CCValAssign::BCvt:
2362      Arg = DAG.getNode(ISD::BITCAST, dl, RegVT, Arg);
2363      break;
2364    case CCValAssign::Indirect: {
2365      // Store the argument.
2366      SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
2367      int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
2368      Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
2369                           MachinePointerInfo::getFixedStack(FI),
2370                           false, false, 0);
2371      Arg = SpillSlot;
2372      break;
2373    }
2374    }
2375
2376    if (VA.isRegLoc()) {
2377      RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2378      if (isVarArg && IsWin64) {
2379        // Win64 ABI requires argument XMM reg to be copied to the corresponding
2380        // shadow reg if callee is a varargs function.
2381        unsigned ShadowReg = 0;
2382        switch (VA.getLocReg()) {
2383        case X86::XMM0: ShadowReg = X86::RCX; break;
2384        case X86::XMM1: ShadowReg = X86::RDX; break;
2385        case X86::XMM2: ShadowReg = X86::R8; break;
2386        case X86::XMM3: ShadowReg = X86::R9; break;
2387        }
2388        if (ShadowReg)
2389          RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
2390      }
2391    } else if (!IsSibcall && (!isTailCall || isByVal)) {
2392      assert(VA.isMemLoc());
2393      if (StackPtr.getNode() == 0)
2394        StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
2395                                      getPointerTy());
2396      MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
2397                                             dl, DAG, VA, Flags));
2398    }
2399  }
2400
2401  if (!MemOpChains.empty())
2402    Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2403                        &MemOpChains[0], MemOpChains.size());
2404
2405  if (Subtarget->isPICStyleGOT()) {
2406    // ELF / PIC requires GOT in the EBX register before function calls via PLT
2407    // GOT pointer.
2408    if (!isTailCall) {
2409      RegsToPass.push_back(std::make_pair(unsigned(X86::EBX),
2410               DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), getPointerTy())));
2411    } else {
2412      // If we are tail calling and generating PIC/GOT style code load the
2413      // address of the callee into ECX. The value in ecx is used as target of
2414      // the tail jump. This is done to circumvent the ebx/callee-saved problem
2415      // for tail calls on PIC/GOT architectures. Normally we would just put the
2416      // address of GOT into ebx and then call target@PLT. But for tail calls
2417      // ebx would be restored (since ebx is callee saved) before jumping to the
2418      // target@PLT.
2419
2420      // Note: The actual moving to ECX is done further down.
2421      GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2422      if (G && !G->getGlobal()->hasHiddenVisibility() &&
2423          !G->getGlobal()->hasProtectedVisibility())
2424        Callee = LowerGlobalAddress(Callee, DAG);
2425      else if (isa<ExternalSymbolSDNode>(Callee))
2426        Callee = LowerExternalSymbol(Callee, DAG);
2427    }
2428  }
2429
2430  if (Is64Bit && isVarArg && !IsWin64) {
2431    // From AMD64 ABI document:
2432    // For calls that may call functions that use varargs or stdargs
2433    // (prototype-less calls or calls to functions containing ellipsis (...) in
2434    // the declaration) %al is used as hidden argument to specify the number
2435    // of SSE registers used. The contents of %al do not need to match exactly
2436    // the number of registers, but must be an ubound on the number of SSE
2437    // registers used and is in the range 0 - 8 inclusive.
2438
2439    // Count the number of XMM registers allocated.
2440    static const uint16_t XMMArgRegs[] = {
2441      X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2442      X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2443    };
2444    unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
2445    assert((Subtarget->hasSSE1() || !NumXMMRegs)
2446           && "SSE registers cannot be used when SSE is disabled");
2447
2448    RegsToPass.push_back(std::make_pair(unsigned(X86::AL),
2449                                        DAG.getConstant(NumXMMRegs, MVT::i8)));
2450  }
2451
2452  // For tail calls lower the arguments to the 'real' stack slot.
2453  if (isTailCall) {
2454    // Force all the incoming stack arguments to be loaded from the stack
2455    // before any new outgoing arguments are stored to the stack, because the
2456    // outgoing stack slots may alias the incoming argument stack slots, and
2457    // the alias isn't otherwise explicit. This is slightly more conservative
2458    // than necessary, because it means that each store effectively depends
2459    // on every argument instead of just those arguments it would clobber.
2460    SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
2461
2462    SmallVector<SDValue, 8> MemOpChains2;
2463    SDValue FIN;
2464    int FI = 0;
2465    if (getTargetMachine().Options.GuaranteedTailCallOpt) {
2466      for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2467        CCValAssign &VA = ArgLocs[i];
2468        if (VA.isRegLoc())
2469          continue;
2470        assert(VA.isMemLoc());
2471        SDValue Arg = OutVals[i];
2472        ISD::ArgFlagsTy Flags = Outs[i].Flags;
2473        // Create frame index.
2474        int32_t Offset = VA.getLocMemOffset()+FPDiff;
2475        uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
2476        FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
2477        FIN = DAG.getFrameIndex(FI, getPointerTy());
2478
2479        if (Flags.isByVal()) {
2480          // Copy relative to framepointer.
2481          SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
2482          if (StackPtr.getNode() == 0)
2483            StackPtr = DAG.getCopyFromReg(Chain, dl,
2484                                          RegInfo->getStackRegister(),
2485                                          getPointerTy());
2486          Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
2487
2488          MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
2489                                                           ArgChain,
2490                                                           Flags, DAG, dl));
2491        } else {
2492          // Store relative to framepointer.
2493          MemOpChains2.push_back(
2494            DAG.getStore(ArgChain, dl, Arg, FIN,
2495                         MachinePointerInfo::getFixedStack(FI),
2496                         false, false, 0));
2497        }
2498      }
2499    }
2500
2501    if (!MemOpChains2.empty())
2502      Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2503                          &MemOpChains2[0], MemOpChains2.size());
2504
2505    // Store the return address to the appropriate stack slot.
2506    Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx,
2507                                     getPointerTy(), RegInfo->getSlotSize(),
2508                                     FPDiff, dl);
2509  }
2510
2511  // Build a sequence of copy-to-reg nodes chained together with token chain
2512  // and flag operands which copy the outgoing args into registers.
2513  SDValue InFlag;
2514  for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2515    Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2516                             RegsToPass[i].second, InFlag);
2517    InFlag = Chain.getValue(1);
2518  }
2519
2520  if (getTargetMachine().getCodeModel() == CodeModel::Large) {
2521    assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
2522    // In the 64-bit large code model, we have to make all calls
2523    // through a register, since the call instruction's 32-bit
2524    // pc-relative offset may not be large enough to hold the whole
2525    // address.
2526  } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2527    // If the callee is a GlobalAddress node (quite common, every direct call
2528    // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
2529    // it.
2530
2531    // We should use extra load for direct calls to dllimported functions in
2532    // non-JIT mode.
2533    const GlobalValue *GV = G->getGlobal();
2534    if (!GV->hasDLLImportLinkage()) {
2535      unsigned char OpFlags = 0;
2536      bool ExtraLoad = false;
2537      unsigned WrapperKind = ISD::DELETED_NODE;
2538
2539      // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
2540      // external symbols most go through the PLT in PIC mode.  If the symbol
2541      // has hidden or protected visibility, or if it is static or local, then
2542      // we don't need to use the PLT - we can directly call it.
2543      if (Subtarget->isTargetELF() &&
2544          getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
2545          GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
2546        OpFlags = X86II::MO_PLT;
2547      } else if (Subtarget->isPICStyleStubAny() &&
2548                 (GV->isDeclaration() || GV->isWeakForLinker()) &&
2549                 (!Subtarget->getTargetTriple().isMacOSX() ||
2550                  Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2551        // PC-relative references to external symbols should go through $stub,
2552        // unless we're building with the leopard linker or later, which
2553        // automatically synthesizes these stubs.
2554        OpFlags = X86II::MO_DARWIN_STUB;
2555      } else if (Subtarget->isPICStyleRIPRel() &&
2556                 isa<Function>(GV) &&
2557                 cast<Function>(GV)->getAttributes().
2558                   hasAttribute(AttributeSet::FunctionIndex,
2559                                Attribute::NonLazyBind)) {
2560        // If the function is marked as non-lazy, generate an indirect call
2561        // which loads from the GOT directly. This avoids runtime overhead
2562        // at the cost of eager binding (and one extra byte of encoding).
2563        OpFlags = X86II::MO_GOTPCREL;
2564        WrapperKind = X86ISD::WrapperRIP;
2565        ExtraLoad = true;
2566      }
2567
2568      Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
2569                                          G->getOffset(), OpFlags);
2570
2571      // Add a wrapper if needed.
2572      if (WrapperKind != ISD::DELETED_NODE)
2573        Callee = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Callee);
2574      // Add extra indirection if needed.
2575      if (ExtraLoad)
2576        Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Callee,
2577                             MachinePointerInfo::getGOT(),
2578                             false, false, false, 0);
2579    }
2580  } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2581    unsigned char OpFlags = 0;
2582
2583    // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
2584    // external symbols should go through the PLT.
2585    if (Subtarget->isTargetELF() &&
2586        getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2587      OpFlags = X86II::MO_PLT;
2588    } else if (Subtarget->isPICStyleStubAny() &&
2589               (!Subtarget->getTargetTriple().isMacOSX() ||
2590                Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2591      // PC-relative references to external symbols should go through $stub,
2592      // unless we're building with the leopard linker or later, which
2593      // automatically synthesizes these stubs.
2594      OpFlags = X86II::MO_DARWIN_STUB;
2595    }
2596
2597    Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
2598                                         OpFlags);
2599  }
2600
2601  // Returns a chain & a flag for retval copy to use.
2602  SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2603  SmallVector<SDValue, 8> Ops;
2604
2605  if (!IsSibcall && isTailCall) {
2606    Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
2607                           DAG.getIntPtrConstant(0, true), InFlag);
2608    InFlag = Chain.getValue(1);
2609  }
2610
2611  Ops.push_back(Chain);
2612  Ops.push_back(Callee);
2613
2614  if (isTailCall)
2615    Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
2616
2617  // Add argument registers to the end of the list so that they are known live
2618  // into the call.
2619  for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2620    Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2621                                  RegsToPass[i].second.getValueType()));
2622
2623  // Add a register mask operand representing the call-preserved registers.
2624  const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
2625  const uint32_t *Mask = TRI->getCallPreservedMask(CallConv);
2626  assert(Mask && "Missing call preserved mask for calling convention");
2627  Ops.push_back(DAG.getRegisterMask(Mask));
2628
2629  if (InFlag.getNode())
2630    Ops.push_back(InFlag);
2631
2632  if (isTailCall) {
2633    // We used to do:
2634    //// If this is the first return lowered for this function, add the regs
2635    //// to the liveout set for the function.
2636    // This isn't right, although it's probably harmless on x86; liveouts
2637    // should be computed from returns not tail calls.  Consider a void
2638    // function making a tail call to a function returning int.
2639    return DAG.getNode(X86ISD::TC_RETURN, dl,
2640                       NodeTys, &Ops[0], Ops.size());
2641  }
2642
2643  Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, &Ops[0], Ops.size());
2644  InFlag = Chain.getValue(1);
2645
2646  // Create the CALLSEQ_END node.
2647  unsigned NumBytesForCalleeToPush;
2648  if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2649                       getTargetMachine().Options.GuaranteedTailCallOpt))
2650    NumBytesForCalleeToPush = NumBytes;    // Callee pops everything
2651  else if (!Is64Bit && !IsTailCallConvention(CallConv) && !IsWindows &&
2652           SR == StackStructReturn)
2653    // If this is a call to a struct-return function, the callee
2654    // pops the hidden struct pointer, so we have to push it back.
2655    // This is common for Darwin/X86, Linux & Mingw32 targets.
2656    // For MSVC Win32 targets, the caller pops the hidden struct pointer.
2657    NumBytesForCalleeToPush = 4;
2658  else
2659    NumBytesForCalleeToPush = 0;  // Callee pops nothing.
2660
2661  // Returns a flag for retval copy to use.
2662  if (!IsSibcall) {
2663    Chain = DAG.getCALLSEQ_END(Chain,
2664                               DAG.getIntPtrConstant(NumBytes, true),
2665                               DAG.getIntPtrConstant(NumBytesForCalleeToPush,
2666                                                     true),
2667                               InFlag);
2668    InFlag = Chain.getValue(1);
2669  }
2670
2671  // Handle result values, copying them out of physregs into vregs that we
2672  // return.
2673  return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
2674                         Ins, dl, DAG, InVals);
2675}
2676
2677//===----------------------------------------------------------------------===//
2678//                Fast Calling Convention (tail call) implementation
2679//===----------------------------------------------------------------------===//
2680
2681//  Like std call, callee cleans arguments, convention except that ECX is
2682//  reserved for storing the tail called function address. Only 2 registers are
2683//  free for argument passing (inreg). Tail call optimization is performed
2684//  provided:
2685//                * tailcallopt is enabled
2686//                * caller/callee are fastcc
2687//  On X86_64 architecture with GOT-style position independent code only local
2688//  (within module) calls are supported at the moment.
2689//  To keep the stack aligned according to platform abi the function
2690//  GetAlignedArgumentStackSize ensures that argument delta is always multiples
2691//  of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
2692//  If a tail called function callee has more arguments than the caller the
2693//  caller needs to make sure that there is room to move the RETADDR to. This is
2694//  achieved by reserving an area the size of the argument delta right after the
2695//  original REtADDR, but before the saved framepointer or the spilled registers
2696//  e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
2697//  stack layout:
2698//    arg1
2699//    arg2
2700//    RETADDR
2701//    [ new RETADDR
2702//      move area ]
2703//    (possible EBP)
2704//    ESI
2705//    EDI
2706//    local1 ..
2707
2708/// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
2709/// for a 16 byte align requirement.
2710unsigned
2711X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
2712                                               SelectionDAG& DAG) const {
2713  MachineFunction &MF = DAG.getMachineFunction();
2714  const TargetMachine &TM = MF.getTarget();
2715  const TargetFrameLowering &TFI = *TM.getFrameLowering();
2716  unsigned StackAlignment = TFI.getStackAlignment();
2717  uint64_t AlignMask = StackAlignment - 1;
2718  int64_t Offset = StackSize;
2719  unsigned SlotSize = RegInfo->getSlotSize();
2720  if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
2721    // Number smaller than 12 so just add the difference.
2722    Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
2723  } else {
2724    // Mask out lower bits, add stackalignment once plus the 12 bytes.
2725    Offset = ((~AlignMask) & Offset) + StackAlignment +
2726      (StackAlignment-SlotSize);
2727  }
2728  return Offset;
2729}
2730
2731/// MatchingStackOffset - Return true if the given stack call argument is
2732/// already available in the same position (relatively) of the caller's
2733/// incoming argument stack.
2734static
2735bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
2736                         MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
2737                         const X86InstrInfo *TII) {
2738  unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
2739  int FI = INT_MAX;
2740  if (Arg.getOpcode() == ISD::CopyFromReg) {
2741    unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
2742    if (!TargetRegisterInfo::isVirtualRegister(VR))
2743      return false;
2744    MachineInstr *Def = MRI->getVRegDef(VR);
2745    if (!Def)
2746      return false;
2747    if (!Flags.isByVal()) {
2748      if (!TII->isLoadFromStackSlot(Def, FI))
2749        return false;
2750    } else {
2751      unsigned Opcode = Def->getOpcode();
2752      if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r) &&
2753          Def->getOperand(1).isFI()) {
2754        FI = Def->getOperand(1).getIndex();
2755        Bytes = Flags.getByValSize();
2756      } else
2757        return false;
2758    }
2759  } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
2760    if (Flags.isByVal())
2761      // ByVal argument is passed in as a pointer but it's now being
2762      // dereferenced. e.g.
2763      // define @foo(%struct.X* %A) {
2764      //   tail call @bar(%struct.X* byval %A)
2765      // }
2766      return false;
2767    SDValue Ptr = Ld->getBasePtr();
2768    FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
2769    if (!FINode)
2770      return false;
2771    FI = FINode->getIndex();
2772  } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
2773    FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
2774    FI = FINode->getIndex();
2775    Bytes = Flags.getByValSize();
2776  } else
2777    return false;
2778
2779  assert(FI != INT_MAX);
2780  if (!MFI->isFixedObjectIndex(FI))
2781    return false;
2782  return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
2783}
2784
2785/// IsEligibleForTailCallOptimization - Check whether the call is eligible
2786/// for tail call optimization. Targets which want to do tail call
2787/// optimization should implement this function.
2788bool
2789X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
2790                                                     CallingConv::ID CalleeCC,
2791                                                     bool isVarArg,
2792                                                     bool isCalleeStructRet,
2793                                                     bool isCallerStructRet,
2794                                                     Type *RetTy,
2795                                    const SmallVectorImpl<ISD::OutputArg> &Outs,
2796                                    const SmallVectorImpl<SDValue> &OutVals,
2797                                    const SmallVectorImpl<ISD::InputArg> &Ins,
2798                                                     SelectionDAG& DAG) const {
2799  if (!IsTailCallConvention(CalleeCC) &&
2800      CalleeCC != CallingConv::C)
2801    return false;
2802
2803  // If -tailcallopt is specified, make fastcc functions tail-callable.
2804  const MachineFunction &MF = DAG.getMachineFunction();
2805  const Function *CallerF = DAG.getMachineFunction().getFunction();
2806
2807  // If the function return type is x86_fp80 and the callee return type is not,
2808  // then the FP_EXTEND of the call result is not a nop. It's not safe to
2809  // perform a tailcall optimization here.
2810  if (CallerF->getReturnType()->isX86_FP80Ty() && !RetTy->isX86_FP80Ty())
2811    return false;
2812
2813  CallingConv::ID CallerCC = CallerF->getCallingConv();
2814  bool CCMatch = CallerCC == CalleeCC;
2815
2816  if (getTargetMachine().Options.GuaranteedTailCallOpt) {
2817    if (IsTailCallConvention(CalleeCC) && CCMatch)
2818      return true;
2819    return false;
2820  }
2821
2822  // Look for obvious safe cases to perform tail call optimization that do not
2823  // require ABI changes. This is what gcc calls sibcall.
2824
2825  // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
2826  // emit a special epilogue.
2827  if (RegInfo->needsStackRealignment(MF))
2828    return false;
2829
2830  // Also avoid sibcall optimization if either caller or callee uses struct
2831  // return semantics.
2832  if (isCalleeStructRet || isCallerStructRet)
2833    return false;
2834
2835  // An stdcall caller is expected to clean up its arguments; the callee
2836  // isn't going to do that.
2837  if (!CCMatch && CallerCC==CallingConv::X86_StdCall)
2838    return false;
2839
2840  // Do not sibcall optimize vararg calls unless all arguments are passed via
2841  // registers.
2842  if (isVarArg && !Outs.empty()) {
2843
2844    // Optimizing for varargs on Win64 is unlikely to be safe without
2845    // additional testing.
2846    if (Subtarget->isTargetWin64())
2847      return false;
2848
2849    SmallVector<CCValAssign, 16> ArgLocs;
2850    CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
2851                   getTargetMachine(), ArgLocs, *DAG.getContext());
2852
2853    CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2854    for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
2855      if (!ArgLocs[i].isRegLoc())
2856        return false;
2857  }
2858
2859  // If the call result is in ST0 / ST1, it needs to be popped off the x87
2860  // stack.  Therefore, if it's not used by the call it is not safe to optimize
2861  // this into a sibcall.
2862  bool Unused = false;
2863  for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
2864    if (!Ins[i].Used) {
2865      Unused = true;
2866      break;
2867    }
2868  }
2869  if (Unused) {
2870    SmallVector<CCValAssign, 16> RVLocs;
2871    CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(),
2872                   getTargetMachine(), RVLocs, *DAG.getContext());
2873    CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2874    for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2875      CCValAssign &VA = RVLocs[i];
2876      if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1)
2877        return false;
2878    }
2879  }
2880
2881  // If the calling conventions do not match, then we'd better make sure the
2882  // results are returned in the same way as what the caller expects.
2883  if (!CCMatch) {
2884    SmallVector<CCValAssign, 16> RVLocs1;
2885    CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(),
2886                    getTargetMachine(), RVLocs1, *DAG.getContext());
2887    CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
2888
2889    SmallVector<CCValAssign, 16> RVLocs2;
2890    CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(),
2891                    getTargetMachine(), RVLocs2, *DAG.getContext());
2892    CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
2893
2894    if (RVLocs1.size() != RVLocs2.size())
2895      return false;
2896    for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
2897      if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
2898        return false;
2899      if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
2900        return false;
2901      if (RVLocs1[i].isRegLoc()) {
2902        if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
2903          return false;
2904      } else {
2905        if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
2906          return false;
2907      }
2908    }
2909  }
2910
2911  // If the callee takes no arguments then go on to check the results of the
2912  // call.
2913  if (!Outs.empty()) {
2914    // Check if stack adjustment is needed. For now, do not do this if any
2915    // argument is passed on the stack.
2916    SmallVector<CCValAssign, 16> ArgLocs;
2917    CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
2918                   getTargetMachine(), ArgLocs, *DAG.getContext());
2919
2920    // Allocate shadow area for Win64
2921    if (Subtarget->isTargetWin64()) {
2922      CCInfo.AllocateStack(32, 8);
2923    }
2924
2925    CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2926    if (CCInfo.getNextStackOffset()) {
2927      MachineFunction &MF = DAG.getMachineFunction();
2928      if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
2929        return false;
2930
2931      // Check if the arguments are already laid out in the right way as
2932      // the caller's fixed stack objects.
2933      MachineFrameInfo *MFI = MF.getFrameInfo();
2934      const MachineRegisterInfo *MRI = &MF.getRegInfo();
2935      const X86InstrInfo *TII =
2936        ((const X86TargetMachine&)getTargetMachine()).getInstrInfo();
2937      for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2938        CCValAssign &VA = ArgLocs[i];
2939        SDValue Arg = OutVals[i];
2940        ISD::ArgFlagsTy Flags = Outs[i].Flags;
2941        if (VA.getLocInfo() == CCValAssign::Indirect)
2942          return false;
2943        if (!VA.isRegLoc()) {
2944          if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2945                                   MFI, MRI, TII))
2946            return false;
2947        }
2948      }
2949    }
2950
2951    // If the tailcall address may be in a register, then make sure it's
2952    // possible to register allocate for it. In 32-bit, the call address can
2953    // only target EAX, EDX, or ECX since the tail call must be scheduled after
2954    // callee-saved registers are restored. These happen to be the same
2955    // registers used to pass 'inreg' arguments so watch out for those.
2956    if (!Subtarget->is64Bit() &&
2957        !isa<GlobalAddressSDNode>(Callee) &&
2958        !isa<ExternalSymbolSDNode>(Callee)) {
2959      unsigned NumInRegs = 0;
2960      for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2961        CCValAssign &VA = ArgLocs[i];
2962        if (!VA.isRegLoc())
2963          continue;
2964        unsigned Reg = VA.getLocReg();
2965        switch (Reg) {
2966        default: break;
2967        case X86::EAX: case X86::EDX: case X86::ECX:
2968          if (++NumInRegs == 3)
2969            return false;
2970          break;
2971        }
2972      }
2973    }
2974  }
2975
2976  return true;
2977}
2978
2979FastISel *
2980X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
2981                                  const TargetLibraryInfo *libInfo) const {
2982  return X86::createFastISel(funcInfo, libInfo);
2983}
2984
2985//===----------------------------------------------------------------------===//
2986//                           Other Lowering Hooks
2987//===----------------------------------------------------------------------===//
2988
2989static bool MayFoldLoad(SDValue Op) {
2990  return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
2991}
2992
2993static bool MayFoldIntoStore(SDValue Op) {
2994  return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
2995}
2996
2997static bool isTargetShuffle(unsigned Opcode) {
2998  switch(Opcode) {
2999  default: return false;
3000  case X86ISD::PSHUFD:
3001  case X86ISD::PSHUFHW:
3002  case X86ISD::PSHUFLW:
3003  case X86ISD::SHUFP:
3004  case X86ISD::PALIGN:
3005  case X86ISD::MOVLHPS:
3006  case X86ISD::MOVLHPD:
3007  case X86ISD::MOVHLPS:
3008  case X86ISD::MOVLPS:
3009  case X86ISD::MOVLPD:
3010  case X86ISD::MOVSHDUP:
3011  case X86ISD::MOVSLDUP:
3012  case X86ISD::MOVDDUP:
3013  case X86ISD::MOVSS:
3014  case X86ISD::MOVSD:
3015  case X86ISD::UNPCKL:
3016  case X86ISD::UNPCKH:
3017  case X86ISD::VPERMILP:
3018  case X86ISD::VPERM2X128:
3019  case X86ISD::VPERMI:
3020    return true;
3021  }
3022}
3023
3024static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
3025                                    SDValue V1, SelectionDAG &DAG) {
3026  switch(Opc) {
3027  default: llvm_unreachable("Unknown x86 shuffle node");
3028  case X86ISD::MOVSHDUP:
3029  case X86ISD::MOVSLDUP:
3030  case X86ISD::MOVDDUP:
3031    return DAG.getNode(Opc, dl, VT, V1);
3032  }
3033}
3034
3035static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
3036                                    SDValue V1, unsigned TargetMask,
3037                                    SelectionDAG &DAG) {
3038  switch(Opc) {
3039  default: llvm_unreachable("Unknown x86 shuffle node");
3040  case X86ISD::PSHUFD:
3041  case X86ISD::PSHUFHW:
3042  case X86ISD::PSHUFLW:
3043  case X86ISD::VPERMILP:
3044  case X86ISD::VPERMI:
3045    return DAG.getNode(Opc, dl, VT, V1, DAG.getConstant(TargetMask, MVT::i8));
3046  }
3047}
3048
3049static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
3050                                    SDValue V1, SDValue V2, unsigned TargetMask,
3051                                    SelectionDAG &DAG) {
3052  switch(Opc) {
3053  default: llvm_unreachable("Unknown x86 shuffle node");
3054  case X86ISD::PALIGN:
3055  case X86ISD::SHUFP:
3056  case X86ISD::VPERM2X128:
3057    return DAG.getNode(Opc, dl, VT, V1, V2,
3058                       DAG.getConstant(TargetMask, MVT::i8));
3059  }
3060}
3061
3062static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
3063                                    SDValue V1, SDValue V2, SelectionDAG &DAG) {
3064  switch(Opc) {
3065  default: llvm_unreachable("Unknown x86 shuffle node");
3066  case X86ISD::MOVLHPS:
3067  case X86ISD::MOVLHPD:
3068  case X86ISD::MOVHLPS:
3069  case X86ISD::MOVLPS:
3070  case X86ISD::MOVLPD:
3071  case X86ISD::MOVSS:
3072  case X86ISD::MOVSD:
3073  case X86ISD::UNPCKL:
3074  case X86ISD::UNPCKH:
3075    return DAG.getNode(Opc, dl, VT, V1, V2);
3076  }
3077}
3078
3079SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
3080  MachineFunction &MF = DAG.getMachineFunction();
3081  X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
3082  int ReturnAddrIndex = FuncInfo->getRAIndex();
3083
3084  if (ReturnAddrIndex == 0) {
3085    // Set up a frame object for the return address.
3086    unsigned SlotSize = RegInfo->getSlotSize();
3087    ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize, -SlotSize,
3088                                                           false);
3089    FuncInfo->setRAIndex(ReturnAddrIndex);
3090  }
3091
3092  return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
3093}
3094
3095bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
3096                                       bool hasSymbolicDisplacement) {
3097  // Offset should fit into 32 bit immediate field.
3098  if (!isInt<32>(Offset))
3099    return false;
3100
3101  // If we don't have a symbolic displacement - we don't have any extra
3102  // restrictions.
3103  if (!hasSymbolicDisplacement)
3104    return true;
3105
3106  // FIXME: Some tweaks might be needed for medium code model.
3107  if (M != CodeModel::Small && M != CodeModel::Kernel)
3108    return false;
3109
3110  // For small code model we assume that latest object is 16MB before end of 31
3111  // bits boundary. We may also accept pretty large negative constants knowing
3112  // that all objects are in the positive half of address space.
3113  if (M == CodeModel::Small && Offset < 16*1024*1024)
3114    return true;
3115
3116  // For kernel code model we know that all object resist in the negative half
3117  // of 32bits address space. We may not accept negative offsets, since they may
3118  // be just off and we may accept pretty large positive ones.
3119  if (M == CodeModel::Kernel && Offset > 0)
3120    return true;
3121
3122  return false;
3123}
3124
3125/// isCalleePop - Determines whether the callee is required to pop its
3126/// own arguments. Callee pop is necessary to support tail calls.
3127bool X86::isCalleePop(CallingConv::ID CallingConv,
3128                      bool is64Bit, bool IsVarArg, bool TailCallOpt) {
3129  if (IsVarArg)
3130    return false;
3131
3132  switch (CallingConv) {
3133  default:
3134    return false;
3135  case CallingConv::X86_StdCall:
3136    return !is64Bit;
3137  case CallingConv::X86_FastCall:
3138    return !is64Bit;
3139  case CallingConv::X86_ThisCall:
3140    return !is64Bit;
3141  case CallingConv::Fast:
3142    return TailCallOpt;
3143  case CallingConv::GHC:
3144    return TailCallOpt;
3145  case CallingConv::HiPE:
3146    return TailCallOpt;
3147  }
3148}
3149
3150/// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
3151/// specific condition code, returning the condition code and the LHS/RHS of the
3152/// comparison to make.
3153static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
3154                               SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
3155  if (!isFP) {
3156    if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
3157      if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
3158        // X > -1   -> X == 0, jump !sign.
3159        RHS = DAG.getConstant(0, RHS.getValueType());
3160        return X86::COND_NS;
3161      }
3162      if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
3163        // X < 0   -> X == 0, jump on sign.
3164        return X86::COND_S;
3165      }
3166      if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
3167        // X < 1   -> X <= 0
3168        RHS = DAG.getConstant(0, RHS.getValueType());
3169        return X86::COND_LE;
3170      }
3171    }
3172
3173    switch (SetCCOpcode) {
3174    default: llvm_unreachable("Invalid integer condition!");
3175    case ISD::SETEQ:  return X86::COND_E;
3176    case ISD::SETGT:  return X86::COND_G;
3177    case ISD::SETGE:  return X86::COND_GE;
3178    case ISD::SETLT:  return X86::COND_L;
3179    case ISD::SETLE:  return X86::COND_LE;
3180    case ISD::SETNE:  return X86::COND_NE;
3181    case ISD::SETULT: return X86::COND_B;
3182    case ISD::SETUGT: return X86::COND_A;
3183    case ISD::SETULE: return X86::COND_BE;
3184    case ISD::SETUGE: return X86::COND_AE;
3185    }
3186  }
3187
3188  // First determine if it is required or is profitable to flip the operands.
3189
3190  // If LHS is a foldable load, but RHS is not, flip the condition.
3191  if (ISD::isNON_EXTLoad(LHS.getNode()) &&
3192      !ISD::isNON_EXTLoad(RHS.getNode())) {
3193    SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
3194    std::swap(LHS, RHS);
3195  }
3196
3197  switch (SetCCOpcode) {
3198  default: break;
3199  case ISD::SETOLT:
3200  case ISD::SETOLE:
3201  case ISD::SETUGT:
3202  case ISD::SETUGE:
3203    std::swap(LHS, RHS);
3204    break;
3205  }
3206
3207  // On a floating point condition, the flags are set as follows:
3208  // ZF  PF  CF   op
3209  //  0 | 0 | 0 | X > Y
3210  //  0 | 0 | 1 | X < Y
3211  //  1 | 0 | 0 | X == Y
3212  //  1 | 1 | 1 | unordered
3213  switch (SetCCOpcode) {
3214  default: llvm_unreachable("Condcode should be pre-legalized away");
3215  case ISD::SETUEQ:
3216  case ISD::SETEQ:   return X86::COND_E;
3217  case ISD::SETOLT:              // flipped
3218  case ISD::SETOGT:
3219  case ISD::SETGT:   return X86::COND_A;
3220  case ISD::SETOLE:              // flipped
3221  case ISD::SETOGE:
3222  case ISD::SETGE:   return X86::COND_AE;
3223  case ISD::SETUGT:              // flipped
3224  case ISD::SETULT:
3225  case ISD::SETLT:   return X86::COND_B;
3226  case ISD::SETUGE:              // flipped
3227  case ISD::SETULE:
3228  case ISD::SETLE:   return X86::COND_BE;
3229  case ISD::SETONE:
3230  case ISD::SETNE:   return X86::COND_NE;
3231  case ISD::SETUO:   return X86::COND_P;
3232  case ISD::SETO:    return X86::COND_NP;
3233  case ISD::SETOEQ:
3234  case ISD::SETUNE:  return X86::COND_INVALID;
3235  }
3236}
3237
3238/// hasFPCMov - is there a floating point cmov for the specific X86 condition
3239/// code. Current x86 isa includes the following FP cmov instructions:
3240/// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
3241static bool hasFPCMov(unsigned X86CC) {
3242  switch (X86CC) {
3243  default:
3244    return false;
3245  case X86::COND_B:
3246  case X86::COND_BE:
3247  case X86::COND_E:
3248  case X86::COND_P:
3249  case X86::COND_A:
3250  case X86::COND_AE:
3251  case X86::COND_NE:
3252  case X86::COND_NP:
3253    return true;
3254  }
3255}
3256
3257/// isFPImmLegal - Returns true if the target can instruction select the
3258/// specified FP immediate natively. If false, the legalizer will
3259/// materialize the FP immediate as a load from a constant pool.
3260bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3261  for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
3262    if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
3263      return true;
3264  }
3265  return false;
3266}
3267
3268/// isUndefOrInRange - Return true if Val is undef or if its value falls within
3269/// the specified range (L, H].
3270static bool isUndefOrInRange(int Val, int Low, int Hi) {
3271  return (Val < 0) || (Val >= Low && Val < Hi);
3272}
3273
3274/// isUndefOrEqual - Val is either less than zero (undef) or equal to the
3275/// specified value.
3276static bool isUndefOrEqual(int Val, int CmpVal) {
3277  return (Val < 0 || Val == CmpVal);
3278}
3279
3280/// isSequentialOrUndefInRange - Return true if every element in Mask, beginning
3281/// from position Pos and ending in Pos+Size, falls within the specified
3282/// sequential range (L, L+Pos]. or is undef.
3283static bool isSequentialOrUndefInRange(ArrayRef<int> Mask,
3284                                       unsigned Pos, unsigned Size, int Low) {
3285  for (unsigned i = Pos, e = Pos+Size; i != e; ++i, ++Low)
3286    if (!isUndefOrEqual(Mask[i], Low))
3287      return false;
3288  return true;
3289}
3290
3291/// isPSHUFDMask - Return true if the node specifies a shuffle of elements that
3292/// is suitable for input to PSHUFD or PSHUFW.  That is, it doesn't reference
3293/// the second operand.
3294static bool isPSHUFDMask(ArrayRef<int> Mask, EVT VT) {
3295  if (VT == MVT::v4f32 || VT == MVT::v4i32 )
3296    return (Mask[0] < 4 && Mask[1] < 4 && Mask[2] < 4 && Mask[3] < 4);
3297  if (VT == MVT::v2f64 || VT == MVT::v2i64)
3298    return (Mask[0] < 2 && Mask[1] < 2);
3299  return false;
3300}
3301
3302/// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that
3303/// is suitable for input to PSHUFHW.
3304static bool isPSHUFHWMask(ArrayRef<int> Mask, EVT VT, bool HasInt256) {
3305  if (VT != MVT::v8i16 && (!HasInt256 || VT != MVT::v16i16))
3306    return false;
3307
3308  // Lower quadword copied in order or undef.
3309  if (!isSequentialOrUndefInRange(Mask, 0, 4, 0))
3310    return false;
3311
3312  // Upper quadword shuffled.
3313  for (unsigned i = 4; i != 8; ++i)
3314    if (!isUndefOrInRange(Mask[i], 4, 8))
3315      return false;
3316
3317  if (VT == MVT::v16i16) {
3318    // Lower quadword copied in order or undef.
3319    if (!isSequentialOrUndefInRange(Mask, 8, 4, 8))
3320      return false;
3321
3322    // Upper quadword shuffled.
3323    for (unsigned i = 12; i != 16; ++i)
3324      if (!isUndefOrInRange(Mask[i], 12, 16))
3325        return false;
3326  }
3327
3328  return true;
3329}
3330
3331/// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that
3332/// is suitable for input to PSHUFLW.
3333static bool isPSHUFLWMask(ArrayRef<int> Mask, EVT VT, bool HasInt256) {
3334  if (VT != MVT::v8i16 && (!HasInt256 || VT != MVT::v16i16))
3335    return false;
3336
3337  // Upper quadword copied in order.
3338  if (!isSequentialOrUndefInRange(Mask, 4, 4, 4))
3339    return false;
3340
3341  // Lower quadword shuffled.
3342  for (unsigned i = 0; i != 4; ++i)
3343    if (!isUndefOrInRange(Mask[i], 0, 4))
3344      return false;
3345
3346  if (VT == MVT::v16i16) {
3347    // Upper quadword copied in order.
3348    if (!isSequentialOrUndefInRange(Mask, 12, 4, 12))
3349      return false;
3350
3351    // Lower quadword shuffled.
3352    for (unsigned i = 8; i != 12; ++i)
3353      if (!isUndefOrInRange(Mask[i], 8, 12))
3354        return false;
3355  }
3356
3357  return true;
3358}
3359
3360/// isPALIGNRMask - Return true if the node specifies a shuffle of elements that
3361/// is suitable for input to PALIGNR.
3362static bool isPALIGNRMask(ArrayRef<int> Mask, EVT VT,
3363                          const X86Subtarget *Subtarget) {
3364  if ((VT.getSizeInBits() == 128 && !Subtarget->hasSSSE3()) ||
3365      (VT.getSizeInBits() == 256 && !Subtarget->hasInt256()))
3366    return false;
3367
3368  unsigned NumElts = VT.getVectorNumElements();
3369  unsigned NumLanes = VT.getSizeInBits()/128;
3370  unsigned NumLaneElts = NumElts/NumLanes;
3371
3372  // Do not handle 64-bit element shuffles with palignr.
3373  if (NumLaneElts == 2)
3374    return false;
3375
3376  for (unsigned l = 0; l != NumElts; l+=NumLaneElts) {
3377    unsigned i;
3378    for (i = 0; i != NumLaneElts; ++i) {
3379      if (Mask[i+l] >= 0)
3380        break;
3381    }
3382
3383    // Lane is all undef, go to next lane
3384    if (i == NumLaneElts)
3385      continue;
3386
3387    int Start = Mask[i+l];
3388
3389    // Make sure its in this lane in one of the sources
3390    if (!isUndefOrInRange(Start, l, l+NumLaneElts) &&
3391        !isUndefOrInRange(Start, l+NumElts, l+NumElts+NumLaneElts))
3392      return false;
3393
3394    // If not lane 0, then we must match lane 0
3395    if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Start, Mask[i]+l))
3396      return false;
3397
3398    // Correct second source to be contiguous with first source
3399    if (Start >= (int)NumElts)
3400      Start -= NumElts - NumLaneElts;
3401
3402    // Make sure we're shifting in the right direction.
3403    if (Start <= (int)(i+l))
3404      return false;
3405
3406    Start -= i;
3407
3408    // Check the rest of the elements to see if they are consecutive.
3409    for (++i; i != NumLaneElts; ++i) {
3410      int Idx = Mask[i+l];
3411
3412      // Make sure its in this lane
3413      if (!isUndefOrInRange(Idx, l, l+NumLaneElts) &&
3414          !isUndefOrInRange(Idx, l+NumElts, l+NumElts+NumLaneElts))
3415        return false;
3416
3417      // If not lane 0, then we must match lane 0
3418      if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Idx, Mask[i]+l))
3419        return false;
3420
3421      if (Idx >= (int)NumElts)
3422        Idx -= NumElts - NumLaneElts;
3423
3424      if (!isUndefOrEqual(Idx, Start+i))
3425        return false;
3426
3427    }
3428  }
3429
3430  return true;
3431}
3432
3433/// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
3434/// the two vector operands have swapped position.
3435static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask,
3436                                     unsigned NumElems) {
3437  for (unsigned i = 0; i != NumElems; ++i) {
3438    int idx = Mask[i];
3439    if (idx < 0)
3440      continue;
3441    else if (idx < (int)NumElems)
3442      Mask[i] = idx + NumElems;
3443    else
3444      Mask[i] = idx - NumElems;
3445  }
3446}
3447
3448/// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
3449/// specifies a shuffle of elements that is suitable for input to 128/256-bit
3450/// SHUFPS and SHUFPD. If Commuted is true, then it checks for sources to be
3451/// reverse of what x86 shuffles want.
3452static bool isSHUFPMask(ArrayRef<int> Mask, EVT VT, bool HasFp256,
3453                        bool Commuted = false) {
3454  if (!HasFp256 && VT.getSizeInBits() == 256)
3455    return false;
3456
3457  unsigned NumElems = VT.getVectorNumElements();
3458  unsigned NumLanes = VT.getSizeInBits()/128;
3459  unsigned NumLaneElems = NumElems/NumLanes;
3460
3461  if (NumLaneElems != 2 && NumLaneElems != 4)
3462    return false;
3463
3464  // VSHUFPSY divides the resulting vector into 4 chunks.
3465  // The sources are also splitted into 4 chunks, and each destination
3466  // chunk must come from a different source chunk.
3467  //
3468  //  SRC1 =>   X7    X6    X5    X4    X3    X2    X1    X0
3469  //  SRC2 =>   Y7    Y6    Y5    Y4    Y3    Y2    Y1    Y9
3470  //
3471  //  DST  =>  Y7..Y4,   Y7..Y4,   X7..X4,   X7..X4,
3472  //           Y3..Y0,   Y3..Y0,   X3..X0,   X3..X0
3473  //
3474  // VSHUFPDY divides the resulting vector into 4 chunks.
3475  // The sources are also splitted into 4 chunks, and each destination
3476  // chunk must come from a different source chunk.
3477  //
3478  //  SRC1 =>      X3       X2       X1       X0
3479  //  SRC2 =>      Y3       Y2       Y1       Y0
3480  //
3481  //  DST  =>  Y3..Y2,  X3..X2,  Y1..Y0,  X1..X0
3482  //
3483  unsigned HalfLaneElems = NumLaneElems/2;
3484  for (unsigned l = 0; l != NumElems; l += NumLaneElems) {
3485    for (unsigned i = 0; i != NumLaneElems; ++i) {
3486      int Idx = Mask[i+l];
3487      unsigned RngStart = l + ((Commuted == (i<HalfLaneElems)) ? NumElems : 0);
3488      if (!isUndefOrInRange(Idx, RngStart, RngStart+NumLaneElems))
3489        return false;
3490      // For VSHUFPSY, the mask of the second half must be the same as the
3491      // first but with the appropriate offsets. This works in the same way as
3492      // VPERMILPS works with masks.
3493      if (NumElems != 8 || l == 0 || Mask[i] < 0)
3494        continue;
3495      if (!isUndefOrEqual(Idx, Mask[i]+l))
3496        return false;
3497    }
3498  }
3499
3500  return true;
3501}
3502
3503/// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
3504/// specifies a shuffle of elements that is suitable for input to MOVHLPS.
3505static bool isMOVHLPSMask(ArrayRef<int> Mask, EVT VT) {
3506  if (!VT.is128BitVector())
3507    return false;
3508
3509  unsigned NumElems = VT.getVectorNumElements();
3510
3511  if (NumElems != 4)
3512    return false;
3513
3514  // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
3515  return isUndefOrEqual(Mask[0], 6) &&
3516         isUndefOrEqual(Mask[1], 7) &&
3517         isUndefOrEqual(Mask[2], 2) &&
3518         isUndefOrEqual(Mask[3], 3);
3519}
3520
3521/// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
3522/// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
3523/// <2, 3, 2, 3>
3524static bool isMOVHLPS_v_undef_Mask(ArrayRef<int> Mask, EVT VT) {
3525  if (!VT.is128BitVector())
3526    return false;
3527
3528  unsigned NumElems = VT.getVectorNumElements();
3529
3530  if (NumElems != 4)
3531    return false;
3532
3533  return isUndefOrEqual(Mask[0], 2) &&
3534         isUndefOrEqual(Mask[1], 3) &&
3535         isUndefOrEqual(Mask[2], 2) &&
3536         isUndefOrEqual(Mask[3], 3);
3537}
3538
3539/// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
3540/// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
3541static bool isMOVLPMask(ArrayRef<int> Mask, EVT VT) {
3542  if (!VT.is128BitVector())
3543    return false;
3544
3545  unsigned NumElems = VT.getVectorNumElements();
3546
3547  if (NumElems != 2 && NumElems != 4)
3548    return false;
3549
3550  for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3551    if (!isUndefOrEqual(Mask[i], i + NumElems))
3552      return false;
3553
3554  for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
3555    if (!isUndefOrEqual(Mask[i], i))
3556      return false;
3557
3558  return true;
3559}
3560
3561/// isMOVLHPSMask - Return true if the specified VECTOR_SHUFFLE operand
3562/// specifies a shuffle of elements that is suitable for input to MOVLHPS.
3563static bool isMOVLHPSMask(ArrayRef<int> Mask, EVT VT) {
3564  if (!VT.is128BitVector())
3565    return false;
3566
3567  unsigned NumElems = VT.getVectorNumElements();
3568
3569  if (NumElems != 2 && NumElems != 4)
3570    return false;
3571
3572  for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3573    if (!isUndefOrEqual(Mask[i], i))
3574      return false;
3575
3576  for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3577    if (!isUndefOrEqual(Mask[i + e], i + NumElems))
3578      return false;
3579
3580  return true;
3581}
3582
3583//
3584// Some special combinations that can be optimized.
3585//
3586static
3587SDValue Compact8x32ShuffleNode(ShuffleVectorSDNode *SVOp,
3588                               SelectionDAG &DAG) {
3589  EVT VT = SVOp->getValueType(0);
3590  DebugLoc dl = SVOp->getDebugLoc();
3591
3592  if (VT != MVT::v8i32 && VT != MVT::v8f32)
3593    return SDValue();
3594
3595  ArrayRef<int> Mask = SVOp->getMask();
3596
3597  // These are the special masks that may be optimized.
3598  static const int MaskToOptimizeEven[] = {0, 8, 2, 10, 4, 12, 6, 14};
3599  static const int MaskToOptimizeOdd[]  = {1, 9, 3, 11, 5, 13, 7, 15};
3600  bool MatchEvenMask = true;
3601  bool MatchOddMask  = true;
3602  for (int i=0; i<8; ++i) {
3603    if (!isUndefOrEqual(Mask[i], MaskToOptimizeEven[i]))
3604      MatchEvenMask = false;
3605    if (!isUndefOrEqual(Mask[i], MaskToOptimizeOdd[i]))
3606      MatchOddMask = false;
3607  }
3608
3609  if (!MatchEvenMask && !MatchOddMask)
3610    return SDValue();
3611
3612  SDValue UndefNode = DAG.getNode(ISD::UNDEF, dl, VT);
3613
3614  SDValue Op0 = SVOp->getOperand(0);
3615  SDValue Op1 = SVOp->getOperand(1);
3616
3617  if (MatchEvenMask) {
3618    // Shift the second operand right to 32 bits.
3619    static const int ShiftRightMask[] = {-1, 0, -1, 2, -1, 4, -1, 6 };
3620    Op1 = DAG.getVectorShuffle(VT, dl, Op1, UndefNode, ShiftRightMask);
3621  } else {
3622    // Shift the first operand left to 32 bits.
3623    static const int ShiftLeftMask[] = {1, -1, 3, -1, 5, -1, 7, -1 };
3624    Op0 = DAG.getVectorShuffle(VT, dl, Op0, UndefNode, ShiftLeftMask);
3625  }
3626  static const int BlendMask[] = {0, 9, 2, 11, 4, 13, 6, 15};
3627  return DAG.getVectorShuffle(VT, dl, Op0, Op1, BlendMask);
3628}
3629
3630/// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
3631/// specifies a shuffle of elements that is suitable for input to UNPCKL.
3632static bool isUNPCKLMask(ArrayRef<int> Mask, EVT VT,
3633                         bool HasInt256, bool V2IsSplat = false) {
3634  unsigned NumElts = VT.getVectorNumElements();
3635
3636  assert((VT.is128BitVector() || VT.is256BitVector()) &&
3637         "Unsupported vector type for unpckh");
3638
3639  if (VT.getSizeInBits() == 256 && NumElts != 4 && NumElts != 8 &&
3640      (!HasInt256 || (NumElts != 16 && NumElts != 32)))
3641    return false;
3642
3643  // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3644  // independently on 128-bit lanes.
3645  unsigned NumLanes = VT.getSizeInBits()/128;
3646  unsigned NumLaneElts = NumElts/NumLanes;
3647
3648  for (unsigned l = 0; l != NumLanes; ++l) {
3649    for (unsigned i = l*NumLaneElts, j = l*NumLaneElts;
3650         i != (l+1)*NumLaneElts;
3651         i += 2, ++j) {
3652      int BitI  = Mask[i];
3653      int BitI1 = Mask[i+1];
3654      if (!isUndefOrEqual(BitI, j))
3655        return false;
3656      if (V2IsSplat) {
3657        if (!isUndefOrEqual(BitI1, NumElts))
3658          return false;
3659      } else {
3660        if (!isUndefOrEqual(BitI1, j + NumElts))
3661          return false;
3662      }
3663    }
3664  }
3665
3666  return true;
3667}
3668
3669/// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
3670/// specifies a shuffle of elements that is suitable for input to UNPCKH.
3671static bool isUNPCKHMask(ArrayRef<int> Mask, EVT VT,
3672                         bool HasInt256, bool V2IsSplat = false) {
3673  unsigned NumElts = VT.getVectorNumElements();
3674
3675  assert((VT.is128BitVector() || VT.is256BitVector()) &&
3676         "Unsupported vector type for unpckh");
3677
3678  if (VT.getSizeInBits() == 256 && NumElts != 4 && NumElts != 8 &&
3679      (!HasInt256 || (NumElts != 16 && NumElts != 32)))
3680    return false;
3681
3682  // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3683  // independently on 128-bit lanes.
3684  unsigned NumLanes = VT.getSizeInBits()/128;
3685  unsigned NumLaneElts = NumElts/NumLanes;
3686
3687  for (unsigned l = 0; l != NumLanes; ++l) {
3688    for (unsigned i = l*NumLaneElts, j = (l*NumLaneElts)+NumLaneElts/2;
3689         i != (l+1)*NumLaneElts; i += 2, ++j) {
3690      int BitI  = Mask[i];
3691      int BitI1 = Mask[i+1];
3692      if (!isUndefOrEqual(BitI, j))
3693        return false;
3694      if (V2IsSplat) {
3695        if (isUndefOrEqual(BitI1, NumElts))
3696          return false;
3697      } else {
3698        if (!isUndefOrEqual(BitI1, j+NumElts))
3699          return false;
3700      }
3701    }
3702  }
3703  return true;
3704}
3705
3706/// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
3707/// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
3708/// <0, 0, 1, 1>
3709static bool isUNPCKL_v_undef_Mask(ArrayRef<int> Mask, EVT VT,
3710                                  bool HasInt256) {
3711  unsigned NumElts = VT.getVectorNumElements();
3712
3713  assert((VT.is128BitVector() || VT.is256BitVector()) &&
3714         "Unsupported vector type for unpckh");
3715
3716  if (VT.getSizeInBits() == 256 && NumElts != 4 && NumElts != 8 &&
3717      (!HasInt256 || (NumElts != 16 && NumElts != 32)))
3718    return false;
3719
3720  // For 256-bit i64/f64, use MOVDDUPY instead, so reject the matching pattern
3721  // FIXME: Need a better way to get rid of this, there's no latency difference
3722  // between UNPCKLPD and MOVDDUP, the later should always be checked first and
3723  // the former later. We should also remove the "_undef" special mask.
3724  if (NumElts == 4 && VT.getSizeInBits() == 256)
3725    return false;
3726
3727  // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3728  // independently on 128-bit lanes.
3729  unsigned NumLanes = VT.getSizeInBits()/128;
3730  unsigned NumLaneElts = NumElts/NumLanes;
3731
3732  for (unsigned l = 0; l != NumLanes; ++l) {
3733    for (unsigned i = l*NumLaneElts, j = l*NumLaneElts;
3734         i != (l+1)*NumLaneElts;
3735         i += 2, ++j) {
3736      int BitI  = Mask[i];
3737      int BitI1 = Mask[i+1];
3738
3739      if (!isUndefOrEqual(BitI, j))
3740        return false;
3741      if (!isUndefOrEqual(BitI1, j))
3742        return false;
3743    }
3744  }
3745
3746  return true;
3747}
3748
3749/// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
3750/// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
3751/// <2, 2, 3, 3>
3752static bool isUNPCKH_v_undef_Mask(ArrayRef<int> Mask, EVT VT, bool HasInt256) {
3753  unsigned NumElts = VT.getVectorNumElements();
3754
3755  assert((VT.is128BitVector() || VT.is256BitVector()) &&
3756         "Unsupported vector type for unpckh");
3757
3758  if (VT.getSizeInBits() == 256 && NumElts != 4 && NumElts != 8 &&
3759      (!HasInt256 || (NumElts != 16 && NumElts != 32)))
3760    return false;
3761
3762  // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3763  // independently on 128-bit lanes.
3764  unsigned NumLanes = VT.getSizeInBits()/128;
3765  unsigned NumLaneElts = NumElts/NumLanes;
3766
3767  for (unsigned l = 0; l != NumLanes; ++l) {
3768    for (unsigned i = l*NumLaneElts, j = (l*NumLaneElts)+NumLaneElts/2;
3769         i != (l+1)*NumLaneElts; i += 2, ++j) {
3770      int BitI  = Mask[i];
3771      int BitI1 = Mask[i+1];
3772      if (!isUndefOrEqual(BitI, j))
3773        return false;
3774      if (!isUndefOrEqual(BitI1, j))
3775        return false;
3776    }
3777  }
3778  return true;
3779}
3780
3781/// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
3782/// specifies a shuffle of elements that is suitable for input to MOVSS,
3783/// MOVSD, and MOVD, i.e. setting the lowest element.
3784static bool isMOVLMask(ArrayRef<int> Mask, EVT VT) {
3785  if (VT.getVectorElementType().getSizeInBits() < 32)
3786    return false;
3787  if (!VT.is128BitVector())
3788    return false;
3789
3790  unsigned NumElts = VT.getVectorNumElements();
3791
3792  if (!isUndefOrEqual(Mask[0], NumElts))
3793    return false;
3794
3795  for (unsigned i = 1; i != NumElts; ++i)
3796    if (!isUndefOrEqual(Mask[i], i))
3797      return false;
3798
3799  return true;
3800}
3801
3802/// isVPERM2X128Mask - Match 256-bit shuffles where the elements are considered
3803/// as permutations between 128-bit chunks or halves. As an example: this
3804/// shuffle bellow:
3805///   vector_shuffle <4, 5, 6, 7, 12, 13, 14, 15>
3806/// The first half comes from the second half of V1 and the second half from the
3807/// the second half of V2.
3808static bool isVPERM2X128Mask(ArrayRef<int> Mask, EVT VT, bool HasFp256) {
3809  if (!HasFp256 || !VT.is256BitVector())
3810    return false;
3811
3812  // The shuffle result is divided into half A and half B. In total the two
3813  // sources have 4 halves, namely: C, D, E, F. The final values of A and
3814  // B must come from C, D, E or F.
3815  unsigned HalfSize = VT.getVectorNumElements()/2;
3816  bool MatchA = false, MatchB = false;
3817
3818  // Check if A comes from one of C, D, E, F.
3819  for (unsigned Half = 0; Half != 4; ++Half) {
3820    if (isSequentialOrUndefInRange(Mask, 0, HalfSize, Half*HalfSize)) {
3821      MatchA = true;
3822      break;
3823    }
3824  }
3825
3826  // Check if B comes from one of C, D, E, F.
3827  for (unsigned Half = 0; Half != 4; ++Half) {
3828    if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, Half*HalfSize)) {
3829      MatchB = true;
3830      break;
3831    }
3832  }
3833
3834  return MatchA && MatchB;
3835}
3836
3837/// getShuffleVPERM2X128Immediate - Return the appropriate immediate to shuffle
3838/// the specified VECTOR_MASK mask with VPERM2F128/VPERM2I128 instructions.
3839static unsigned getShuffleVPERM2X128Immediate(ShuffleVectorSDNode *SVOp) {
3840  EVT VT = SVOp->getValueType(0);
3841
3842  unsigned HalfSize = VT.getVectorNumElements()/2;
3843
3844  unsigned FstHalf = 0, SndHalf = 0;
3845  for (unsigned i = 0; i < HalfSize; ++i) {
3846    if (SVOp->getMaskElt(i) > 0) {
3847      FstHalf = SVOp->getMaskElt(i)/HalfSize;
3848      break;
3849    }
3850  }
3851  for (unsigned i = HalfSize; i < HalfSize*2; ++i) {
3852    if (SVOp->getMaskElt(i) > 0) {
3853      SndHalf = SVOp->getMaskElt(i)/HalfSize;
3854      break;
3855    }
3856  }
3857
3858  return (FstHalf | (SndHalf << 4));
3859}
3860
3861/// isVPERMILPMask - Return true if the specified VECTOR_SHUFFLE operand
3862/// specifies a shuffle of elements that is suitable for input to VPERMILPD*.
3863/// Note that VPERMIL mask matching is different depending whether theunderlying
3864/// type is 32 or 64. In the VPERMILPS the high half of the mask should point
3865/// to the same elements of the low, but to the higher half of the source.
3866/// In VPERMILPD the two lanes could be shuffled independently of each other
3867/// with the same restriction that lanes can't be crossed. Also handles PSHUFDY.
3868static bool isVPERMILPMask(ArrayRef<int> Mask, EVT VT, bool HasFp256) {
3869  if (!HasFp256)
3870    return false;
3871
3872  unsigned NumElts = VT.getVectorNumElements();
3873  // Only match 256-bit with 32/64-bit types
3874  if (VT.getSizeInBits() != 256 || (NumElts != 4 && NumElts != 8))
3875    return false;
3876
3877  unsigned NumLanes = VT.getSizeInBits()/128;
3878  unsigned LaneSize = NumElts/NumLanes;
3879  for (unsigned l = 0; l != NumElts; l += LaneSize) {
3880    for (unsigned i = 0; i != LaneSize; ++i) {
3881      if (!isUndefOrInRange(Mask[i+l], l, l+LaneSize))
3882        return false;
3883      if (NumElts != 8 || l == 0)
3884        continue;
3885      // VPERMILPS handling
3886      if (Mask[i] < 0)
3887        continue;
3888      if (!isUndefOrEqual(Mask[i+l], Mask[i]+l))
3889        return false;
3890    }
3891  }
3892
3893  return true;
3894}
3895
3896/// isCommutedMOVLMask - Returns true if the shuffle mask is except the reverse
3897/// of what x86 movss want. X86 movs requires the lowest  element to be lowest
3898/// element of vector 2 and the other elements to come from vector 1 in order.
3899static bool isCommutedMOVLMask(ArrayRef<int> Mask, EVT VT,
3900                               bool V2IsSplat = false, bool V2IsUndef = false) {
3901  if (!VT.is128BitVector())
3902    return false;
3903
3904  unsigned NumOps = VT.getVectorNumElements();
3905  if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
3906    return false;
3907
3908  if (!isUndefOrEqual(Mask[0], 0))
3909    return false;
3910
3911  for (unsigned i = 1; i != NumOps; ++i)
3912    if (!(isUndefOrEqual(Mask[i], i+NumOps) ||
3913          (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) ||
3914          (V2IsSplat && isUndefOrEqual(Mask[i], NumOps))))
3915      return false;
3916
3917  return true;
3918}
3919
3920/// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3921/// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
3922/// Masks to match: <1, 1, 3, 3> or <1, 1, 3, 3, 5, 5, 7, 7>
3923static bool isMOVSHDUPMask(ArrayRef<int> Mask, EVT VT,
3924                           const X86Subtarget *Subtarget) {
3925  if (!Subtarget->hasSSE3())
3926    return false;
3927
3928  unsigned NumElems = VT.getVectorNumElements();
3929
3930  if ((VT.getSizeInBits() == 128 && NumElems != 4) ||
3931      (VT.getSizeInBits() == 256 && NumElems != 8))
3932    return false;
3933
3934  // "i+1" is the value the indexed mask element must have
3935  for (unsigned i = 0; i != NumElems; i += 2)
3936    if (!isUndefOrEqual(Mask[i], i+1) ||
3937        !isUndefOrEqual(Mask[i+1], i+1))
3938      return false;
3939
3940  return true;
3941}
3942
3943/// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3944/// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
3945/// Masks to match: <0, 0, 2, 2> or <0, 0, 2, 2, 4, 4, 6, 6>
3946static bool isMOVSLDUPMask(ArrayRef<int> Mask, EVT VT,
3947                           const X86Subtarget *Subtarget) {
3948  if (!Subtarget->hasSSE3())
3949    return false;
3950
3951  unsigned NumElems = VT.getVectorNumElements();
3952
3953  if ((VT.getSizeInBits() == 128 && NumElems != 4) ||
3954      (VT.getSizeInBits() == 256 && NumElems != 8))
3955    return false;
3956
3957  // "i" is the value the indexed mask element must have
3958  for (unsigned i = 0; i != NumElems; i += 2)
3959    if (!isUndefOrEqual(Mask[i], i) ||
3960        !isUndefOrEqual(Mask[i+1], i))
3961      return false;
3962
3963  return true;
3964}
3965
3966/// isMOVDDUPYMask - Return true if the specified VECTOR_SHUFFLE operand
3967/// specifies a shuffle of elements that is suitable for input to 256-bit
3968/// version of MOVDDUP.
3969static bool isMOVDDUPYMask(ArrayRef<int> Mask, EVT VT, bool HasFp256) {
3970  if (!HasFp256 || !VT.is256BitVector())
3971    return false;
3972
3973  unsigned NumElts = VT.getVectorNumElements();
3974  if (NumElts != 4)
3975    return false;
3976
3977  for (unsigned i = 0; i != NumElts/2; ++i)
3978    if (!isUndefOrEqual(Mask[i], 0))
3979      return false;
3980  for (unsigned i = NumElts/2; i != NumElts; ++i)
3981    if (!isUndefOrEqual(Mask[i], NumElts/2))
3982      return false;
3983  return true;
3984}
3985
3986/// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3987/// specifies a shuffle of elements that is suitable for input to 128-bit
3988/// version of MOVDDUP.
3989static bool isMOVDDUPMask(ArrayRef<int> Mask, EVT VT) {
3990  if (!VT.is128BitVector())
3991    return false;
3992
3993  unsigned e = VT.getVectorNumElements() / 2;
3994  for (unsigned i = 0; i != e; ++i)
3995    if (!isUndefOrEqual(Mask[i], i))
3996      return false;
3997  for (unsigned i = 0; i != e; ++i)
3998    if (!isUndefOrEqual(Mask[e+i], i))
3999      return false;
4000  return true;
4001}
4002
4003/// isVEXTRACTF128Index - Return true if the specified
4004/// EXTRACT_SUBVECTOR operand specifies a vector extract that is
4005/// suitable for input to VEXTRACTF128.
4006bool X86::isVEXTRACTF128Index(SDNode *N) {
4007  if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4008    return false;
4009
4010  // The index should be aligned on a 128-bit boundary.
4011  uint64_t Index =
4012    cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4013
4014  unsigned VL = N->getValueType(0).getVectorNumElements();
4015  unsigned VBits = N->getValueType(0).getSizeInBits();
4016  unsigned ElSize = VBits / VL;
4017  bool Result = (Index * ElSize) % 128 == 0;
4018
4019  return Result;
4020}
4021
4022/// isVINSERTF128Index - Return true if the specified INSERT_SUBVECTOR
4023/// operand specifies a subvector insert that is suitable for input to
4024/// VINSERTF128.
4025bool X86::isVINSERTF128Index(SDNode *N) {
4026  if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4027    return false;
4028
4029  // The index should be aligned on a 128-bit boundary.
4030  uint64_t Index =
4031    cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4032
4033  unsigned VL = N->getValueType(0).getVectorNumElements();
4034  unsigned VBits = N->getValueType(0).getSizeInBits();
4035  unsigned ElSize = VBits / VL;
4036  bool Result = (Index * ElSize) % 128 == 0;
4037
4038  return Result;
4039}
4040
4041/// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
4042/// the specified VECTOR_SHUFFLE mask with PSHUF* and SHUFP* instructions.
4043/// Handles 128-bit and 256-bit.
4044static unsigned getShuffleSHUFImmediate(ShuffleVectorSDNode *N) {
4045  EVT VT = N->getValueType(0);
4046
4047  assert((VT.is128BitVector() || VT.is256BitVector()) &&
4048         "Unsupported vector type for PSHUF/SHUFP");
4049
4050  // Handle 128 and 256-bit vector lengths. AVX defines PSHUF/SHUFP to operate
4051  // independently on 128-bit lanes.
4052  unsigned NumElts = VT.getVectorNumElements();
4053  unsigned NumLanes = VT.getSizeInBits()/128;
4054  unsigned NumLaneElts = NumElts/NumLanes;
4055
4056  assert((NumLaneElts == 2 || NumLaneElts == 4) &&
4057         "Only supports 2 or 4 elements per lane");
4058
4059  unsigned Shift = (NumLaneElts == 4) ? 1 : 0;
4060  unsigned Mask = 0;
4061  for (unsigned i = 0; i != NumElts; ++i) {
4062    int Elt = N->getMaskElt(i);
4063    if (Elt < 0) continue;
4064    Elt &= NumLaneElts - 1;
4065    unsigned ShAmt = (i << Shift) % 8;
4066    Mask |= Elt << ShAmt;
4067  }
4068
4069  return Mask;
4070}
4071
4072/// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
4073/// the specified VECTOR_SHUFFLE mask with the PSHUFHW instruction.
4074static unsigned getShufflePSHUFHWImmediate(ShuffleVectorSDNode *N) {
4075  EVT VT = N->getValueType(0);
4076
4077  assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4078         "Unsupported vector type for PSHUFHW");
4079
4080  unsigned NumElts = VT.getVectorNumElements();
4081
4082  unsigned Mask = 0;
4083  for (unsigned l = 0; l != NumElts; l += 8) {
4084    // 8 nodes per lane, but we only care about the last 4.
4085    for (unsigned i = 0; i < 4; ++i) {
4086      int Elt = N->getMaskElt(l+i+4);
4087      if (Elt < 0) continue;
4088      Elt &= 0x3; // only 2-bits.
4089      Mask |= Elt << (i * 2);
4090    }
4091  }
4092
4093  return Mask;
4094}
4095
4096/// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
4097/// the specified VECTOR_SHUFFLE mask with the PSHUFLW instruction.
4098static unsigned getShufflePSHUFLWImmediate(ShuffleVectorSDNode *N) {
4099  EVT VT = N->getValueType(0);
4100
4101  assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4102         "Unsupported vector type for PSHUFHW");
4103
4104  unsigned NumElts = VT.getVectorNumElements();
4105
4106  unsigned Mask = 0;
4107  for (unsigned l = 0; l != NumElts; l += 8) {
4108    // 8 nodes per lane, but we only care about the first 4.
4109    for (unsigned i = 0; i < 4; ++i) {
4110      int Elt = N->getMaskElt(l+i);
4111      if (Elt < 0) continue;
4112      Elt &= 0x3; // only 2-bits
4113      Mask |= Elt << (i * 2);
4114    }
4115  }
4116
4117  return Mask;
4118}
4119
4120/// getShufflePALIGNRImmediate - Return the appropriate immediate to shuffle
4121/// the specified VECTOR_SHUFFLE mask with the PALIGNR instruction.
4122static unsigned getShufflePALIGNRImmediate(ShuffleVectorSDNode *SVOp) {
4123  EVT VT = SVOp->getValueType(0);
4124  unsigned EltSize = VT.getVectorElementType().getSizeInBits() >> 3;
4125
4126  unsigned NumElts = VT.getVectorNumElements();
4127  unsigned NumLanes = VT.getSizeInBits()/128;
4128  unsigned NumLaneElts = NumElts/NumLanes;
4129
4130  int Val = 0;
4131  unsigned i;
4132  for (i = 0; i != NumElts; ++i) {
4133    Val = SVOp->getMaskElt(i);
4134    if (Val >= 0)
4135      break;
4136  }
4137  if (Val >= (int)NumElts)
4138    Val -= NumElts - NumLaneElts;
4139
4140  assert(Val - i > 0 && "PALIGNR imm should be positive");
4141  return (Val - i) * EltSize;
4142}
4143
4144/// getExtractVEXTRACTF128Immediate - Return the appropriate immediate
4145/// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF128
4146/// instructions.
4147unsigned X86::getExtractVEXTRACTF128Immediate(SDNode *N) {
4148  if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4149    llvm_unreachable("Illegal extract subvector for VEXTRACTF128");
4150
4151  uint64_t Index =
4152    cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4153
4154  EVT VecVT = N->getOperand(0).getValueType();
4155  EVT ElVT = VecVT.getVectorElementType();
4156
4157  unsigned NumElemsPerChunk = 128 / ElVT.getSizeInBits();
4158  return Index / NumElemsPerChunk;
4159}
4160
4161/// getInsertVINSERTF128Immediate - Return the appropriate immediate
4162/// to insert at the specified INSERT_SUBVECTOR index with VINSERTF128
4163/// instructions.
4164unsigned X86::getInsertVINSERTF128Immediate(SDNode *N) {
4165  if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4166    llvm_unreachable("Illegal insert subvector for VINSERTF128");
4167
4168  uint64_t Index =
4169    cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4170
4171  EVT VecVT = N->getValueType(0);
4172  EVT ElVT = VecVT.getVectorElementType();
4173
4174  unsigned NumElemsPerChunk = 128 / ElVT.getSizeInBits();
4175  return Index / NumElemsPerChunk;
4176}
4177
4178/// getShuffleCLImmediate - Return the appropriate immediate to shuffle
4179/// the specified VECTOR_SHUFFLE mask with VPERMQ and VPERMPD instructions.
4180/// Handles 256-bit.
4181static unsigned getShuffleCLImmediate(ShuffleVectorSDNode *N) {
4182  EVT VT = N->getValueType(0);
4183
4184  unsigned NumElts = VT.getVectorNumElements();
4185
4186  assert((VT.is256BitVector() && NumElts == 4) &&
4187         "Unsupported vector type for VPERMQ/VPERMPD");
4188
4189  unsigned Mask = 0;
4190  for (unsigned i = 0; i != NumElts; ++i) {
4191    int Elt = N->getMaskElt(i);
4192    if (Elt < 0)
4193      continue;
4194    Mask |= Elt << (i*2);
4195  }
4196
4197  return Mask;
4198}
4199/// isZeroNode - Returns true if Elt is a constant zero or a floating point
4200/// constant +0.0.
4201bool X86::isZeroNode(SDValue Elt) {
4202  return ((isa<ConstantSDNode>(Elt) &&
4203           cast<ConstantSDNode>(Elt)->isNullValue()) ||
4204          (isa<ConstantFPSDNode>(Elt) &&
4205           cast<ConstantFPSDNode>(Elt)->getValueAPF().isPosZero()));
4206}
4207
4208/// CommuteVectorShuffle - Swap vector_shuffle operands as well as values in
4209/// their permute mask.
4210static SDValue CommuteVectorShuffle(ShuffleVectorSDNode *SVOp,
4211                                    SelectionDAG &DAG) {
4212  EVT VT = SVOp->getValueType(0);
4213  unsigned NumElems = VT.getVectorNumElements();
4214  SmallVector<int, 8> MaskVec;
4215
4216  for (unsigned i = 0; i != NumElems; ++i) {
4217    int Idx = SVOp->getMaskElt(i);
4218    if (Idx >= 0) {
4219      if (Idx < (int)NumElems)
4220        Idx += NumElems;
4221      else
4222        Idx -= NumElems;
4223    }
4224    MaskVec.push_back(Idx);
4225  }
4226  return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(1),
4227                              SVOp->getOperand(0), &MaskVec[0]);
4228}
4229
4230/// ShouldXformToMOVHLPS - Return true if the node should be transformed to
4231/// match movhlps. The lower half elements should come from upper half of
4232/// V1 (and in order), and the upper half elements should come from the upper
4233/// half of V2 (and in order).
4234static bool ShouldXformToMOVHLPS(ArrayRef<int> Mask, EVT VT) {
4235  if (!VT.is128BitVector())
4236    return false;
4237  if (VT.getVectorNumElements() != 4)
4238    return false;
4239  for (unsigned i = 0, e = 2; i != e; ++i)
4240    if (!isUndefOrEqual(Mask[i], i+2))
4241      return false;
4242  for (unsigned i = 2; i != 4; ++i)
4243    if (!isUndefOrEqual(Mask[i], i+4))
4244      return false;
4245  return true;
4246}
4247
4248/// isScalarLoadToVector - Returns true if the node is a scalar load that
4249/// is promoted to a vector. It also returns the LoadSDNode by reference if
4250/// required.
4251static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = NULL) {
4252  if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
4253    return false;
4254  N = N->getOperand(0).getNode();
4255  if (!ISD::isNON_EXTLoad(N))
4256    return false;
4257  if (LD)
4258    *LD = cast<LoadSDNode>(N);
4259  return true;
4260}
4261
4262// Test whether the given value is a vector value which will be legalized
4263// into a load.
4264static bool WillBeConstantPoolLoad(SDNode *N) {
4265  if (N->getOpcode() != ISD::BUILD_VECTOR)
4266    return false;
4267
4268  // Check for any non-constant elements.
4269  for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
4270    switch (N->getOperand(i).getNode()->getOpcode()) {
4271    case ISD::UNDEF:
4272    case ISD::ConstantFP:
4273    case ISD::Constant:
4274      break;
4275    default:
4276      return false;
4277    }
4278
4279  // Vectors of all-zeros and all-ones are materialized with special
4280  // instructions rather than being loaded.
4281  return !ISD::isBuildVectorAllZeros(N) &&
4282         !ISD::isBuildVectorAllOnes(N);
4283}
4284
4285/// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
4286/// match movlp{s|d}. The lower half elements should come from lower half of
4287/// V1 (and in order), and the upper half elements should come from the upper
4288/// half of V2 (and in order). And since V1 will become the source of the
4289/// MOVLP, it must be either a vector load or a scalar load to vector.
4290static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2,
4291                               ArrayRef<int> Mask, EVT VT) {
4292  if (!VT.is128BitVector())
4293    return false;
4294
4295  if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
4296    return false;
4297  // Is V2 is a vector load, don't do this transformation. We will try to use
4298  // load folding shufps op.
4299  if (ISD::isNON_EXTLoad(V2) || WillBeConstantPoolLoad(V2))
4300    return false;
4301
4302  unsigned NumElems = VT.getVectorNumElements();
4303
4304  if (NumElems != 2 && NumElems != 4)
4305    return false;
4306  for (unsigned i = 0, e = NumElems/2; i != e; ++i)
4307    if (!isUndefOrEqual(Mask[i], i))
4308      return false;
4309  for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
4310    if (!isUndefOrEqual(Mask[i], i+NumElems))
4311      return false;
4312  return true;
4313}
4314
4315/// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
4316/// all the same.
4317static bool isSplatVector(SDNode *N) {
4318  if (N->getOpcode() != ISD::BUILD_VECTOR)
4319    return false;
4320
4321  SDValue SplatValue = N->getOperand(0);
4322  for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
4323    if (N->getOperand(i) != SplatValue)
4324      return false;
4325  return true;
4326}
4327
4328/// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
4329/// to an zero vector.
4330/// FIXME: move to dag combiner / method on ShuffleVectorSDNode
4331static bool isZeroShuffle(ShuffleVectorSDNode *N) {
4332  SDValue V1 = N->getOperand(0);
4333  SDValue V2 = N->getOperand(1);
4334  unsigned NumElems = N->getValueType(0).getVectorNumElements();
4335  for (unsigned i = 0; i != NumElems; ++i) {
4336    int Idx = N->getMaskElt(i);
4337    if (Idx >= (int)NumElems) {
4338      unsigned Opc = V2.getOpcode();
4339      if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
4340        continue;
4341      if (Opc != ISD::BUILD_VECTOR ||
4342          !X86::isZeroNode(V2.getOperand(Idx-NumElems)))
4343        return false;
4344    } else if (Idx >= 0) {
4345      unsigned Opc = V1.getOpcode();
4346      if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
4347        continue;
4348      if (Opc != ISD::BUILD_VECTOR ||
4349          !X86::isZeroNode(V1.getOperand(Idx)))
4350        return false;
4351    }
4352  }
4353  return true;
4354}
4355
4356/// getZeroVector - Returns a vector of specified type with all zero elements.
4357///
4358static SDValue getZeroVector(EVT VT, const X86Subtarget *Subtarget,
4359                             SelectionDAG &DAG, DebugLoc dl) {
4360  assert(VT.isVector() && "Expected a vector type");
4361  unsigned Size = VT.getSizeInBits();
4362
4363  // Always build SSE zero vectors as <4 x i32> bitcasted
4364  // to their dest type. This ensures they get CSE'd.
4365  SDValue Vec;
4366  if (Size == 128) {  // SSE
4367    if (Subtarget->hasSSE2()) {  // SSE2
4368      SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4369      Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4370    } else { // SSE1
4371      SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4372      Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
4373    }
4374  } else if (Size == 256) { // AVX
4375    if (Subtarget->hasInt256()) { // AVX2
4376      SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4377      SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4378      Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops, 8);
4379    } else {
4380      // 256-bit logic and arithmetic instructions in AVX are all
4381      // floating-point, no support for integer ops. Emit fp zeroed vectors.
4382      SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4383      SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4384      Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops, 8);
4385    }
4386  } else
4387    llvm_unreachable("Unexpected vector type");
4388
4389  return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4390}
4391
4392/// getOnesVector - Returns a vector of specified type with all bits set.
4393/// Always build ones vectors as <4 x i32> or <8 x i32>. For 256-bit types with
4394/// no AVX2 supprt, use two <4 x i32> inserted in a <8 x i32> appropriately.
4395/// Then bitcast to their original type, ensuring they get CSE'd.
4396static SDValue getOnesVector(EVT VT, bool HasInt256, SelectionDAG &DAG,
4397                             DebugLoc dl) {
4398  assert(VT.isVector() && "Expected a vector type");
4399  unsigned Size = VT.getSizeInBits();
4400
4401  SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
4402  SDValue Vec;
4403  if (Size == 256) {
4404    if (HasInt256) { // AVX2
4405      SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4406      Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops, 8);
4407    } else { // AVX
4408      Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4409      Vec = Concat128BitVectors(Vec, Vec, MVT::v8i32, 8, DAG, dl);
4410    }
4411  } else if (Size == 128) {
4412    Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4413  } else
4414    llvm_unreachable("Unexpected vector type");
4415
4416  return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4417}
4418
4419/// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
4420/// that point to V2 points to its first element.
4421static void NormalizeMask(SmallVectorImpl<int> &Mask, unsigned NumElems) {
4422  for (unsigned i = 0; i != NumElems; ++i) {
4423    if (Mask[i] > (int)NumElems) {
4424      Mask[i] = NumElems;
4425    }
4426  }
4427}
4428
4429/// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
4430/// operation of specified width.
4431static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
4432                       SDValue V2) {
4433  unsigned NumElems = VT.getVectorNumElements();
4434  SmallVector<int, 8> Mask;
4435  Mask.push_back(NumElems);
4436  for (unsigned i = 1; i != NumElems; ++i)
4437    Mask.push_back(i);
4438  return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4439}
4440
4441/// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
4442static SDValue getUnpackl(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
4443                          SDValue V2) {
4444  unsigned NumElems = VT.getVectorNumElements();
4445  SmallVector<int, 8> Mask;
4446  for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
4447    Mask.push_back(i);
4448    Mask.push_back(i + NumElems);
4449  }
4450  return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4451}
4452
4453/// getUnpackh - Returns a vector_shuffle node for an unpackh operation.
4454static SDValue getUnpackh(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
4455                          SDValue V2) {
4456  unsigned NumElems = VT.getVectorNumElements();
4457  SmallVector<int, 8> Mask;
4458  for (unsigned i = 0, Half = NumElems/2; i != Half; ++i) {
4459    Mask.push_back(i + Half);
4460    Mask.push_back(i + NumElems + Half);
4461  }
4462  return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4463}
4464
4465// PromoteSplati8i16 - All i16 and i8 vector types can't be used directly by
4466// a generic shuffle instruction because the target has no such instructions.
4467// Generate shuffles which repeat i16 and i8 several times until they can be
4468// represented by v4f32 and then be manipulated by target suported shuffles.
4469static SDValue PromoteSplati8i16(SDValue V, SelectionDAG &DAG, int &EltNo) {
4470  EVT VT = V.getValueType();
4471  int NumElems = VT.getVectorNumElements();
4472  DebugLoc dl = V.getDebugLoc();
4473
4474  while (NumElems > 4) {
4475    if (EltNo < NumElems/2) {
4476      V = getUnpackl(DAG, dl, VT, V, V);
4477    } else {
4478      V = getUnpackh(DAG, dl, VT, V, V);
4479      EltNo -= NumElems/2;
4480    }
4481    NumElems >>= 1;
4482  }
4483  return V;
4484}
4485
4486/// getLegalSplat - Generate a legal splat with supported x86 shuffles
4487static SDValue getLegalSplat(SelectionDAG &DAG, SDValue V, int EltNo) {
4488  EVT VT = V.getValueType();
4489  DebugLoc dl = V.getDebugLoc();
4490  unsigned Size = VT.getSizeInBits();
4491
4492  if (Size == 128) {
4493    V = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V);
4494    int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo };
4495    V = DAG.getVectorShuffle(MVT::v4f32, dl, V, DAG.getUNDEF(MVT::v4f32),
4496                             &SplatMask[0]);
4497  } else if (Size == 256) {
4498    // To use VPERMILPS to splat scalars, the second half of indicies must
4499    // refer to the higher part, which is a duplication of the lower one,
4500    // because VPERMILPS can only handle in-lane permutations.
4501    int SplatMask[8] = { EltNo, EltNo, EltNo, EltNo,
4502                         EltNo+4, EltNo+4, EltNo+4, EltNo+4 };
4503
4504    V = DAG.getNode(ISD::BITCAST, dl, MVT::v8f32, V);
4505    V = DAG.getVectorShuffle(MVT::v8f32, dl, V, DAG.getUNDEF(MVT::v8f32),
4506                             &SplatMask[0]);
4507  } else
4508    llvm_unreachable("Vector size not supported");
4509
4510  return DAG.getNode(ISD::BITCAST, dl, VT, V);
4511}
4512
4513/// PromoteSplat - Splat is promoted to target supported vector shuffles.
4514static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG) {
4515  EVT SrcVT = SV->getValueType(0);
4516  SDValue V1 = SV->getOperand(0);
4517  DebugLoc dl = SV->getDebugLoc();
4518
4519  int EltNo = SV->getSplatIndex();
4520  int NumElems = SrcVT.getVectorNumElements();
4521  unsigned Size = SrcVT.getSizeInBits();
4522
4523  assert(((Size == 128 && NumElems > 4) || Size == 256) &&
4524          "Unknown how to promote splat for type");
4525
4526  // Extract the 128-bit part containing the splat element and update
4527  // the splat element index when it refers to the higher register.
4528  if (Size == 256) {
4529    V1 = Extract128BitVector(V1, EltNo, DAG, dl);
4530    if (EltNo >= NumElems/2)
4531      EltNo -= NumElems/2;
4532  }
4533
4534  // All i16 and i8 vector types can't be used directly by a generic shuffle
4535  // instruction because the target has no such instruction. Generate shuffles
4536  // which repeat i16 and i8 several times until they fit in i32, and then can
4537  // be manipulated by target suported shuffles.
4538  EVT EltVT = SrcVT.getVectorElementType();
4539  if (EltVT == MVT::i8 || EltVT == MVT::i16)
4540    V1 = PromoteSplati8i16(V1, DAG, EltNo);
4541
4542  // Recreate the 256-bit vector and place the same 128-bit vector
4543  // into the low and high part. This is necessary because we want
4544  // to use VPERM* to shuffle the vectors
4545  if (Size == 256) {
4546    V1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, SrcVT, V1, V1);
4547  }
4548
4549  return getLegalSplat(DAG, V1, EltNo);
4550}
4551
4552/// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
4553/// vector of zero or undef vector.  This produces a shuffle where the low
4554/// element of V2 is swizzled into the zero/undef vector, landing at element
4555/// Idx.  This produces a shuffle mask like 4,1,2,3 (idx=0) or  0,1,2,4 (idx=3).
4556static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
4557                                           bool IsZero,
4558                                           const X86Subtarget *Subtarget,
4559                                           SelectionDAG &DAG) {
4560  EVT VT = V2.getValueType();
4561  SDValue V1 = IsZero
4562    ? getZeroVector(VT, Subtarget, DAG, V2.getDebugLoc()) : DAG.getUNDEF(VT);
4563  unsigned NumElems = VT.getVectorNumElements();
4564  SmallVector<int, 16> MaskVec;
4565  for (unsigned i = 0; i != NumElems; ++i)
4566    // If this is the insertion idx, put the low elt of V2 here.
4567    MaskVec.push_back(i == Idx ? NumElems : i);
4568  return DAG.getVectorShuffle(VT, V2.getDebugLoc(), V1, V2, &MaskVec[0]);
4569}
4570
4571/// getTargetShuffleMask - Calculates the shuffle mask corresponding to the
4572/// target specific opcode. Returns true if the Mask could be calculated.
4573/// Sets IsUnary to true if only uses one source.
4574static bool getTargetShuffleMask(SDNode *N, MVT VT,
4575                                 SmallVectorImpl<int> &Mask, bool &IsUnary) {
4576  unsigned NumElems = VT.getVectorNumElements();
4577  SDValue ImmN;
4578
4579  IsUnary = false;
4580  switch(N->getOpcode()) {
4581  case X86ISD::SHUFP:
4582    ImmN = N->getOperand(N->getNumOperands()-1);
4583    DecodeSHUFPMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4584    break;
4585  case X86ISD::UNPCKH:
4586    DecodeUNPCKHMask(VT, Mask);
4587    break;
4588  case X86ISD::UNPCKL:
4589    DecodeUNPCKLMask(VT, Mask);
4590    break;
4591  case X86ISD::MOVHLPS:
4592    DecodeMOVHLPSMask(NumElems, Mask);
4593    break;
4594  case X86ISD::MOVLHPS:
4595    DecodeMOVLHPSMask(NumElems, Mask);
4596    break;
4597  case X86ISD::PSHUFD:
4598  case X86ISD::VPERMILP:
4599    ImmN = N->getOperand(N->getNumOperands()-1);
4600    DecodePSHUFMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4601    IsUnary = true;
4602    break;
4603  case X86ISD::PSHUFHW:
4604    ImmN = N->getOperand(N->getNumOperands()-1);
4605    DecodePSHUFHWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4606    IsUnary = true;
4607    break;
4608  case X86ISD::PSHUFLW:
4609    ImmN = N->getOperand(N->getNumOperands()-1);
4610    DecodePSHUFLWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4611    IsUnary = true;
4612    break;
4613  case X86ISD::VPERMI:
4614    ImmN = N->getOperand(N->getNumOperands()-1);
4615    DecodeVPERMMask(cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4616    IsUnary = true;
4617    break;
4618  case X86ISD::MOVSS:
4619  case X86ISD::MOVSD: {
4620    // The index 0 always comes from the first element of the second source,
4621    // this is why MOVSS and MOVSD are used in the first place. The other
4622    // elements come from the other positions of the first source vector
4623    Mask.push_back(NumElems);
4624    for (unsigned i = 1; i != NumElems; ++i) {
4625      Mask.push_back(i);
4626    }
4627    break;
4628  }
4629  case X86ISD::VPERM2X128:
4630    ImmN = N->getOperand(N->getNumOperands()-1);
4631    DecodeVPERM2X128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4632    if (Mask.empty()) return false;
4633    break;
4634  case X86ISD::MOVDDUP:
4635  case X86ISD::MOVLHPD:
4636  case X86ISD::MOVLPD:
4637  case X86ISD::MOVLPS:
4638  case X86ISD::MOVSHDUP:
4639  case X86ISD::MOVSLDUP:
4640  case X86ISD::PALIGN:
4641    // Not yet implemented
4642    return false;
4643  default: llvm_unreachable("unknown target shuffle node");
4644  }
4645
4646  return true;
4647}
4648
4649/// getShuffleScalarElt - Returns the scalar element that will make up the ith
4650/// element of the result of the vector shuffle.
4651static SDValue getShuffleScalarElt(SDNode *N, unsigned Index, SelectionDAG &DAG,
4652                                   unsigned Depth) {
4653  if (Depth == 6)
4654    return SDValue();  // Limit search depth.
4655
4656  SDValue V = SDValue(N, 0);
4657  EVT VT = V.getValueType();
4658  unsigned Opcode = V.getOpcode();
4659
4660  // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
4661  if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
4662    int Elt = SV->getMaskElt(Index);
4663
4664    if (Elt < 0)
4665      return DAG.getUNDEF(VT.getVectorElementType());
4666
4667    unsigned NumElems = VT.getVectorNumElements();
4668    SDValue NewV = (Elt < (int)NumElems) ? SV->getOperand(0)
4669                                         : SV->getOperand(1);
4670    return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG, Depth+1);
4671  }
4672
4673  // Recurse into target specific vector shuffles to find scalars.
4674  if (isTargetShuffle(Opcode)) {
4675    MVT ShufVT = V.getValueType().getSimpleVT();
4676    unsigned NumElems = ShufVT.getVectorNumElements();
4677    SmallVector<int, 16> ShuffleMask;
4678    bool IsUnary;
4679
4680    if (!getTargetShuffleMask(N, ShufVT, ShuffleMask, IsUnary))
4681      return SDValue();
4682
4683    int Elt = ShuffleMask[Index];
4684    if (Elt < 0)
4685      return DAG.getUNDEF(ShufVT.getVectorElementType());
4686
4687    SDValue NewV = (Elt < (int)NumElems) ? N->getOperand(0)
4688                                         : N->getOperand(1);
4689    return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG,
4690                               Depth+1);
4691  }
4692
4693  // Actual nodes that may contain scalar elements
4694  if (Opcode == ISD::BITCAST) {
4695    V = V.getOperand(0);
4696    EVT SrcVT = V.getValueType();
4697    unsigned NumElems = VT.getVectorNumElements();
4698
4699    if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
4700      return SDValue();
4701  }
4702
4703  if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
4704    return (Index == 0) ? V.getOperand(0)
4705                        : DAG.getUNDEF(VT.getVectorElementType());
4706
4707  if (V.getOpcode() == ISD::BUILD_VECTOR)
4708    return V.getOperand(Index);
4709
4710  return SDValue();
4711}
4712
4713/// getNumOfConsecutiveZeros - Return the number of elements of a vector
4714/// shuffle operation which come from a consecutively from a zero. The
4715/// search can start in two different directions, from left or right.
4716static
4717unsigned getNumOfConsecutiveZeros(ShuffleVectorSDNode *SVOp, unsigned NumElems,
4718                                  bool ZerosFromLeft, SelectionDAG &DAG) {
4719  unsigned i;
4720  for (i = 0; i != NumElems; ++i) {
4721    unsigned Index = ZerosFromLeft ? i : NumElems-i-1;
4722    SDValue Elt = getShuffleScalarElt(SVOp, Index, DAG, 0);
4723    if (!(Elt.getNode() &&
4724         (Elt.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elt))))
4725      break;
4726  }
4727
4728  return i;
4729}
4730
4731/// isShuffleMaskConsecutive - Check if the shuffle mask indicies [MaskI, MaskE)
4732/// correspond consecutively to elements from one of the vector operands,
4733/// starting from its index OpIdx. Also tell OpNum which source vector operand.
4734static
4735bool isShuffleMaskConsecutive(ShuffleVectorSDNode *SVOp,
4736                              unsigned MaskI, unsigned MaskE, unsigned OpIdx,
4737                              unsigned NumElems, unsigned &OpNum) {
4738  bool SeenV1 = false;
4739  bool SeenV2 = false;
4740
4741  for (unsigned i = MaskI; i != MaskE; ++i, ++OpIdx) {
4742    int Idx = SVOp->getMaskElt(i);
4743    // Ignore undef indicies
4744    if (Idx < 0)
4745      continue;
4746
4747    if (Idx < (int)NumElems)
4748      SeenV1 = true;
4749    else
4750      SeenV2 = true;
4751
4752    // Only accept consecutive elements from the same vector
4753    if ((Idx % NumElems != OpIdx) || (SeenV1 && SeenV2))
4754      return false;
4755  }
4756
4757  OpNum = SeenV1 ? 0 : 1;
4758  return true;
4759}
4760
4761/// isVectorShiftRight - Returns true if the shuffle can be implemented as a
4762/// logical left shift of a vector.
4763static bool isVectorShiftRight(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4764                               bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4765  unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
4766  unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems,
4767              false /* check zeros from right */, DAG);
4768  unsigned OpSrc;
4769
4770  if (!NumZeros)
4771    return false;
4772
4773  // Considering the elements in the mask that are not consecutive zeros,
4774  // check if they consecutively come from only one of the source vectors.
4775  //
4776  //               V1 = {X, A, B, C}     0
4777  //                         \  \  \    /
4778  //   vector_shuffle V1, V2 <1, 2, 3, X>
4779  //
4780  if (!isShuffleMaskConsecutive(SVOp,
4781            0,                   // Mask Start Index
4782            NumElems-NumZeros,   // Mask End Index(exclusive)
4783            NumZeros,            // Where to start looking in the src vector
4784            NumElems,            // Number of elements in vector
4785            OpSrc))              // Which source operand ?
4786    return false;
4787
4788  isLeft = false;
4789  ShAmt = NumZeros;
4790  ShVal = SVOp->getOperand(OpSrc);
4791  return true;
4792}
4793
4794/// isVectorShiftLeft - Returns true if the shuffle can be implemented as a
4795/// logical left shift of a vector.
4796static bool isVectorShiftLeft(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4797                              bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4798  unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
4799  unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems,
4800              true /* check zeros from left */, DAG);
4801  unsigned OpSrc;
4802
4803  if (!NumZeros)
4804    return false;
4805
4806  // Considering the elements in the mask that are not consecutive zeros,
4807  // check if they consecutively come from only one of the source vectors.
4808  //
4809  //                           0    { A, B, X, X } = V2
4810  //                          / \    /  /
4811  //   vector_shuffle V1, V2 <X, X, 4, 5>
4812  //
4813  if (!isShuffleMaskConsecutive(SVOp,
4814            NumZeros,     // Mask Start Index
4815            NumElems,     // Mask End Index(exclusive)
4816            0,            // Where to start looking in the src vector
4817            NumElems,     // Number of elements in vector
4818            OpSrc))       // Which source operand ?
4819    return false;
4820
4821  isLeft = true;
4822  ShAmt = NumZeros;
4823  ShVal = SVOp->getOperand(OpSrc);
4824  return true;
4825}
4826
4827/// isVectorShift - Returns true if the shuffle can be implemented as a
4828/// logical left or right shift of a vector.
4829static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4830                          bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4831  // Although the logic below support any bitwidth size, there are no
4832  // shift instructions which handle more than 128-bit vectors.
4833  if (!SVOp->getValueType(0).is128BitVector())
4834    return false;
4835
4836  if (isVectorShiftLeft(SVOp, DAG, isLeft, ShVal, ShAmt) ||
4837      isVectorShiftRight(SVOp, DAG, isLeft, ShVal, ShAmt))
4838    return true;
4839
4840  return false;
4841}
4842
4843/// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
4844///
4845static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
4846                                       unsigned NumNonZero, unsigned NumZero,
4847                                       SelectionDAG &DAG,
4848                                       const X86Subtarget* Subtarget,
4849                                       const TargetLowering &TLI) {
4850  if (NumNonZero > 8)
4851    return SDValue();
4852
4853  DebugLoc dl = Op.getDebugLoc();
4854  SDValue V(0, 0);
4855  bool First = true;
4856  for (unsigned i = 0; i < 16; ++i) {
4857    bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
4858    if (ThisIsNonZero && First) {
4859      if (NumZero)
4860        V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
4861      else
4862        V = DAG.getUNDEF(MVT::v8i16);
4863      First = false;
4864    }
4865
4866    if ((i & 1) != 0) {
4867      SDValue ThisElt(0, 0), LastElt(0, 0);
4868      bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
4869      if (LastIsNonZero) {
4870        LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
4871                              MVT::i16, Op.getOperand(i-1));
4872      }
4873      if (ThisIsNonZero) {
4874        ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
4875        ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
4876                              ThisElt, DAG.getConstant(8, MVT::i8));
4877        if (LastIsNonZero)
4878          ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
4879      } else
4880        ThisElt = LastElt;
4881
4882      if (ThisElt.getNode())
4883        V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
4884                        DAG.getIntPtrConstant(i/2));
4885    }
4886  }
4887
4888  return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V);
4889}
4890
4891/// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
4892///
4893static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
4894                                     unsigned NumNonZero, unsigned NumZero,
4895                                     SelectionDAG &DAG,
4896                                     const X86Subtarget* Subtarget,
4897                                     const TargetLowering &TLI) {
4898  if (NumNonZero > 4)
4899    return SDValue();
4900
4901  DebugLoc dl = Op.getDebugLoc();
4902  SDValue V(0, 0);
4903  bool First = true;
4904  for (unsigned i = 0; i < 8; ++i) {
4905    bool isNonZero = (NonZeros & (1 << i)) != 0;
4906    if (isNonZero) {
4907      if (First) {
4908        if (NumZero)
4909          V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
4910        else
4911          V = DAG.getUNDEF(MVT::v8i16);
4912        First = false;
4913      }
4914      V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
4915                      MVT::v8i16, V, Op.getOperand(i),
4916                      DAG.getIntPtrConstant(i));
4917    }
4918  }
4919
4920  return V;
4921}
4922
4923/// getVShift - Return a vector logical shift node.
4924///
4925static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
4926                         unsigned NumBits, SelectionDAG &DAG,
4927                         const TargetLowering &TLI, DebugLoc dl) {
4928  assert(VT.is128BitVector() && "Unknown type for VShift");
4929  EVT ShVT = MVT::v2i64;
4930  unsigned Opc = isLeft ? X86ISD::VSHLDQ : X86ISD::VSRLDQ;
4931  SrcOp = DAG.getNode(ISD::BITCAST, dl, ShVT, SrcOp);
4932  return DAG.getNode(ISD::BITCAST, dl, VT,
4933                     DAG.getNode(Opc, dl, ShVT, SrcOp,
4934                             DAG.getConstant(NumBits,
4935                                  TLI.getShiftAmountTy(SrcOp.getValueType()))));
4936}
4937
4938SDValue
4939X86TargetLowering::LowerAsSplatVectorLoad(SDValue SrcOp, EVT VT, DebugLoc dl,
4940                                          SelectionDAG &DAG) const {
4941
4942  // Check if the scalar load can be widened into a vector load. And if
4943  // the address is "base + cst" see if the cst can be "absorbed" into
4944  // the shuffle mask.
4945  if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
4946    SDValue Ptr = LD->getBasePtr();
4947    if (!ISD::isNormalLoad(LD) || LD->isVolatile())
4948      return SDValue();
4949    EVT PVT = LD->getValueType(0);
4950    if (PVT != MVT::i32 && PVT != MVT::f32)
4951      return SDValue();
4952
4953    int FI = -1;
4954    int64_t Offset = 0;
4955    if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
4956      FI = FINode->getIndex();
4957      Offset = 0;
4958    } else if (DAG.isBaseWithConstantOffset(Ptr) &&
4959               isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
4960      FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
4961      Offset = Ptr.getConstantOperandVal(1);
4962      Ptr = Ptr.getOperand(0);
4963    } else {
4964      return SDValue();
4965    }
4966
4967    // FIXME: 256-bit vector instructions don't require a strict alignment,
4968    // improve this code to support it better.
4969    unsigned RequiredAlign = VT.getSizeInBits()/8;
4970    SDValue Chain = LD->getChain();
4971    // Make sure the stack object alignment is at least 16 or 32.
4972    MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
4973    if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
4974      if (MFI->isFixedObjectIndex(FI)) {
4975        // Can't change the alignment. FIXME: It's possible to compute
4976        // the exact stack offset and reference FI + adjust offset instead.
4977        // If someone *really* cares about this. That's the way to implement it.
4978        return SDValue();
4979      } else {
4980        MFI->setObjectAlignment(FI, RequiredAlign);
4981      }
4982    }
4983
4984    // (Offset % 16 or 32) must be multiple of 4. Then address is then
4985    // Ptr + (Offset & ~15).
4986    if (Offset < 0)
4987      return SDValue();
4988    if ((Offset % RequiredAlign) & 3)
4989      return SDValue();
4990    int64_t StartOffset = Offset & ~(RequiredAlign-1);
4991    if (StartOffset)
4992      Ptr = DAG.getNode(ISD::ADD, Ptr.getDebugLoc(), Ptr.getValueType(),
4993                        Ptr,DAG.getConstant(StartOffset, Ptr.getValueType()));
4994
4995    int EltNo = (Offset - StartOffset) >> 2;
4996    unsigned NumElems = VT.getVectorNumElements();
4997
4998    EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
4999    SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
5000                             LD->getPointerInfo().getWithOffset(StartOffset),
5001                             false, false, false, 0);
5002
5003    SmallVector<int, 8> Mask;
5004    for (unsigned i = 0; i != NumElems; ++i)
5005      Mask.push_back(EltNo);
5006
5007    return DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &Mask[0]);
5008  }
5009
5010  return SDValue();
5011}
5012
5013/// EltsFromConsecutiveLoads - Given the initializing elements 'Elts' of a
5014/// vector of type 'VT', see if the elements can be replaced by a single large
5015/// load which has the same value as a build_vector whose operands are 'elts'.
5016///
5017/// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
5018///
5019/// FIXME: we'd also like to handle the case where the last elements are zero
5020/// rather than undef via VZEXT_LOAD, but we do not detect that case today.
5021/// There's even a handy isZeroNode for that purpose.
5022static SDValue EltsFromConsecutiveLoads(EVT VT, SmallVectorImpl<SDValue> &Elts,
5023                                        DebugLoc &DL, SelectionDAG &DAG) {
5024  EVT EltVT = VT.getVectorElementType();
5025  unsigned NumElems = Elts.size();
5026
5027  LoadSDNode *LDBase = NULL;
5028  unsigned LastLoadedElt = -1U;
5029
5030  // For each element in the initializer, see if we've found a load or an undef.
5031  // If we don't find an initial load element, or later load elements are
5032  // non-consecutive, bail out.
5033  for (unsigned i = 0; i < NumElems; ++i) {
5034    SDValue Elt = Elts[i];
5035
5036    if (!Elt.getNode() ||
5037        (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
5038      return SDValue();
5039    if (!LDBase) {
5040      if (Elt.getNode()->getOpcode() == ISD::UNDEF)
5041        return SDValue();
5042      LDBase = cast<LoadSDNode>(Elt.getNode());
5043      LastLoadedElt = i;
5044      continue;
5045    }
5046    if (Elt.getOpcode() == ISD::UNDEF)
5047      continue;
5048
5049    LoadSDNode *LD = cast<LoadSDNode>(Elt);
5050    if (!DAG.isConsecutiveLoad(LD, LDBase, EltVT.getSizeInBits()/8, i))
5051      return SDValue();
5052    LastLoadedElt = i;
5053  }
5054
5055  // If we have found an entire vector of loads and undefs, then return a large
5056  // load of the entire vector width starting at the base pointer.  If we found
5057  // consecutive loads for the low half, generate a vzext_load node.
5058  if (LastLoadedElt == NumElems - 1) {
5059    if (DAG.InferPtrAlignment(LDBase->getBasePtr()) >= 16)
5060      return DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5061                         LDBase->getPointerInfo(),
5062                         LDBase->isVolatile(), LDBase->isNonTemporal(),
5063                         LDBase->isInvariant(), 0);
5064    return DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5065                       LDBase->getPointerInfo(),
5066                       LDBase->isVolatile(), LDBase->isNonTemporal(),
5067                       LDBase->isInvariant(), LDBase->getAlignment());
5068  }
5069  if (NumElems == 4 && LastLoadedElt == 1 &&
5070      DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) {
5071    SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
5072    SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
5073    SDValue ResNode =
5074        DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops, 2, MVT::i64,
5075                                LDBase->getPointerInfo(),
5076                                LDBase->getAlignment(),
5077                                false/*isVolatile*/, true/*ReadMem*/,
5078                                false/*WriteMem*/);
5079
5080    // Make sure the newly-created LOAD is in the same position as LDBase in
5081    // terms of dependency. We create a TokenFactor for LDBase and ResNode, and
5082    // update uses of LDBase's output chain to use the TokenFactor.
5083    if (LDBase->hasAnyUseOfValue(1)) {
5084      SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5085                             SDValue(LDBase, 1), SDValue(ResNode.getNode(), 1));
5086      DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5087      DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5088                             SDValue(ResNode.getNode(), 1));
5089    }
5090
5091    return DAG.getNode(ISD::BITCAST, DL, VT, ResNode);
5092  }
5093  return SDValue();
5094}
5095
5096/// LowerVectorBroadcast - Attempt to use the vbroadcast instruction
5097/// to generate a splat value for the following cases:
5098/// 1. A splat BUILD_VECTOR which uses a single scalar load, or a constant.
5099/// 2. A splat shuffle which uses a scalar_to_vector node which comes from
5100/// a scalar load, or a constant.
5101/// The VBROADCAST node is returned when a pattern is found,
5102/// or SDValue() otherwise.
5103SDValue
5104X86TargetLowering::LowerVectorBroadcast(SDValue Op, SelectionDAG &DAG) const {
5105  if (!Subtarget->hasFp256())
5106    return SDValue();
5107
5108  EVT VT = Op.getValueType();
5109  DebugLoc dl = Op.getDebugLoc();
5110
5111  assert((VT.is128BitVector() || VT.is256BitVector()) &&
5112         "Unsupported vector type for broadcast.");
5113
5114  SDValue Ld;
5115  bool ConstSplatVal;
5116
5117  switch (Op.getOpcode()) {
5118    default:
5119      // Unknown pattern found.
5120      return SDValue();
5121
5122    case ISD::BUILD_VECTOR: {
5123      // The BUILD_VECTOR node must be a splat.
5124      if (!isSplatVector(Op.getNode()))
5125        return SDValue();
5126
5127      Ld = Op.getOperand(0);
5128      ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5129                     Ld.getOpcode() == ISD::ConstantFP);
5130
5131      // The suspected load node has several users. Make sure that all
5132      // of its users are from the BUILD_VECTOR node.
5133      // Constants may have multiple users.
5134      if (!ConstSplatVal && !Ld->hasNUsesOfValue(VT.getVectorNumElements(), 0))
5135        return SDValue();
5136      break;
5137    }
5138
5139    case ISD::VECTOR_SHUFFLE: {
5140      ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5141
5142      // Shuffles must have a splat mask where the first element is
5143      // broadcasted.
5144      if ((!SVOp->isSplat()) || SVOp->getMaskElt(0) != 0)
5145        return SDValue();
5146
5147      SDValue Sc = Op.getOperand(0);
5148      if (Sc.getOpcode() != ISD::SCALAR_TO_VECTOR &&
5149          Sc.getOpcode() != ISD::BUILD_VECTOR) {
5150
5151        if (!Subtarget->hasInt256())
5152          return SDValue();
5153
5154        // Use the register form of the broadcast instruction available on AVX2.
5155        if (VT.is256BitVector())
5156          Sc = Extract128BitVector(Sc, 0, DAG, dl);
5157        return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Sc);
5158      }
5159
5160      Ld = Sc.getOperand(0);
5161      ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5162                       Ld.getOpcode() == ISD::ConstantFP);
5163
5164      // The scalar_to_vector node and the suspected
5165      // load node must have exactly one user.
5166      // Constants may have multiple users.
5167      if (!ConstSplatVal && (!Sc.hasOneUse() || !Ld.hasOneUse()))
5168        return SDValue();
5169      break;
5170    }
5171  }
5172
5173  bool Is256 = VT.is256BitVector();
5174
5175  // Handle the broadcasting a single constant scalar from the constant pool
5176  // into a vector. On Sandybridge it is still better to load a constant vector
5177  // from the constant pool and not to broadcast it from a scalar.
5178  if (ConstSplatVal && Subtarget->hasInt256()) {
5179    EVT CVT = Ld.getValueType();
5180    assert(!CVT.isVector() && "Must not broadcast a vector type");
5181    unsigned ScalarSize = CVT.getSizeInBits();
5182
5183    if (ScalarSize == 32 || (Is256 && ScalarSize == 64)) {
5184      const Constant *C = 0;
5185      if (ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Ld))
5186        C = CI->getConstantIntValue();
5187      else if (ConstantFPSDNode *CF = dyn_cast<ConstantFPSDNode>(Ld))
5188        C = CF->getConstantFPValue();
5189
5190      assert(C && "Invalid constant type");
5191
5192      SDValue CP = DAG.getConstantPool(C, getPointerTy());
5193      unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
5194      Ld = DAG.getLoad(CVT, dl, DAG.getEntryNode(), CP,
5195                       MachinePointerInfo::getConstantPool(),
5196                       false, false, false, Alignment);
5197
5198      return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5199    }
5200  }
5201
5202  bool IsLoad = ISD::isNormalLoad(Ld.getNode());
5203  unsigned ScalarSize = Ld.getValueType().getSizeInBits();
5204
5205  // Handle AVX2 in-register broadcasts.
5206  if (!IsLoad && Subtarget->hasInt256() &&
5207      (ScalarSize == 32 || (Is256 && ScalarSize == 64)))
5208    return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5209
5210  // The scalar source must be a normal load.
5211  if (!IsLoad)
5212    return SDValue();
5213
5214  if (ScalarSize == 32 || (Is256 && ScalarSize == 64))
5215    return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5216
5217  // The integer check is needed for the 64-bit into 128-bit so it doesn't match
5218  // double since there is no vbroadcastsd xmm
5219  if (Subtarget->hasInt256() && Ld.getValueType().isInteger()) {
5220    if (ScalarSize == 8 || ScalarSize == 16 || ScalarSize == 64)
5221      return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5222  }
5223
5224  // Unsupported broadcast.
5225  return SDValue();
5226}
5227
5228SDValue
5229X86TargetLowering::buildFromShuffleMostly(SDValue Op, SelectionDAG &DAG) const {
5230  EVT VT = Op.getValueType();
5231
5232  // Skip if insert_vec_elt is not supported.
5233  if (!isOperationLegalOrCustom(ISD::INSERT_VECTOR_ELT, VT))
5234    return SDValue();
5235
5236  DebugLoc DL = Op.getDebugLoc();
5237  unsigned NumElems = Op.getNumOperands();
5238
5239  SDValue VecIn1;
5240  SDValue VecIn2;
5241  SmallVector<unsigned, 4> InsertIndices;
5242  SmallVector<int, 8> Mask(NumElems, -1);
5243
5244  for (unsigned i = 0; i != NumElems; ++i) {
5245    unsigned Opc = Op.getOperand(i).getOpcode();
5246
5247    if (Opc == ISD::UNDEF)
5248      continue;
5249
5250    if (Opc != ISD::EXTRACT_VECTOR_ELT) {
5251      // Quit if more than 1 elements need inserting.
5252      if (InsertIndices.size() > 1)
5253        return SDValue();
5254
5255      InsertIndices.push_back(i);
5256      continue;
5257    }
5258
5259    SDValue ExtractedFromVec = Op.getOperand(i).getOperand(0);
5260    SDValue ExtIdx = Op.getOperand(i).getOperand(1);
5261
5262    // Quit if extracted from vector of different type.
5263    if (ExtractedFromVec.getValueType() != VT)
5264      return SDValue();
5265
5266    // Quit if non-constant index.
5267    if (!isa<ConstantSDNode>(ExtIdx))
5268      return SDValue();
5269
5270    if (VecIn1.getNode() == 0)
5271      VecIn1 = ExtractedFromVec;
5272    else if (VecIn1 != ExtractedFromVec) {
5273      if (VecIn2.getNode() == 0)
5274        VecIn2 = ExtractedFromVec;
5275      else if (VecIn2 != ExtractedFromVec)
5276        // Quit if more than 2 vectors to shuffle
5277        return SDValue();
5278    }
5279
5280    unsigned Idx = cast<ConstantSDNode>(ExtIdx)->getZExtValue();
5281
5282    if (ExtractedFromVec == VecIn1)
5283      Mask[i] = Idx;
5284    else if (ExtractedFromVec == VecIn2)
5285      Mask[i] = Idx + NumElems;
5286  }
5287
5288  if (VecIn1.getNode() == 0)
5289    return SDValue();
5290
5291  VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
5292  SDValue NV = DAG.getVectorShuffle(VT, DL, VecIn1, VecIn2, &Mask[0]);
5293  for (unsigned i = 0, e = InsertIndices.size(); i != e; ++i) {
5294    unsigned Idx = InsertIndices[i];
5295    NV = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, NV, Op.getOperand(Idx),
5296                     DAG.getIntPtrConstant(Idx));
5297  }
5298
5299  return NV;
5300}
5301
5302SDValue
5303X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
5304  DebugLoc dl = Op.getDebugLoc();
5305
5306  EVT VT = Op.getValueType();
5307  EVT ExtVT = VT.getVectorElementType();
5308  unsigned NumElems = Op.getNumOperands();
5309
5310  // Vectors containing all zeros can be matched by pxor and xorps later
5311  if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5312    // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
5313    // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
5314    if (VT == MVT::v4i32 || VT == MVT::v8i32)
5315      return Op;
5316
5317    return getZeroVector(VT, Subtarget, DAG, dl);
5318  }
5319
5320  // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
5321  // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use
5322  // vpcmpeqd on 256-bit vectors.
5323  if (ISD::isBuildVectorAllOnes(Op.getNode())) {
5324    if (VT == MVT::v4i32 || (VT == MVT::v8i32 && Subtarget->hasInt256()))
5325      return Op;
5326
5327    return getOnesVector(VT, Subtarget->hasInt256(), DAG, dl);
5328  }
5329
5330  SDValue Broadcast = LowerVectorBroadcast(Op, DAG);
5331  if (Broadcast.getNode())
5332    return Broadcast;
5333
5334  unsigned EVTBits = ExtVT.getSizeInBits();
5335
5336  unsigned NumZero  = 0;
5337  unsigned NumNonZero = 0;
5338  unsigned NonZeros = 0;
5339  bool IsAllConstants = true;
5340  SmallSet<SDValue, 8> Values;
5341  for (unsigned i = 0; i < NumElems; ++i) {
5342    SDValue Elt = Op.getOperand(i);
5343    if (Elt.getOpcode() == ISD::UNDEF)
5344      continue;
5345    Values.insert(Elt);
5346    if (Elt.getOpcode() != ISD::Constant &&
5347        Elt.getOpcode() != ISD::ConstantFP)
5348      IsAllConstants = false;
5349    if (X86::isZeroNode(Elt))
5350      NumZero++;
5351    else {
5352      NonZeros |= (1 << i);
5353      NumNonZero++;
5354    }
5355  }
5356
5357  // All undef vector. Return an UNDEF.  All zero vectors were handled above.
5358  if (NumNonZero == 0)
5359    return DAG.getUNDEF(VT);
5360
5361  // Special case for single non-zero, non-undef, element.
5362  if (NumNonZero == 1) {
5363    unsigned Idx = CountTrailingZeros_32(NonZeros);
5364    SDValue Item = Op.getOperand(Idx);
5365
5366    // If this is an insertion of an i64 value on x86-32, and if the top bits of
5367    // the value are obviously zero, truncate the value to i32 and do the
5368    // insertion that way.  Only do this if the value is non-constant or if the
5369    // value is a constant being inserted into element 0.  It is cheaper to do
5370    // a constant pool load than it is to do a movd + shuffle.
5371    if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
5372        (!IsAllConstants || Idx == 0)) {
5373      if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
5374        // Handle SSE only.
5375        assert(VT == MVT::v2i64 && "Expected an SSE value type!");
5376        EVT VecVT = MVT::v4i32;
5377        unsigned VecElts = 4;
5378
5379        // Truncate the value (which may itself be a constant) to i32, and
5380        // convert it to a vector with movd (S2V+shuffle to zero extend).
5381        Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
5382        Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
5383        Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5384
5385        // Now we have our 32-bit value zero extended in the low element of
5386        // a vector.  If Idx != 0, swizzle it into place.
5387        if (Idx != 0) {
5388          SmallVector<int, 4> Mask;
5389          Mask.push_back(Idx);
5390          for (unsigned i = 1; i != VecElts; ++i)
5391            Mask.push_back(i);
5392          Item = DAG.getVectorShuffle(VecVT, dl, Item, DAG.getUNDEF(VecVT),
5393                                      &Mask[0]);
5394        }
5395        return DAG.getNode(ISD::BITCAST, dl, VT, Item);
5396      }
5397    }
5398
5399    // If we have a constant or non-constant insertion into the low element of
5400    // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
5401    // the rest of the elements.  This will be matched as movd/movq/movss/movsd
5402    // depending on what the source datatype is.
5403    if (Idx == 0) {
5404      if (NumZero == 0)
5405        return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5406
5407      if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
5408          (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
5409        if (VT.is256BitVector()) {
5410          SDValue ZeroVec = getZeroVector(VT, Subtarget, DAG, dl);
5411          return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, ZeroVec,
5412                             Item, DAG.getIntPtrConstant(0));
5413        }
5414        assert(VT.is128BitVector() && "Expected an SSE value type!");
5415        Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5416        // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
5417        return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5418      }
5419
5420      if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
5421        Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
5422        Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
5423        if (VT.is256BitVector()) {
5424          SDValue ZeroVec = getZeroVector(MVT::v8i32, Subtarget, DAG, dl);
5425          Item = Insert128BitVector(ZeroVec, Item, 0, DAG, dl);
5426        } else {
5427          assert(VT.is128BitVector() && "Expected an SSE value type!");
5428          Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5429        }
5430        return DAG.getNode(ISD::BITCAST, dl, VT, Item);
5431      }
5432    }
5433
5434    // Is it a vector logical left shift?
5435    if (NumElems == 2 && Idx == 1 &&
5436        X86::isZeroNode(Op.getOperand(0)) &&
5437        !X86::isZeroNode(Op.getOperand(1))) {
5438      unsigned NumBits = VT.getSizeInBits();
5439      return getVShift(true, VT,
5440                       DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
5441                                   VT, Op.getOperand(1)),
5442                       NumBits/2, DAG, *this, dl);
5443    }
5444
5445    if (IsAllConstants) // Otherwise, it's better to do a constpool load.
5446      return SDValue();
5447
5448    // Otherwise, if this is a vector with i32 or f32 elements, and the element
5449    // is a non-constant being inserted into an element other than the low one,
5450    // we can't use a constant pool load.  Instead, use SCALAR_TO_VECTOR (aka
5451    // movd/movss) to move this into the low element, then shuffle it into
5452    // place.
5453    if (EVTBits == 32) {
5454      Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5455
5456      // Turn it into a shuffle of zero and zero-extended scalar to vector.
5457      Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0, Subtarget, DAG);
5458      SmallVector<int, 8> MaskVec;
5459      for (unsigned i = 0; i != NumElems; ++i)
5460        MaskVec.push_back(i == Idx ? 0 : 1);
5461      return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
5462    }
5463  }
5464
5465  // Splat is obviously ok. Let legalizer expand it to a shuffle.
5466  if (Values.size() == 1) {
5467    if (EVTBits == 32) {
5468      // Instead of a shuffle like this:
5469      // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
5470      // Check if it's possible to issue this instead.
5471      // shuffle (vload ptr)), undef, <1, 1, 1, 1>
5472      unsigned Idx = CountTrailingZeros_32(NonZeros);
5473      SDValue Item = Op.getOperand(Idx);
5474      if (Op.getNode()->isOnlyUserOf(Item.getNode()))
5475        return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
5476    }
5477    return SDValue();
5478  }
5479
5480  // A vector full of immediates; various special cases are already
5481  // handled, so this is best done with a single constant-pool load.
5482  if (IsAllConstants)
5483    return SDValue();
5484
5485  // For AVX-length vectors, build the individual 128-bit pieces and use
5486  // shuffles to put them in place.
5487  if (VT.is256BitVector()) {
5488    SmallVector<SDValue, 32> V;
5489    for (unsigned i = 0; i != NumElems; ++i)
5490      V.push_back(Op.getOperand(i));
5491
5492    EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
5493
5494    // Build both the lower and upper subvector.
5495    SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[0], NumElems/2);
5496    SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[NumElems / 2],
5497                                NumElems/2);
5498
5499    // Recreate the wider vector with the lower and upper part.
5500    return Concat128BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
5501  }
5502
5503  // Let legalizer expand 2-wide build_vectors.
5504  if (EVTBits == 64) {
5505    if (NumNonZero == 1) {
5506      // One half is zero or undef.
5507      unsigned Idx = CountTrailingZeros_32(NonZeros);
5508      SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
5509                                 Op.getOperand(Idx));
5510      return getShuffleVectorZeroOrUndef(V2, Idx, true, Subtarget, DAG);
5511    }
5512    return SDValue();
5513  }
5514
5515  // If element VT is < 32 bits, convert it to inserts into a zero vector.
5516  if (EVTBits == 8 && NumElems == 16) {
5517    SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
5518                                        Subtarget, *this);
5519    if (V.getNode()) return V;
5520  }
5521
5522  if (EVTBits == 16 && NumElems == 8) {
5523    SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
5524                                      Subtarget, *this);
5525    if (V.getNode()) return V;
5526  }
5527
5528  // If element VT is == 32 bits, turn it into a number of shuffles.
5529  SmallVector<SDValue, 8> V(NumElems);
5530  if (NumElems == 4 && NumZero > 0) {
5531    for (unsigned i = 0; i < 4; ++i) {
5532      bool isZero = !(NonZeros & (1 << i));
5533      if (isZero)
5534        V[i] = getZeroVector(VT, Subtarget, DAG, dl);
5535      else
5536        V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
5537    }
5538
5539    for (unsigned i = 0; i < 2; ++i) {
5540      switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
5541        default: break;
5542        case 0:
5543          V[i] = V[i*2];  // Must be a zero vector.
5544          break;
5545        case 1:
5546          V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
5547          break;
5548        case 2:
5549          V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
5550          break;
5551        case 3:
5552          V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
5553          break;
5554      }
5555    }
5556
5557    bool Reverse1 = (NonZeros & 0x3) == 2;
5558    bool Reverse2 = ((NonZeros & (0x3 << 2)) >> 2) == 2;
5559    int MaskVec[] = {
5560      Reverse1 ? 1 : 0,
5561      Reverse1 ? 0 : 1,
5562      static_cast<int>(Reverse2 ? NumElems+1 : NumElems),
5563      static_cast<int>(Reverse2 ? NumElems   : NumElems+1)
5564    };
5565    return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
5566  }
5567
5568  if (Values.size() > 1 && VT.is128BitVector()) {
5569    // Check for a build vector of consecutive loads.
5570    for (unsigned i = 0; i < NumElems; ++i)
5571      V[i] = Op.getOperand(i);
5572
5573    // Check for elements which are consecutive loads.
5574    SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG);
5575    if (LD.getNode())
5576      return LD;
5577
5578    // Check for a build vector from mostly shuffle plus few inserting.
5579    SDValue Sh = buildFromShuffleMostly(Op, DAG);
5580    if (Sh.getNode())
5581      return Sh;
5582
5583    // For SSE 4.1, use insertps to put the high elements into the low element.
5584    if (getSubtarget()->hasSSE41()) {
5585      SDValue Result;
5586      if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
5587        Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
5588      else
5589        Result = DAG.getUNDEF(VT);
5590
5591      for (unsigned i = 1; i < NumElems; ++i) {
5592        if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
5593        Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
5594                             Op.getOperand(i), DAG.getIntPtrConstant(i));
5595      }
5596      return Result;
5597    }
5598
5599    // Otherwise, expand into a number of unpckl*, start by extending each of
5600    // our (non-undef) elements to the full vector width with the element in the
5601    // bottom slot of the vector (which generates no code for SSE).
5602    for (unsigned i = 0; i < NumElems; ++i) {
5603      if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
5604        V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
5605      else
5606        V[i] = DAG.getUNDEF(VT);
5607    }
5608
5609    // Next, we iteratively mix elements, e.g. for v4f32:
5610    //   Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
5611    //         : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
5612    //   Step 2: unpcklps X, Y ==>    <3, 2, 1, 0>
5613    unsigned EltStride = NumElems >> 1;
5614    while (EltStride != 0) {
5615      for (unsigned i = 0; i < EltStride; ++i) {
5616        // If V[i+EltStride] is undef and this is the first round of mixing,
5617        // then it is safe to just drop this shuffle: V[i] is already in the
5618        // right place, the one element (since it's the first round) being
5619        // inserted as undef can be dropped.  This isn't safe for successive
5620        // rounds because they will permute elements within both vectors.
5621        if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
5622            EltStride == NumElems/2)
5623          continue;
5624
5625        V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
5626      }
5627      EltStride >>= 1;
5628    }
5629    return V[0];
5630  }
5631  return SDValue();
5632}
5633
5634// LowerAVXCONCAT_VECTORS - 256-bit AVX can use the vinsertf128 instruction
5635// to create 256-bit vectors from two other 128-bit ones.
5636static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5637  DebugLoc dl = Op.getDebugLoc();
5638  EVT ResVT = Op.getValueType();
5639
5640  assert(ResVT.is256BitVector() && "Value type must be 256-bit wide");
5641
5642  SDValue V1 = Op.getOperand(0);
5643  SDValue V2 = Op.getOperand(1);
5644  unsigned NumElems = ResVT.getVectorNumElements();
5645
5646  return Concat128BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
5647}
5648
5649static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5650  assert(Op.getNumOperands() == 2);
5651
5652  // 256-bit AVX can use the vinsertf128 instruction to create 256-bit vectors
5653  // from two other 128-bit ones.
5654  return LowerAVXCONCAT_VECTORS(Op, DAG);
5655}
5656
5657// Try to lower a shuffle node into a simple blend instruction.
5658static SDValue
5659LowerVECTOR_SHUFFLEtoBlend(ShuffleVectorSDNode *SVOp,
5660                           const X86Subtarget *Subtarget, SelectionDAG &DAG) {
5661  SDValue V1 = SVOp->getOperand(0);
5662  SDValue V2 = SVOp->getOperand(1);
5663  DebugLoc dl = SVOp->getDebugLoc();
5664  EVT VT = SVOp->getValueType(0);
5665  EVT EltVT = VT.getVectorElementType();
5666  unsigned NumElems = VT.getVectorNumElements();
5667
5668  if (!Subtarget->hasSSE41() || EltVT == MVT::i8)
5669    return SDValue();
5670  if (!Subtarget->hasInt256() && VT == MVT::v16i16)
5671    return SDValue();
5672
5673  // Check the mask for BLEND and build the value.
5674  unsigned MaskValue = 0;
5675  // There are 2 lanes if (NumElems > 8), and 1 lane otherwise.
5676  unsigned NumLanes = (NumElems-1)/8 + 1;
5677  unsigned NumElemsInLane = NumElems / NumLanes;
5678
5679  // Blend for v16i16 should be symetric for the both lanes.
5680  for (unsigned i = 0; i < NumElemsInLane; ++i) {
5681
5682    int SndLaneEltIdx = (NumLanes == 2) ?
5683      SVOp->getMaskElt(i + NumElemsInLane) : -1;
5684    int EltIdx = SVOp->getMaskElt(i);
5685
5686    if ((EltIdx == -1 || EltIdx == (int)i) &&
5687        (SndLaneEltIdx == -1 || SndLaneEltIdx == (int)(i + NumElemsInLane)))
5688      continue;
5689
5690    if (((unsigned)EltIdx == (i + NumElems)) &&
5691        (SndLaneEltIdx == -1 ||
5692         (unsigned)SndLaneEltIdx == i + NumElems + NumElemsInLane))
5693      MaskValue |= (1<<i);
5694    else
5695      return SDValue();
5696  }
5697
5698  // Convert i32 vectors to floating point if it is not AVX2.
5699  // AVX2 introduced VPBLENDD instruction for 128 and 256-bit vectors.
5700  EVT BlendVT = VT;
5701  if (EltVT == MVT::i64 || (EltVT == MVT::i32 && !Subtarget->hasInt256())) {
5702    BlendVT = EVT::getVectorVT(*DAG.getContext(),
5703                              EVT::getFloatingPointVT(EltVT.getSizeInBits()),
5704                              NumElems);
5705    V1 = DAG.getNode(ISD::BITCAST, dl, VT, V1);
5706    V2 = DAG.getNode(ISD::BITCAST, dl, VT, V2);
5707  }
5708
5709  SDValue Ret =  DAG.getNode(X86ISD::BLENDI, dl, BlendVT, V1, V2,
5710                             DAG.getConstant(MaskValue, MVT::i32));
5711  return DAG.getNode(ISD::BITCAST, dl, VT, Ret);
5712}
5713
5714// v8i16 shuffles - Prefer shuffles in the following order:
5715// 1. [all]   pshuflw, pshufhw, optional move
5716// 2. [ssse3] 1 x pshufb
5717// 3. [ssse3] 2 x pshufb + 1 x por
5718// 4. [all]   mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
5719static SDValue
5720LowerVECTOR_SHUFFLEv8i16(SDValue Op, const X86Subtarget *Subtarget,
5721                         SelectionDAG &DAG) {
5722  ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5723  SDValue V1 = SVOp->getOperand(0);
5724  SDValue V2 = SVOp->getOperand(1);
5725  DebugLoc dl = SVOp->getDebugLoc();
5726  SmallVector<int, 8> MaskVals;
5727
5728  // Determine if more than 1 of the words in each of the low and high quadwords
5729  // of the result come from the same quadword of one of the two inputs.  Undef
5730  // mask values count as coming from any quadword, for better codegen.
5731  unsigned LoQuad[] = { 0, 0, 0, 0 };
5732  unsigned HiQuad[] = { 0, 0, 0, 0 };
5733  std::bitset<4> InputQuads;
5734  for (unsigned i = 0; i < 8; ++i) {
5735    unsigned *Quad = i < 4 ? LoQuad : HiQuad;
5736    int EltIdx = SVOp->getMaskElt(i);
5737    MaskVals.push_back(EltIdx);
5738    if (EltIdx < 0) {
5739      ++Quad[0];
5740      ++Quad[1];
5741      ++Quad[2];
5742      ++Quad[3];
5743      continue;
5744    }
5745    ++Quad[EltIdx / 4];
5746    InputQuads.set(EltIdx / 4);
5747  }
5748
5749  int BestLoQuad = -1;
5750  unsigned MaxQuad = 1;
5751  for (unsigned i = 0; i < 4; ++i) {
5752    if (LoQuad[i] > MaxQuad) {
5753      BestLoQuad = i;
5754      MaxQuad = LoQuad[i];
5755    }
5756  }
5757
5758  int BestHiQuad = -1;
5759  MaxQuad = 1;
5760  for (unsigned i = 0; i < 4; ++i) {
5761    if (HiQuad[i] > MaxQuad) {
5762      BestHiQuad = i;
5763      MaxQuad = HiQuad[i];
5764    }
5765  }
5766
5767  // For SSSE3, If all 8 words of the result come from only 1 quadword of each
5768  // of the two input vectors, shuffle them into one input vector so only a
5769  // single pshufb instruction is necessary. If There are more than 2 input
5770  // quads, disable the next transformation since it does not help SSSE3.
5771  bool V1Used = InputQuads[0] || InputQuads[1];
5772  bool V2Used = InputQuads[2] || InputQuads[3];
5773  if (Subtarget->hasSSSE3()) {
5774    if (InputQuads.count() == 2 && V1Used && V2Used) {
5775      BestLoQuad = InputQuads[0] ? 0 : 1;
5776      BestHiQuad = InputQuads[2] ? 2 : 3;
5777    }
5778    if (InputQuads.count() > 2) {
5779      BestLoQuad = -1;
5780      BestHiQuad = -1;
5781    }
5782  }
5783
5784  // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
5785  // the shuffle mask.  If a quad is scored as -1, that means that it contains
5786  // words from all 4 input quadwords.
5787  SDValue NewV;
5788  if (BestLoQuad >= 0 || BestHiQuad >= 0) {
5789    int MaskV[] = {
5790      BestLoQuad < 0 ? 0 : BestLoQuad,
5791      BestHiQuad < 0 ? 1 : BestHiQuad
5792    };
5793    NewV = DAG.getVectorShuffle(MVT::v2i64, dl,
5794                  DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1),
5795                  DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2), &MaskV[0]);
5796    NewV = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, NewV);
5797
5798    // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
5799    // source words for the shuffle, to aid later transformations.
5800    bool AllWordsInNewV = true;
5801    bool InOrder[2] = { true, true };
5802    for (unsigned i = 0; i != 8; ++i) {
5803      int idx = MaskVals[i];
5804      if (idx != (int)i)
5805        InOrder[i/4] = false;
5806      if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
5807        continue;
5808      AllWordsInNewV = false;
5809      break;
5810    }
5811
5812    bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
5813    if (AllWordsInNewV) {
5814      for (int i = 0; i != 8; ++i) {
5815        int idx = MaskVals[i];
5816        if (idx < 0)
5817          continue;
5818        idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
5819        if ((idx != i) && idx < 4)
5820          pshufhw = false;
5821        if ((idx != i) && idx > 3)
5822          pshuflw = false;
5823      }
5824      V1 = NewV;
5825      V2Used = false;
5826      BestLoQuad = 0;
5827      BestHiQuad = 1;
5828    }
5829
5830    // If we've eliminated the use of V2, and the new mask is a pshuflw or
5831    // pshufhw, that's as cheap as it gets.  Return the new shuffle.
5832    if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
5833      unsigned Opc = pshufhw ? X86ISD::PSHUFHW : X86ISD::PSHUFLW;
5834      unsigned TargetMask = 0;
5835      NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV,
5836                                  DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
5837      ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
5838      TargetMask = pshufhw ? getShufflePSHUFHWImmediate(SVOp):
5839                             getShufflePSHUFLWImmediate(SVOp);
5840      V1 = NewV.getOperand(0);
5841      return getTargetShuffleNode(Opc, dl, MVT::v8i16, V1, TargetMask, DAG);
5842    }
5843  }
5844
5845  // If we have SSSE3, and all words of the result are from 1 input vector,
5846  // case 2 is generated, otherwise case 3 is generated.  If no SSSE3
5847  // is present, fall back to case 4.
5848  if (Subtarget->hasSSSE3()) {
5849    SmallVector<SDValue,16> pshufbMask;
5850
5851    // If we have elements from both input vectors, set the high bit of the
5852    // shuffle mask element to zero out elements that come from V2 in the V1
5853    // mask, and elements that come from V1 in the V2 mask, so that the two
5854    // results can be OR'd together.
5855    bool TwoInputs = V1Used && V2Used;
5856    for (unsigned i = 0; i != 8; ++i) {
5857      int EltIdx = MaskVals[i] * 2;
5858      int Idx0 = (TwoInputs && (EltIdx >= 16)) ? 0x80 : EltIdx;
5859      int Idx1 = (TwoInputs && (EltIdx >= 16)) ? 0x80 : EltIdx+1;
5860      pshufbMask.push_back(DAG.getConstant(Idx0,   MVT::i8));
5861      pshufbMask.push_back(DAG.getConstant(Idx1, MVT::i8));
5862    }
5863    V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V1);
5864    V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
5865                     DAG.getNode(ISD::BUILD_VECTOR, dl,
5866                                 MVT::v16i8, &pshufbMask[0], 16));
5867    if (!TwoInputs)
5868      return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5869
5870    // Calculate the shuffle mask for the second input, shuffle it, and
5871    // OR it with the first shuffled input.
5872    pshufbMask.clear();
5873    for (unsigned i = 0; i != 8; ++i) {
5874      int EltIdx = MaskVals[i] * 2;
5875      int Idx0 = (EltIdx < 16) ? 0x80 : EltIdx - 16;
5876      int Idx1 = (EltIdx < 16) ? 0x80 : EltIdx - 15;
5877      pshufbMask.push_back(DAG.getConstant(Idx0, MVT::i8));
5878      pshufbMask.push_back(DAG.getConstant(Idx1, MVT::i8));
5879    }
5880    V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V2);
5881    V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
5882                     DAG.getNode(ISD::BUILD_VECTOR, dl,
5883                                 MVT::v16i8, &pshufbMask[0], 16));
5884    V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
5885    return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5886  }
5887
5888  // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
5889  // and update MaskVals with new element order.
5890  std::bitset<8> InOrder;
5891  if (BestLoQuad >= 0) {
5892    int MaskV[] = { -1, -1, -1, -1, 4, 5, 6, 7 };
5893    for (int i = 0; i != 4; ++i) {
5894      int idx = MaskVals[i];
5895      if (idx < 0) {
5896        InOrder.set(i);
5897      } else if ((idx / 4) == BestLoQuad) {
5898        MaskV[i] = idx & 3;
5899        InOrder.set(i);
5900      }
5901    }
5902    NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
5903                                &MaskV[0]);
5904
5905    if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3()) {
5906      ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
5907      NewV = getTargetShuffleNode(X86ISD::PSHUFLW, dl, MVT::v8i16,
5908                                  NewV.getOperand(0),
5909                                  getShufflePSHUFLWImmediate(SVOp), DAG);
5910    }
5911  }
5912
5913  // If BestHi >= 0, generate a pshufhw to put the high elements in order,
5914  // and update MaskVals with the new element order.
5915  if (BestHiQuad >= 0) {
5916    int MaskV[] = { 0, 1, 2, 3, -1, -1, -1, -1 };
5917    for (unsigned i = 4; i != 8; ++i) {
5918      int idx = MaskVals[i];
5919      if (idx < 0) {
5920        InOrder.set(i);
5921      } else if ((idx / 4) == BestHiQuad) {
5922        MaskV[i] = (idx & 3) + 4;
5923        InOrder.set(i);
5924      }
5925    }
5926    NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
5927                                &MaskV[0]);
5928
5929    if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3()) {
5930      ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
5931      NewV = getTargetShuffleNode(X86ISD::PSHUFHW, dl, MVT::v8i16,
5932                                  NewV.getOperand(0),
5933                                  getShufflePSHUFHWImmediate(SVOp), DAG);
5934    }
5935  }
5936
5937  // In case BestHi & BestLo were both -1, which means each quadword has a word
5938  // from each of the four input quadwords, calculate the InOrder bitvector now
5939  // before falling through to the insert/extract cleanup.
5940  if (BestLoQuad == -1 && BestHiQuad == -1) {
5941    NewV = V1;
5942    for (int i = 0; i != 8; ++i)
5943      if (MaskVals[i] < 0 || MaskVals[i] == i)
5944        InOrder.set(i);
5945  }
5946
5947  // The other elements are put in the right place using pextrw and pinsrw.
5948  for (unsigned i = 0; i != 8; ++i) {
5949    if (InOrder[i])
5950      continue;
5951    int EltIdx = MaskVals[i];
5952    if (EltIdx < 0)
5953      continue;
5954    SDValue ExtOp = (EltIdx < 8) ?
5955      DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
5956                  DAG.getIntPtrConstant(EltIdx)) :
5957      DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
5958                  DAG.getIntPtrConstant(EltIdx - 8));
5959    NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
5960                       DAG.getIntPtrConstant(i));
5961  }
5962  return NewV;
5963}
5964
5965// v16i8 shuffles - Prefer shuffles in the following order:
5966// 1. [ssse3] 1 x pshufb
5967// 2. [ssse3] 2 x pshufb + 1 x por
5968// 3. [all]   v8i16 shuffle + N x pextrw + rotate + pinsrw
5969static
5970SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
5971                                 SelectionDAG &DAG,
5972                                 const X86TargetLowering &TLI) {
5973  SDValue V1 = SVOp->getOperand(0);
5974  SDValue V2 = SVOp->getOperand(1);
5975  DebugLoc dl = SVOp->getDebugLoc();
5976  ArrayRef<int> MaskVals = SVOp->getMask();
5977
5978  // If we have SSSE3, case 1 is generated when all result bytes come from
5979  // one of  the inputs.  Otherwise, case 2 is generated.  If no SSSE3 is
5980  // present, fall back to case 3.
5981
5982  // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
5983  if (TLI.getSubtarget()->hasSSSE3()) {
5984    SmallVector<SDValue,16> pshufbMask;
5985
5986    // If all result elements are from one input vector, then only translate
5987    // undef mask values to 0x80 (zero out result) in the pshufb mask.
5988    //
5989    // Otherwise, we have elements from both input vectors, and must zero out
5990    // elements that come from V2 in the first mask, and V1 in the second mask
5991    // so that we can OR them together.
5992    for (unsigned i = 0; i != 16; ++i) {
5993      int EltIdx = MaskVals[i];
5994      if (EltIdx < 0 || EltIdx >= 16)
5995        EltIdx = 0x80;
5996      pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
5997    }
5998    V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
5999                     DAG.getNode(ISD::BUILD_VECTOR, dl,
6000                                 MVT::v16i8, &pshufbMask[0], 16));
6001
6002    // As PSHUFB will zero elements with negative indices, it's safe to ignore
6003    // the 2nd operand if it's undefined or zero.
6004    if (V2.getOpcode() == ISD::UNDEF ||
6005        ISD::isBuildVectorAllZeros(V2.getNode()))
6006      return V1;
6007
6008    // Calculate the shuffle mask for the second input, shuffle it, and
6009    // OR it with the first shuffled input.
6010    pshufbMask.clear();
6011    for (unsigned i = 0; i != 16; ++i) {
6012      int EltIdx = MaskVals[i];
6013      EltIdx = (EltIdx < 16) ? 0x80 : EltIdx - 16;
6014      pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
6015    }
6016    V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
6017                     DAG.getNode(ISD::BUILD_VECTOR, dl,
6018                                 MVT::v16i8, &pshufbMask[0], 16));
6019    return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
6020  }
6021
6022  // No SSSE3 - Calculate in place words and then fix all out of place words
6023  // With 0-16 extracts & inserts.  Worst case is 16 bytes out of order from
6024  // the 16 different words that comprise the two doublequadword input vectors.
6025  V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
6026  V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
6027  SDValue NewV = V1;
6028  for (int i = 0; i != 8; ++i) {
6029    int Elt0 = MaskVals[i*2];
6030    int Elt1 = MaskVals[i*2+1];
6031
6032    // This word of the result is all undef, skip it.
6033    if (Elt0 < 0 && Elt1 < 0)
6034      continue;
6035
6036    // This word of the result is already in the correct place, skip it.
6037    if ((Elt0 == i*2) && (Elt1 == i*2+1))
6038      continue;
6039
6040    SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
6041    SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
6042    SDValue InsElt;
6043
6044    // If Elt0 and Elt1 are defined, are consecutive, and can be load
6045    // using a single extract together, load it and store it.
6046    if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
6047      InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
6048                           DAG.getIntPtrConstant(Elt1 / 2));
6049      NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
6050                        DAG.getIntPtrConstant(i));
6051      continue;
6052    }
6053
6054    // If Elt1 is defined, extract it from the appropriate source.  If the
6055    // source byte is not also odd, shift the extracted word left 8 bits
6056    // otherwise clear the bottom 8 bits if we need to do an or.
6057    if (Elt1 >= 0) {
6058      InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
6059                           DAG.getIntPtrConstant(Elt1 / 2));
6060      if ((Elt1 & 1) == 0)
6061        InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
6062                             DAG.getConstant(8,
6063                                  TLI.getShiftAmountTy(InsElt.getValueType())));
6064      else if (Elt0 >= 0)
6065        InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
6066                             DAG.getConstant(0xFF00, MVT::i16));
6067    }
6068    // If Elt0 is defined, extract it from the appropriate source.  If the
6069    // source byte is not also even, shift the extracted word right 8 bits. If
6070    // Elt1 was also defined, OR the extracted values together before
6071    // inserting them in the result.
6072    if (Elt0 >= 0) {
6073      SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
6074                                    Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
6075      if ((Elt0 & 1) != 0)
6076        InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
6077                              DAG.getConstant(8,
6078                                 TLI.getShiftAmountTy(InsElt0.getValueType())));
6079      else if (Elt1 >= 0)
6080        InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
6081                             DAG.getConstant(0x00FF, MVT::i16));
6082      InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
6083                         : InsElt0;
6084    }
6085    NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
6086                       DAG.getIntPtrConstant(i));
6087  }
6088  return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, NewV);
6089}
6090
6091// v32i8 shuffles - Translate to VPSHUFB if possible.
6092static
6093SDValue LowerVECTOR_SHUFFLEv32i8(ShuffleVectorSDNode *SVOp,
6094                                 const X86Subtarget *Subtarget,
6095                                 SelectionDAG &DAG) {
6096  EVT VT = SVOp->getValueType(0);
6097  SDValue V1 = SVOp->getOperand(0);
6098  SDValue V2 = SVOp->getOperand(1);
6099  DebugLoc dl = SVOp->getDebugLoc();
6100  SmallVector<int, 32> MaskVals(SVOp->getMask().begin(), SVOp->getMask().end());
6101
6102  bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
6103  bool V1IsAllZero = ISD::isBuildVectorAllZeros(V1.getNode());
6104  bool V2IsAllZero = ISD::isBuildVectorAllZeros(V2.getNode());
6105
6106  // VPSHUFB may be generated if
6107  // (1) one of input vector is undefined or zeroinitializer.
6108  // The mask value 0x80 puts 0 in the corresponding slot of the vector.
6109  // And (2) the mask indexes don't cross the 128-bit lane.
6110  if (VT != MVT::v32i8 || !Subtarget->hasInt256() ||
6111      (!V2IsUndef && !V2IsAllZero && !V1IsAllZero))
6112    return SDValue();
6113
6114  if (V1IsAllZero && !V2IsAllZero) {
6115    CommuteVectorShuffleMask(MaskVals, 32);
6116    V1 = V2;
6117  }
6118  SmallVector<SDValue, 32> pshufbMask;
6119  for (unsigned i = 0; i != 32; i++) {
6120    int EltIdx = MaskVals[i];
6121    if (EltIdx < 0 || EltIdx >= 32)
6122      EltIdx = 0x80;
6123    else {
6124      if ((EltIdx >= 16 && i < 16) || (EltIdx < 16 && i >= 16))
6125        // Cross lane is not allowed.
6126        return SDValue();
6127      EltIdx &= 0xf;
6128    }
6129    pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
6130  }
6131  return DAG.getNode(X86ISD::PSHUFB, dl, MVT::v32i8, V1,
6132                      DAG.getNode(ISD::BUILD_VECTOR, dl,
6133                                  MVT::v32i8, &pshufbMask[0], 32));
6134}
6135
6136/// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
6137/// ones, or rewriting v4i32 / v4f32 as 2 wide ones if possible. This can be
6138/// done when every pair / quad of shuffle mask elements point to elements in
6139/// the right sequence. e.g.
6140/// vector_shuffle X, Y, <2, 3, | 10, 11, | 0, 1, | 14, 15>
6141static
6142SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
6143                                 SelectionDAG &DAG, DebugLoc dl) {
6144  MVT VT = SVOp->getValueType(0).getSimpleVT();
6145  unsigned NumElems = VT.getVectorNumElements();
6146  MVT NewVT;
6147  unsigned Scale;
6148  switch (VT.SimpleTy) {
6149  default: llvm_unreachable("Unexpected!");
6150  case MVT::v4f32:  NewVT = MVT::v2f64; Scale = 2; break;
6151  case MVT::v4i32:  NewVT = MVT::v2i64; Scale = 2; break;
6152  case MVT::v8i16:  NewVT = MVT::v4i32; Scale = 2; break;
6153  case MVT::v16i8:  NewVT = MVT::v4i32; Scale = 4; break;
6154  case MVT::v16i16: NewVT = MVT::v8i32; Scale = 2; break;
6155  case MVT::v32i8:  NewVT = MVT::v8i32; Scale = 4; break;
6156  }
6157
6158  SmallVector<int, 8> MaskVec;
6159  for (unsigned i = 0; i != NumElems; i += Scale) {
6160    int StartIdx = -1;
6161    for (unsigned j = 0; j != Scale; ++j) {
6162      int EltIdx = SVOp->getMaskElt(i+j);
6163      if (EltIdx < 0)
6164        continue;
6165      if (StartIdx < 0)
6166        StartIdx = (EltIdx / Scale);
6167      if (EltIdx != (int)(StartIdx*Scale + j))
6168        return SDValue();
6169    }
6170    MaskVec.push_back(StartIdx);
6171  }
6172
6173  SDValue V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(0));
6174  SDValue V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(1));
6175  return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
6176}
6177
6178/// getVZextMovL - Return a zero-extending vector move low node.
6179///
6180static SDValue getVZextMovL(EVT VT, EVT OpVT,
6181                            SDValue SrcOp, SelectionDAG &DAG,
6182                            const X86Subtarget *Subtarget, DebugLoc dl) {
6183  if (VT == MVT::v2f64 || VT == MVT::v4f32) {
6184    LoadSDNode *LD = NULL;
6185    if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
6186      LD = dyn_cast<LoadSDNode>(SrcOp);
6187    if (!LD) {
6188      // movssrr and movsdrr do not clear top bits. Try to use movd, movq
6189      // instead.
6190      MVT ExtVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
6191      if ((ExtVT != MVT::i64 || Subtarget->is64Bit()) &&
6192          SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
6193          SrcOp.getOperand(0).getOpcode() == ISD::BITCAST &&
6194          SrcOp.getOperand(0).getOperand(0).getValueType() == ExtVT) {
6195        // PR2108
6196        OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
6197        return DAG.getNode(ISD::BITCAST, dl, VT,
6198                           DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
6199                                       DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6200                                                   OpVT,
6201                                                   SrcOp.getOperand(0)
6202                                                          .getOperand(0))));
6203      }
6204    }
6205  }
6206
6207  return DAG.getNode(ISD::BITCAST, dl, VT,
6208                     DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
6209                                 DAG.getNode(ISD::BITCAST, dl,
6210                                             OpVT, SrcOp)));
6211}
6212
6213/// LowerVECTOR_SHUFFLE_256 - Handle all 256-bit wide vectors shuffles
6214/// which could not be matched by any known target speficic shuffle
6215static SDValue
6216LowerVECTOR_SHUFFLE_256(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
6217
6218  SDValue NewOp = Compact8x32ShuffleNode(SVOp, DAG);
6219  if (NewOp.getNode())
6220    return NewOp;
6221
6222  EVT VT = SVOp->getValueType(0);
6223
6224  unsigned NumElems = VT.getVectorNumElements();
6225  unsigned NumLaneElems = NumElems / 2;
6226
6227  DebugLoc dl = SVOp->getDebugLoc();
6228  MVT EltVT = VT.getVectorElementType().getSimpleVT();
6229  EVT NVT = MVT::getVectorVT(EltVT, NumLaneElems);
6230  SDValue Output[2];
6231
6232  SmallVector<int, 16> Mask;
6233  for (unsigned l = 0; l < 2; ++l) {
6234    // Build a shuffle mask for the output, discovering on the fly which
6235    // input vectors to use as shuffle operands (recorded in InputUsed).
6236    // If building a suitable shuffle vector proves too hard, then bail
6237    // out with UseBuildVector set.
6238    bool UseBuildVector = false;
6239    int InputUsed[2] = { -1, -1 }; // Not yet discovered.
6240    unsigned LaneStart = l * NumLaneElems;
6241    for (unsigned i = 0; i != NumLaneElems; ++i) {
6242      // The mask element.  This indexes into the input.
6243      int Idx = SVOp->getMaskElt(i+LaneStart);
6244      if (Idx < 0) {
6245        // the mask element does not index into any input vector.
6246        Mask.push_back(-1);
6247        continue;
6248      }
6249
6250      // The input vector this mask element indexes into.
6251      int Input = Idx / NumLaneElems;
6252
6253      // Turn the index into an offset from the start of the input vector.
6254      Idx -= Input * NumLaneElems;
6255
6256      // Find or create a shuffle vector operand to hold this input.
6257      unsigned OpNo;
6258      for (OpNo = 0; OpNo < array_lengthof(InputUsed); ++OpNo) {
6259        if (InputUsed[OpNo] == Input)
6260          // This input vector is already an operand.
6261          break;
6262        if (InputUsed[OpNo] < 0) {
6263          // Create a new operand for this input vector.
6264          InputUsed[OpNo] = Input;
6265          break;
6266        }
6267      }
6268
6269      if (OpNo >= array_lengthof(InputUsed)) {
6270        // More than two input vectors used!  Give up on trying to create a
6271        // shuffle vector.  Insert all elements into a BUILD_VECTOR instead.
6272        UseBuildVector = true;
6273        break;
6274      }
6275
6276      // Add the mask index for the new shuffle vector.
6277      Mask.push_back(Idx + OpNo * NumLaneElems);
6278    }
6279
6280    if (UseBuildVector) {
6281      SmallVector<SDValue, 16> SVOps;
6282      for (unsigned i = 0; i != NumLaneElems; ++i) {
6283        // The mask element.  This indexes into the input.
6284        int Idx = SVOp->getMaskElt(i+LaneStart);
6285        if (Idx < 0) {
6286          SVOps.push_back(DAG.getUNDEF(EltVT));
6287          continue;
6288        }
6289
6290        // The input vector this mask element indexes into.
6291        int Input = Idx / NumElems;
6292
6293        // Turn the index into an offset from the start of the input vector.
6294        Idx -= Input * NumElems;
6295
6296        // Extract the vector element by hand.
6297        SVOps.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
6298                                    SVOp->getOperand(Input),
6299                                    DAG.getIntPtrConstant(Idx)));
6300      }
6301
6302      // Construct the output using a BUILD_VECTOR.
6303      Output[l] = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, &SVOps[0],
6304                              SVOps.size());
6305    } else if (InputUsed[0] < 0) {
6306      // No input vectors were used! The result is undefined.
6307      Output[l] = DAG.getUNDEF(NVT);
6308    } else {
6309      SDValue Op0 = Extract128BitVector(SVOp->getOperand(InputUsed[0] / 2),
6310                                        (InputUsed[0] % 2) * NumLaneElems,
6311                                        DAG, dl);
6312      // If only one input was used, use an undefined vector for the other.
6313      SDValue Op1 = (InputUsed[1] < 0) ? DAG.getUNDEF(NVT) :
6314        Extract128BitVector(SVOp->getOperand(InputUsed[1] / 2),
6315                            (InputUsed[1] % 2) * NumLaneElems, DAG, dl);
6316      // At least one input vector was used. Create a new shuffle vector.
6317      Output[l] = DAG.getVectorShuffle(NVT, dl, Op0, Op1, &Mask[0]);
6318    }
6319
6320    Mask.clear();
6321  }
6322
6323  // Concatenate the result back
6324  return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Output[0], Output[1]);
6325}
6326
6327/// LowerVECTOR_SHUFFLE_128v4 - Handle all 128-bit wide vectors with
6328/// 4 elements, and match them with several different shuffle types.
6329static SDValue
6330LowerVECTOR_SHUFFLE_128v4(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
6331  SDValue V1 = SVOp->getOperand(0);
6332  SDValue V2 = SVOp->getOperand(1);
6333  DebugLoc dl = SVOp->getDebugLoc();
6334  EVT VT = SVOp->getValueType(0);
6335
6336  assert(VT.is128BitVector() && "Unsupported vector size");
6337
6338  std::pair<int, int> Locs[4];
6339  int Mask1[] = { -1, -1, -1, -1 };
6340  SmallVector<int, 8> PermMask(SVOp->getMask().begin(), SVOp->getMask().end());
6341
6342  unsigned NumHi = 0;
6343  unsigned NumLo = 0;
6344  for (unsigned i = 0; i != 4; ++i) {
6345    int Idx = PermMask[i];
6346    if (Idx < 0) {
6347      Locs[i] = std::make_pair(-1, -1);
6348    } else {
6349      assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
6350      if (Idx < 4) {
6351        Locs[i] = std::make_pair(0, NumLo);
6352        Mask1[NumLo] = Idx;
6353        NumLo++;
6354      } else {
6355        Locs[i] = std::make_pair(1, NumHi);
6356        if (2+NumHi < 4)
6357          Mask1[2+NumHi] = Idx;
6358        NumHi++;
6359      }
6360    }
6361  }
6362
6363  if (NumLo <= 2 && NumHi <= 2) {
6364    // If no more than two elements come from either vector. This can be
6365    // implemented with two shuffles. First shuffle gather the elements.
6366    // The second shuffle, which takes the first shuffle as both of its
6367    // vector operands, put the elements into the right order.
6368    V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6369
6370    int Mask2[] = { -1, -1, -1, -1 };
6371
6372    for (unsigned i = 0; i != 4; ++i)
6373      if (Locs[i].first != -1) {
6374        unsigned Idx = (i < 2) ? 0 : 4;
6375        Idx += Locs[i].first * 2 + Locs[i].second;
6376        Mask2[i] = Idx;
6377      }
6378
6379    return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
6380  }
6381
6382  if (NumLo == 3 || NumHi == 3) {
6383    // Otherwise, we must have three elements from one vector, call it X, and
6384    // one element from the other, call it Y.  First, use a shufps to build an
6385    // intermediate vector with the one element from Y and the element from X
6386    // that will be in the same half in the final destination (the indexes don't
6387    // matter). Then, use a shufps to build the final vector, taking the half
6388    // containing the element from Y from the intermediate, and the other half
6389    // from X.
6390    if (NumHi == 3) {
6391      // Normalize it so the 3 elements come from V1.
6392      CommuteVectorShuffleMask(PermMask, 4);
6393      std::swap(V1, V2);
6394    }
6395
6396    // Find the element from V2.
6397    unsigned HiIndex;
6398    for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
6399      int Val = PermMask[HiIndex];
6400      if (Val < 0)
6401        continue;
6402      if (Val >= 4)
6403        break;
6404    }
6405
6406    Mask1[0] = PermMask[HiIndex];
6407    Mask1[1] = -1;
6408    Mask1[2] = PermMask[HiIndex^1];
6409    Mask1[3] = -1;
6410    V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6411
6412    if (HiIndex >= 2) {
6413      Mask1[0] = PermMask[0];
6414      Mask1[1] = PermMask[1];
6415      Mask1[2] = HiIndex & 1 ? 6 : 4;
6416      Mask1[3] = HiIndex & 1 ? 4 : 6;
6417      return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6418    }
6419
6420    Mask1[0] = HiIndex & 1 ? 2 : 0;
6421    Mask1[1] = HiIndex & 1 ? 0 : 2;
6422    Mask1[2] = PermMask[2];
6423    Mask1[3] = PermMask[3];
6424    if (Mask1[2] >= 0)
6425      Mask1[2] += 4;
6426    if (Mask1[3] >= 0)
6427      Mask1[3] += 4;
6428    return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
6429  }
6430
6431  // Break it into (shuffle shuffle_hi, shuffle_lo).
6432  int LoMask[] = { -1, -1, -1, -1 };
6433  int HiMask[] = { -1, -1, -1, -1 };
6434
6435  int *MaskPtr = LoMask;
6436  unsigned MaskIdx = 0;
6437  unsigned LoIdx = 0;
6438  unsigned HiIdx = 2;
6439  for (unsigned i = 0; i != 4; ++i) {
6440    if (i == 2) {
6441      MaskPtr = HiMask;
6442      MaskIdx = 1;
6443      LoIdx = 0;
6444      HiIdx = 2;
6445    }
6446    int Idx = PermMask[i];
6447    if (Idx < 0) {
6448      Locs[i] = std::make_pair(-1, -1);
6449    } else if (Idx < 4) {
6450      Locs[i] = std::make_pair(MaskIdx, LoIdx);
6451      MaskPtr[LoIdx] = Idx;
6452      LoIdx++;
6453    } else {
6454      Locs[i] = std::make_pair(MaskIdx, HiIdx);
6455      MaskPtr[HiIdx] = Idx;
6456      HiIdx++;
6457    }
6458  }
6459
6460  SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
6461  SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
6462  int MaskOps[] = { -1, -1, -1, -1 };
6463  for (unsigned i = 0; i != 4; ++i)
6464    if (Locs[i].first != -1)
6465      MaskOps[i] = Locs[i].first * 4 + Locs[i].second;
6466  return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
6467}
6468
6469static bool MayFoldVectorLoad(SDValue V) {
6470  while (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
6471    V = V.getOperand(0);
6472
6473  if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
6474    V = V.getOperand(0);
6475  if (V.hasOneUse() && V.getOpcode() == ISD::BUILD_VECTOR &&
6476      V.getNumOperands() == 2 && V.getOperand(1).getOpcode() == ISD::UNDEF)
6477    // BUILD_VECTOR (load), undef
6478    V = V.getOperand(0);
6479
6480  return MayFoldLoad(V);
6481}
6482
6483static
6484SDValue getMOVDDup(SDValue &Op, DebugLoc &dl, SDValue V1, SelectionDAG &DAG) {
6485  EVT VT = Op.getValueType();
6486
6487  // Canonizalize to v2f64.
6488  V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
6489  return DAG.getNode(ISD::BITCAST, dl, VT,
6490                     getTargetShuffleNode(X86ISD::MOVDDUP, dl, MVT::v2f64,
6491                                          V1, DAG));
6492}
6493
6494static
6495SDValue getMOVLowToHigh(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG,
6496                        bool HasSSE2) {
6497  SDValue V1 = Op.getOperand(0);
6498  SDValue V2 = Op.getOperand(1);
6499  EVT VT = Op.getValueType();
6500
6501  assert(VT != MVT::v2i64 && "unsupported shuffle type");
6502
6503  if (HasSSE2 && VT == MVT::v2f64)
6504    return getTargetShuffleNode(X86ISD::MOVLHPD, dl, VT, V1, V2, DAG);
6505
6506  // v4f32 or v4i32: canonizalized to v4f32 (which is legal for SSE1)
6507  return DAG.getNode(ISD::BITCAST, dl, VT,
6508                     getTargetShuffleNode(X86ISD::MOVLHPS, dl, MVT::v4f32,
6509                           DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V1),
6510                           DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V2), DAG));
6511}
6512
6513static
6514SDValue getMOVHighToLow(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG) {
6515  SDValue V1 = Op.getOperand(0);
6516  SDValue V2 = Op.getOperand(1);
6517  EVT VT = Op.getValueType();
6518
6519  assert((VT == MVT::v4i32 || VT == MVT::v4f32) &&
6520         "unsupported shuffle type");
6521
6522  if (V2.getOpcode() == ISD::UNDEF)
6523    V2 = V1;
6524
6525  // v4i32 or v4f32
6526  return getTargetShuffleNode(X86ISD::MOVHLPS, dl, VT, V1, V2, DAG);
6527}
6528
6529static
6530SDValue getMOVLP(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG, bool HasSSE2) {
6531  SDValue V1 = Op.getOperand(0);
6532  SDValue V2 = Op.getOperand(1);
6533  EVT VT = Op.getValueType();
6534  unsigned NumElems = VT.getVectorNumElements();
6535
6536  // Use MOVLPS and MOVLPD in case V1 or V2 are loads. During isel, the second
6537  // operand of these instructions is only memory, so check if there's a
6538  // potencial load folding here, otherwise use SHUFPS or MOVSD to match the
6539  // same masks.
6540  bool CanFoldLoad = false;
6541
6542  // Trivial case, when V2 comes from a load.
6543  if (MayFoldVectorLoad(V2))
6544    CanFoldLoad = true;
6545
6546  // When V1 is a load, it can be folded later into a store in isel, example:
6547  //  (store (v4f32 (X86Movlps (load addr:$src1), VR128:$src2)), addr:$src1)
6548  //    turns into:
6549  //  (MOVLPSmr addr:$src1, VR128:$src2)
6550  // So, recognize this potential and also use MOVLPS or MOVLPD
6551  else if (MayFoldVectorLoad(V1) && MayFoldIntoStore(Op))
6552    CanFoldLoad = true;
6553
6554  ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6555  if (CanFoldLoad) {
6556    if (HasSSE2 && NumElems == 2)
6557      return getTargetShuffleNode(X86ISD::MOVLPD, dl, VT, V1, V2, DAG);
6558
6559    if (NumElems == 4)
6560      // If we don't care about the second element, proceed to use movss.
6561      if (SVOp->getMaskElt(1) != -1)
6562        return getTargetShuffleNode(X86ISD::MOVLPS, dl, VT, V1, V2, DAG);
6563  }
6564
6565  // movl and movlp will both match v2i64, but v2i64 is never matched by
6566  // movl earlier because we make it strict to avoid messing with the movlp load
6567  // folding logic (see the code above getMOVLP call). Match it here then,
6568  // this is horrible, but will stay like this until we move all shuffle
6569  // matching to x86 specific nodes. Note that for the 1st condition all
6570  // types are matched with movsd.
6571  if (HasSSE2) {
6572    // FIXME: isMOVLMask should be checked and matched before getMOVLP,
6573    // as to remove this logic from here, as much as possible
6574    if (NumElems == 2 || !isMOVLMask(SVOp->getMask(), VT))
6575      return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
6576    return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
6577  }
6578
6579  assert(VT != MVT::v4i32 && "unsupported shuffle type");
6580
6581  // Invert the operand order and use SHUFPS to match it.
6582  return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V2, V1,
6583                              getShuffleSHUFImmediate(SVOp), DAG);
6584}
6585
6586// Reduce a vector shuffle to zext.
6587SDValue
6588X86TargetLowering::lowerVectorIntExtend(SDValue Op, SelectionDAG &DAG) const {
6589  // PMOVZX is only available from SSE41.
6590  if (!Subtarget->hasSSE41())
6591    return SDValue();
6592
6593  EVT VT = Op.getValueType();
6594
6595  // Only AVX2 support 256-bit vector integer extending.
6596  if (!Subtarget->hasInt256() && VT.is256BitVector())
6597    return SDValue();
6598
6599  ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6600  DebugLoc DL = Op.getDebugLoc();
6601  SDValue V1 = Op.getOperand(0);
6602  SDValue V2 = Op.getOperand(1);
6603  unsigned NumElems = VT.getVectorNumElements();
6604
6605  // Extending is an unary operation and the element type of the source vector
6606  // won't be equal to or larger than i64.
6607  if (V2.getOpcode() != ISD::UNDEF || !VT.isInteger() ||
6608      VT.getVectorElementType() == MVT::i64)
6609    return SDValue();
6610
6611  // Find the expansion ratio, e.g. expanding from i8 to i32 has a ratio of 4.
6612  unsigned Shift = 1; // Start from 2, i.e. 1 << 1.
6613  while ((1U << Shift) < NumElems) {
6614    if (SVOp->getMaskElt(1U << Shift) == 1)
6615      break;
6616    Shift += 1;
6617    // The maximal ratio is 8, i.e. from i8 to i64.
6618    if (Shift > 3)
6619      return SDValue();
6620  }
6621
6622  // Check the shuffle mask.
6623  unsigned Mask = (1U << Shift) - 1;
6624  for (unsigned i = 0; i != NumElems; ++i) {
6625    int EltIdx = SVOp->getMaskElt(i);
6626    if ((i & Mask) != 0 && EltIdx != -1)
6627      return SDValue();
6628    if ((i & Mask) == 0 && (unsigned)EltIdx != (i >> Shift))
6629      return SDValue();
6630  }
6631
6632  unsigned NBits = VT.getVectorElementType().getSizeInBits() << Shift;
6633  EVT NeVT = EVT::getIntegerVT(*DAG.getContext(), NBits);
6634  EVT NVT = EVT::getVectorVT(*DAG.getContext(), NeVT, NumElems >> Shift);
6635
6636  if (!isTypeLegal(NVT))
6637    return SDValue();
6638
6639  // Simplify the operand as it's prepared to be fed into shuffle.
6640  unsigned SignificantBits = NVT.getSizeInBits() >> Shift;
6641  if (V1.getOpcode() == ISD::BITCAST &&
6642      V1.getOperand(0).getOpcode() == ISD::SCALAR_TO_VECTOR &&
6643      V1.getOperand(0).getOperand(0).getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
6644      V1.getOperand(0)
6645        .getOperand(0).getValueType().getSizeInBits() == SignificantBits) {
6646    // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast x)
6647    SDValue V = V1.getOperand(0).getOperand(0).getOperand(0);
6648    ConstantSDNode *CIdx =
6649      dyn_cast<ConstantSDNode>(V1.getOperand(0).getOperand(0).getOperand(1));
6650    // If it's foldable, i.e. normal load with single use, we will let code
6651    // selection to fold it. Otherwise, we will short the conversion sequence.
6652    if (CIdx && CIdx->getZExtValue() == 0 &&
6653        (!ISD::isNormalLoad(V.getNode()) || !V.hasOneUse()))
6654      V1 = DAG.getNode(ISD::BITCAST, DL, V1.getValueType(), V);
6655  }
6656
6657  return DAG.getNode(ISD::BITCAST, DL, VT,
6658                     DAG.getNode(X86ISD::VZEXT, DL, NVT, V1));
6659}
6660
6661SDValue
6662X86TargetLowering::NormalizeVectorShuffle(SDValue Op, SelectionDAG &DAG) const {
6663  ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6664  EVT VT = Op.getValueType();
6665  DebugLoc dl = Op.getDebugLoc();
6666  SDValue V1 = Op.getOperand(0);
6667  SDValue V2 = Op.getOperand(1);
6668
6669  if (isZeroShuffle(SVOp))
6670    return getZeroVector(VT, Subtarget, DAG, dl);
6671
6672  // Handle splat operations
6673  if (SVOp->isSplat()) {
6674    unsigned NumElem = VT.getVectorNumElements();
6675    int Size = VT.getSizeInBits();
6676
6677    // Use vbroadcast whenever the splat comes from a foldable load
6678    SDValue Broadcast = LowerVectorBroadcast(Op, DAG);
6679    if (Broadcast.getNode())
6680      return Broadcast;
6681
6682    // Handle splats by matching through known shuffle masks
6683    if ((Size == 128 && NumElem <= 4) ||
6684        (Size == 256 && NumElem <= 8))
6685      return SDValue();
6686
6687    // All remaning splats are promoted to target supported vector shuffles.
6688    return PromoteSplat(SVOp, DAG);
6689  }
6690
6691  // Check integer expanding shuffles.
6692  SDValue NewOp = lowerVectorIntExtend(Op, DAG);
6693  if (NewOp.getNode())
6694    return NewOp;
6695
6696  // If the shuffle can be profitably rewritten as a narrower shuffle, then
6697  // do it!
6698  if (VT == MVT::v8i16  || VT == MVT::v16i8 ||
6699      VT == MVT::v16i16 || VT == MVT::v32i8) {
6700    SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
6701    if (NewOp.getNode())
6702      return DAG.getNode(ISD::BITCAST, dl, VT, NewOp);
6703  } else if ((VT == MVT::v4i32 ||
6704             (VT == MVT::v4f32 && Subtarget->hasSSE2()))) {
6705    // FIXME: Figure out a cleaner way to do this.
6706    // Try to make use of movq to zero out the top part.
6707    if (ISD::isBuildVectorAllZeros(V2.getNode())) {
6708      SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
6709      if (NewOp.getNode()) {
6710        EVT NewVT = NewOp.getValueType();
6711        if (isCommutedMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(),
6712                               NewVT, true, false))
6713          return getVZextMovL(VT, NewVT, NewOp.getOperand(0),
6714                              DAG, Subtarget, dl);
6715      }
6716    } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
6717      SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
6718      if (NewOp.getNode()) {
6719        EVT NewVT = NewOp.getValueType();
6720        if (isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(), NewVT))
6721          return getVZextMovL(VT, NewVT, NewOp.getOperand(1),
6722                              DAG, Subtarget, dl);
6723      }
6724    }
6725  }
6726  return SDValue();
6727}
6728
6729SDValue
6730X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) const {
6731  ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6732  SDValue V1 = Op.getOperand(0);
6733  SDValue V2 = Op.getOperand(1);
6734  EVT VT = Op.getValueType();
6735  DebugLoc dl = Op.getDebugLoc();
6736  unsigned NumElems = VT.getVectorNumElements();
6737  bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
6738  bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
6739  bool V1IsSplat = false;
6740  bool V2IsSplat = false;
6741  bool HasSSE2 = Subtarget->hasSSE2();
6742  bool HasFp256    = Subtarget->hasFp256();
6743  bool HasInt256   = Subtarget->hasInt256();
6744  MachineFunction &MF = DAG.getMachineFunction();
6745  bool OptForSize = MF.getFunction()->getAttributes().
6746    hasAttribute(AttributeSet::FunctionIndex, Attribute::OptimizeForSize);
6747
6748  assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
6749
6750  if (V1IsUndef && V2IsUndef)
6751    return DAG.getUNDEF(VT);
6752
6753  assert(!V1IsUndef && "Op 1 of shuffle should not be undef");
6754
6755  // Vector shuffle lowering takes 3 steps:
6756  //
6757  // 1) Normalize the input vectors. Here splats, zeroed vectors, profitable
6758  //    narrowing and commutation of operands should be handled.
6759  // 2) Matching of shuffles with known shuffle masks to x86 target specific
6760  //    shuffle nodes.
6761  // 3) Rewriting of unmatched masks into new generic shuffle operations,
6762  //    so the shuffle can be broken into other shuffles and the legalizer can
6763  //    try the lowering again.
6764  //
6765  // The general idea is that no vector_shuffle operation should be left to
6766  // be matched during isel, all of them must be converted to a target specific
6767  // node here.
6768
6769  // Normalize the input vectors. Here splats, zeroed vectors, profitable
6770  // narrowing and commutation of operands should be handled. The actual code
6771  // doesn't include all of those, work in progress...
6772  SDValue NewOp = NormalizeVectorShuffle(Op, DAG);
6773  if (NewOp.getNode())
6774    return NewOp;
6775
6776  SmallVector<int, 8> M(SVOp->getMask().begin(), SVOp->getMask().end());
6777
6778  // NOTE: isPSHUFDMask can also match both masks below (unpckl_undef and
6779  // unpckh_undef). Only use pshufd if speed is more important than size.
6780  if (OptForSize && isUNPCKL_v_undef_Mask(M, VT, HasInt256))
6781    return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
6782  if (OptForSize && isUNPCKH_v_undef_Mask(M, VT, HasInt256))
6783    return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
6784
6785  if (isMOVDDUPMask(M, VT) && Subtarget->hasSSE3() &&
6786      V2IsUndef && MayFoldVectorLoad(V1))
6787    return getMOVDDup(Op, dl, V1, DAG);
6788
6789  if (isMOVHLPS_v_undef_Mask(M, VT))
6790    return getMOVHighToLow(Op, dl, DAG);
6791
6792  // Use to match splats
6793  if (HasSSE2 && isUNPCKHMask(M, VT, HasInt256) && V2IsUndef &&
6794      (VT == MVT::v2f64 || VT == MVT::v2i64))
6795    return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
6796
6797  if (isPSHUFDMask(M, VT)) {
6798    // The actual implementation will match the mask in the if above and then
6799    // during isel it can match several different instructions, not only pshufd
6800    // as its name says, sad but true, emulate the behavior for now...
6801    if (isMOVDDUPMask(M, VT) && ((VT == MVT::v4f32 || VT == MVT::v2i64)))
6802      return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V1, DAG);
6803
6804    unsigned TargetMask = getShuffleSHUFImmediate(SVOp);
6805
6806    if (HasSSE2 && (VT == MVT::v4f32 || VT == MVT::v4i32))
6807      return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1, TargetMask, DAG);
6808
6809    if (HasFp256 && (VT == MVT::v4f32 || VT == MVT::v2f64))
6810      return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1, TargetMask,
6811                                  DAG);
6812
6813    return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V1,
6814                                TargetMask, DAG);
6815  }
6816
6817  // Check if this can be converted into a logical shift.
6818  bool isLeft = false;
6819  unsigned ShAmt = 0;
6820  SDValue ShVal;
6821  bool isShift = HasSSE2 && isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
6822  if (isShift && ShVal.hasOneUse()) {
6823    // If the shifted value has multiple uses, it may be cheaper to use
6824    // v_set0 + movlhps or movhlps, etc.
6825    EVT EltVT = VT.getVectorElementType();
6826    ShAmt *= EltVT.getSizeInBits();
6827    return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
6828  }
6829
6830  if (isMOVLMask(M, VT)) {
6831    if (ISD::isBuildVectorAllZeros(V1.getNode()))
6832      return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
6833    if (!isMOVLPMask(M, VT)) {
6834      if (HasSSE2 && (VT == MVT::v2i64 || VT == MVT::v2f64))
6835        return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
6836
6837      if (VT == MVT::v4i32 || VT == MVT::v4f32)
6838        return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
6839    }
6840  }
6841
6842  // FIXME: fold these into legal mask.
6843  if (isMOVLHPSMask(M, VT) && !isUNPCKLMask(M, VT, HasInt256))
6844    return getMOVLowToHigh(Op, dl, DAG, HasSSE2);
6845
6846  if (isMOVHLPSMask(M, VT))
6847    return getMOVHighToLow(Op, dl, DAG);
6848
6849  if (V2IsUndef && isMOVSHDUPMask(M, VT, Subtarget))
6850    return getTargetShuffleNode(X86ISD::MOVSHDUP, dl, VT, V1, DAG);
6851
6852  if (V2IsUndef && isMOVSLDUPMask(M, VT, Subtarget))
6853    return getTargetShuffleNode(X86ISD::MOVSLDUP, dl, VT, V1, DAG);
6854
6855  if (isMOVLPMask(M, VT))
6856    return getMOVLP(Op, dl, DAG, HasSSE2);
6857
6858  if (ShouldXformToMOVHLPS(M, VT) ||
6859      ShouldXformToMOVLP(V1.getNode(), V2.getNode(), M, VT))
6860    return CommuteVectorShuffle(SVOp, DAG);
6861
6862  if (isShift) {
6863    // No better options. Use a vshldq / vsrldq.
6864    EVT EltVT = VT.getVectorElementType();
6865    ShAmt *= EltVT.getSizeInBits();
6866    return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
6867  }
6868
6869  bool Commuted = false;
6870  // FIXME: This should also accept a bitcast of a splat?  Be careful, not
6871  // 1,1,1,1 -> v8i16 though.
6872  V1IsSplat = isSplatVector(V1.getNode());
6873  V2IsSplat = isSplatVector(V2.getNode());
6874
6875  // Canonicalize the splat or undef, if present, to be on the RHS.
6876  if (!V2IsUndef && V1IsSplat && !V2IsSplat) {
6877    CommuteVectorShuffleMask(M, NumElems);
6878    std::swap(V1, V2);
6879    std::swap(V1IsSplat, V2IsSplat);
6880    Commuted = true;
6881  }
6882
6883  if (isCommutedMOVLMask(M, VT, V2IsSplat, V2IsUndef)) {
6884    // Shuffling low element of v1 into undef, just return v1.
6885    if (V2IsUndef)
6886      return V1;
6887    // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
6888    // the instruction selector will not match, so get a canonical MOVL with
6889    // swapped operands to undo the commute.
6890    return getMOVL(DAG, dl, VT, V2, V1);
6891  }
6892
6893  if (isUNPCKLMask(M, VT, HasInt256))
6894    return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
6895
6896  if (isUNPCKHMask(M, VT, HasInt256))
6897    return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
6898
6899  if (V2IsSplat) {
6900    // Normalize mask so all entries that point to V2 points to its first
6901    // element then try to match unpck{h|l} again. If match, return a
6902    // new vector_shuffle with the corrected mask.p
6903    SmallVector<int, 8> NewMask(M.begin(), M.end());
6904    NormalizeMask(NewMask, NumElems);
6905    if (isUNPCKLMask(NewMask, VT, HasInt256, true))
6906      return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
6907    if (isUNPCKHMask(NewMask, VT, HasInt256, true))
6908      return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
6909  }
6910
6911  if (Commuted) {
6912    // Commute is back and try unpck* again.
6913    // FIXME: this seems wrong.
6914    CommuteVectorShuffleMask(M, NumElems);
6915    std::swap(V1, V2);
6916    std::swap(V1IsSplat, V2IsSplat);
6917    Commuted = false;
6918
6919    if (isUNPCKLMask(M, VT, HasInt256))
6920      return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
6921
6922    if (isUNPCKHMask(M, VT, HasInt256))
6923      return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
6924  }
6925
6926  // Normalize the node to match x86 shuffle ops if needed
6927  if (!V2IsUndef && (isSHUFPMask(M, VT, HasFp256, /* Commuted */ true)))
6928    return CommuteVectorShuffle(SVOp, DAG);
6929
6930  // The checks below are all present in isShuffleMaskLegal, but they are
6931  // inlined here right now to enable us to directly emit target specific
6932  // nodes, and remove one by one until they don't return Op anymore.
6933
6934  if (isPALIGNRMask(M, VT, Subtarget))
6935    return getTargetShuffleNode(X86ISD::PALIGN, dl, VT, V1, V2,
6936                                getShufflePALIGNRImmediate(SVOp),
6937                                DAG);
6938
6939  if (ShuffleVectorSDNode::isSplatMask(&M[0], VT) &&
6940      SVOp->getSplatIndex() == 0 && V2IsUndef) {
6941    if (VT == MVT::v2f64 || VT == MVT::v2i64)
6942      return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
6943  }
6944
6945  if (isPSHUFHWMask(M, VT, HasInt256))
6946    return getTargetShuffleNode(X86ISD::PSHUFHW, dl, VT, V1,
6947                                getShufflePSHUFHWImmediate(SVOp),
6948                                DAG);
6949
6950  if (isPSHUFLWMask(M, VT, HasInt256))
6951    return getTargetShuffleNode(X86ISD::PSHUFLW, dl, VT, V1,
6952                                getShufflePSHUFLWImmediate(SVOp),
6953                                DAG);
6954
6955  if (isSHUFPMask(M, VT, HasFp256))
6956    return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V2,
6957                                getShuffleSHUFImmediate(SVOp), DAG);
6958
6959  if (isUNPCKL_v_undef_Mask(M, VT, HasInt256))
6960    return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
6961  if (isUNPCKH_v_undef_Mask(M, VT, HasInt256))
6962    return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
6963
6964  //===--------------------------------------------------------------------===//
6965  // Generate target specific nodes for 128 or 256-bit shuffles only
6966  // supported in the AVX instruction set.
6967  //
6968
6969  // Handle VMOVDDUPY permutations
6970  if (V2IsUndef && isMOVDDUPYMask(M, VT, HasFp256))
6971    return getTargetShuffleNode(X86ISD::MOVDDUP, dl, VT, V1, DAG);
6972
6973  // Handle VPERMILPS/D* permutations
6974  if (isVPERMILPMask(M, VT, HasFp256)) {
6975    if (HasInt256 && VT == MVT::v8i32)
6976      return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1,
6977                                  getShuffleSHUFImmediate(SVOp), DAG);
6978    return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1,
6979                                getShuffleSHUFImmediate(SVOp), DAG);
6980  }
6981
6982  // Handle VPERM2F128/VPERM2I128 permutations
6983  if (isVPERM2X128Mask(M, VT, HasFp256))
6984    return getTargetShuffleNode(X86ISD::VPERM2X128, dl, VT, V1,
6985                                V2, getShuffleVPERM2X128Immediate(SVOp), DAG);
6986
6987  SDValue BlendOp = LowerVECTOR_SHUFFLEtoBlend(SVOp, Subtarget, DAG);
6988  if (BlendOp.getNode())
6989    return BlendOp;
6990
6991  if (V2IsUndef && HasInt256 && (VT == MVT::v8i32 || VT == MVT::v8f32)) {
6992    SmallVector<SDValue, 8> permclMask;
6993    for (unsigned i = 0; i != 8; ++i) {
6994      permclMask.push_back(DAG.getConstant((M[i]>=0) ? M[i] : 0, MVT::i32));
6995    }
6996    SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32,
6997                               &permclMask[0], 8);
6998    // Bitcast is for VPERMPS since mask is v8i32 but node takes v8f32
6999    return DAG.getNode(X86ISD::VPERMV, dl, VT,
7000                       DAG.getNode(ISD::BITCAST, dl, VT, Mask), V1);
7001  }
7002
7003  if (V2IsUndef && HasInt256 && (VT == MVT::v4i64 || VT == MVT::v4f64))
7004    return getTargetShuffleNode(X86ISD::VPERMI, dl, VT, V1,
7005                                getShuffleCLImmediate(SVOp), DAG);
7006
7007  //===--------------------------------------------------------------------===//
7008  // Since no target specific shuffle was selected for this generic one,
7009  // lower it into other known shuffles. FIXME: this isn't true yet, but
7010  // this is the plan.
7011  //
7012
7013  // Handle v8i16 specifically since SSE can do byte extraction and insertion.
7014  if (VT == MVT::v8i16) {
7015    SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(Op, Subtarget, DAG);
7016    if (NewOp.getNode())
7017      return NewOp;
7018  }
7019
7020  if (VT == MVT::v16i8) {
7021    SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, DAG, *this);
7022    if (NewOp.getNode())
7023      return NewOp;
7024  }
7025
7026  if (VT == MVT::v32i8) {
7027    SDValue NewOp = LowerVECTOR_SHUFFLEv32i8(SVOp, Subtarget, DAG);
7028    if (NewOp.getNode())
7029      return NewOp;
7030  }
7031
7032  // Handle all 128-bit wide vectors with 4 elements, and match them with
7033  // several different shuffle types.
7034  if (NumElems == 4 && VT.is128BitVector())
7035    return LowerVECTOR_SHUFFLE_128v4(SVOp, DAG);
7036
7037  // Handle general 256-bit shuffles
7038  if (VT.is256BitVector())
7039    return LowerVECTOR_SHUFFLE_256(SVOp, DAG);
7040
7041  return SDValue();
7042}
7043
7044SDValue
7045X86TargetLowering::LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op,
7046                                                SelectionDAG &DAG) const {
7047  EVT VT = Op.getValueType();
7048  DebugLoc dl = Op.getDebugLoc();
7049
7050  if (!Op.getOperand(0).getValueType().is128BitVector())
7051    return SDValue();
7052
7053  if (VT.getSizeInBits() == 8) {
7054    SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
7055                                  Op.getOperand(0), Op.getOperand(1));
7056    SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
7057                                  DAG.getValueType(VT));
7058    return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
7059  }
7060
7061  if (VT.getSizeInBits() == 16) {
7062    unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7063    // If Idx is 0, it's cheaper to do a move instead of a pextrw.
7064    if (Idx == 0)
7065      return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
7066                         DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
7067                                     DAG.getNode(ISD::BITCAST, dl,
7068                                                 MVT::v4i32,
7069                                                 Op.getOperand(0)),
7070                                     Op.getOperand(1)));
7071    SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
7072                                  Op.getOperand(0), Op.getOperand(1));
7073    SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
7074                                  DAG.getValueType(VT));
7075    return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
7076  }
7077
7078  if (VT == MVT::f32) {
7079    // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
7080    // the result back to FR32 register. It's only worth matching if the
7081    // result has a single use which is a store or a bitcast to i32.  And in
7082    // the case of a store, it's not worth it if the index is a constant 0,
7083    // because a MOVSSmr can be used instead, which is smaller and faster.
7084    if (!Op.hasOneUse())
7085      return SDValue();
7086    SDNode *User = *Op.getNode()->use_begin();
7087    if ((User->getOpcode() != ISD::STORE ||
7088         (isa<ConstantSDNode>(Op.getOperand(1)) &&
7089          cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
7090        (User->getOpcode() != ISD::BITCAST ||
7091         User->getValueType(0) != MVT::i32))
7092      return SDValue();
7093    SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
7094                                  DAG.getNode(ISD::BITCAST, dl, MVT::v4i32,
7095                                              Op.getOperand(0)),
7096                                              Op.getOperand(1));
7097    return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Extract);
7098  }
7099
7100  if (VT == MVT::i32 || VT == MVT::i64) {
7101    // ExtractPS/pextrq works with constant index.
7102    if (isa<ConstantSDNode>(Op.getOperand(1)))
7103      return Op;
7104  }
7105  return SDValue();
7106}
7107
7108SDValue
7109X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
7110                                           SelectionDAG &DAG) const {
7111  if (!isa<ConstantSDNode>(Op.getOperand(1)))
7112    return SDValue();
7113
7114  SDValue Vec = Op.getOperand(0);
7115  EVT VecVT = Vec.getValueType();
7116
7117  // If this is a 256-bit vector result, first extract the 128-bit vector and
7118  // then extract the element from the 128-bit vector.
7119  if (VecVT.is256BitVector()) {
7120    DebugLoc dl = Op.getNode()->getDebugLoc();
7121    unsigned NumElems = VecVT.getVectorNumElements();
7122    SDValue Idx = Op.getOperand(1);
7123    unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
7124
7125    // Get the 128-bit vector.
7126    Vec = Extract128BitVector(Vec, IdxVal, DAG, dl);
7127
7128    if (IdxVal >= NumElems/2)
7129      IdxVal -= NumElems/2;
7130    return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
7131                       DAG.getConstant(IdxVal, MVT::i32));
7132  }
7133
7134  assert(VecVT.is128BitVector() && "Unexpected vector length");
7135
7136  if (Subtarget->hasSSE41()) {
7137    SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
7138    if (Res.getNode())
7139      return Res;
7140  }
7141
7142  EVT VT = Op.getValueType();
7143  DebugLoc dl = Op.getDebugLoc();
7144  // TODO: handle v16i8.
7145  if (VT.getSizeInBits() == 16) {
7146    SDValue Vec = Op.getOperand(0);
7147    unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7148    if (Idx == 0)
7149      return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
7150                         DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
7151                                     DAG.getNode(ISD::BITCAST, dl,
7152                                                 MVT::v4i32, Vec),
7153                                     Op.getOperand(1)));
7154    // Transform it so it match pextrw which produces a 32-bit result.
7155    EVT EltVT = MVT::i32;
7156    SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
7157                                  Op.getOperand(0), Op.getOperand(1));
7158    SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
7159                                  DAG.getValueType(VT));
7160    return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
7161  }
7162
7163  if (VT.getSizeInBits() == 32) {
7164    unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7165    if (Idx == 0)
7166      return Op;
7167
7168    // SHUFPS the element to the lowest double word, then movss.
7169    int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
7170    EVT VVT = Op.getOperand(0).getValueType();
7171    SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
7172                                       DAG.getUNDEF(VVT), Mask);
7173    return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
7174                       DAG.getIntPtrConstant(0));
7175  }
7176
7177  if (VT.getSizeInBits() == 64) {
7178    // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
7179    // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
7180    //        to match extract_elt for f64.
7181    unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7182    if (Idx == 0)
7183      return Op;
7184
7185    // UNPCKHPD the element to the lowest double word, then movsd.
7186    // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
7187    // to a f64mem, the whole operation is folded into a single MOVHPDmr.
7188    int Mask[2] = { 1, -1 };
7189    EVT VVT = Op.getOperand(0).getValueType();
7190    SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
7191                                       DAG.getUNDEF(VVT), Mask);
7192    return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
7193                       DAG.getIntPtrConstant(0));
7194  }
7195
7196  return SDValue();
7197}
7198
7199SDValue
7200X86TargetLowering::LowerINSERT_VECTOR_ELT_SSE4(SDValue Op,
7201                                               SelectionDAG &DAG) const {
7202  EVT VT = Op.getValueType();
7203  EVT EltVT = VT.getVectorElementType();
7204  DebugLoc dl = Op.getDebugLoc();
7205
7206  SDValue N0 = Op.getOperand(0);
7207  SDValue N1 = Op.getOperand(1);
7208  SDValue N2 = Op.getOperand(2);
7209
7210  if (!VT.is128BitVector())
7211    return SDValue();
7212
7213  if ((EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) &&
7214      isa<ConstantSDNode>(N2)) {
7215    unsigned Opc;
7216    if (VT == MVT::v8i16)
7217      Opc = X86ISD::PINSRW;
7218    else if (VT == MVT::v16i8)
7219      Opc = X86ISD::PINSRB;
7220    else
7221      Opc = X86ISD::PINSRB;
7222
7223    // Transform it so it match pinsr{b,w} which expects a GR32 as its second
7224    // argument.
7225    if (N1.getValueType() != MVT::i32)
7226      N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
7227    if (N2.getValueType() != MVT::i32)
7228      N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
7229    return DAG.getNode(Opc, dl, VT, N0, N1, N2);
7230  }
7231
7232  if (EltVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
7233    // Bits [7:6] of the constant are the source select.  This will always be
7234    //  zero here.  The DAG Combiner may combine an extract_elt index into these
7235    //  bits.  For example (insert (extract, 3), 2) could be matched by putting
7236    //  the '3' into bits [7:6] of X86ISD::INSERTPS.
7237    // Bits [5:4] of the constant are the destination select.  This is the
7238    //  value of the incoming immediate.
7239    // Bits [3:0] of the constant are the zero mask.  The DAG Combiner may
7240    //   combine either bitwise AND or insert of float 0.0 to set these bits.
7241    N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
7242    // Create this as a scalar to vector..
7243    N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
7244    return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
7245  }
7246
7247  if ((EltVT == MVT::i32 || EltVT == MVT::i64) && isa<ConstantSDNode>(N2)) {
7248    // PINSR* works with constant index.
7249    return Op;
7250  }
7251  return SDValue();
7252}
7253
7254SDValue
7255X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) const {
7256  EVT VT = Op.getValueType();
7257  EVT EltVT = VT.getVectorElementType();
7258
7259  DebugLoc dl = Op.getDebugLoc();
7260  SDValue N0 = Op.getOperand(0);
7261  SDValue N1 = Op.getOperand(1);
7262  SDValue N2 = Op.getOperand(2);
7263
7264  // If this is a 256-bit vector result, first extract the 128-bit vector,
7265  // insert the element into the extracted half and then place it back.
7266  if (VT.is256BitVector()) {
7267    if (!isa<ConstantSDNode>(N2))
7268      return SDValue();
7269
7270    // Get the desired 128-bit vector half.
7271    unsigned NumElems = VT.getVectorNumElements();
7272    unsigned IdxVal = cast<ConstantSDNode>(N2)->getZExtValue();
7273    SDValue V = Extract128BitVector(N0, IdxVal, DAG, dl);
7274
7275    // Insert the element into the desired half.
7276    bool Upper = IdxVal >= NumElems/2;
7277    V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V, N1,
7278                 DAG.getConstant(Upper ? IdxVal-NumElems/2 : IdxVal, MVT::i32));
7279
7280    // Insert the changed part back to the 256-bit vector
7281    return Insert128BitVector(N0, V, IdxVal, DAG, dl);
7282  }
7283
7284  if (Subtarget->hasSSE41())
7285    return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
7286
7287  if (EltVT == MVT::i8)
7288    return SDValue();
7289
7290  if (EltVT.getSizeInBits() == 16 && isa<ConstantSDNode>(N2)) {
7291    // Transform it so it match pinsrw which expects a 16-bit value in a GR32
7292    // as its second argument.
7293    if (N1.getValueType() != MVT::i32)
7294      N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
7295    if (N2.getValueType() != MVT::i32)
7296      N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
7297    return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
7298  }
7299  return SDValue();
7300}
7301
7302static SDValue LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
7303  LLVMContext *Context = DAG.getContext();
7304  DebugLoc dl = Op.getDebugLoc();
7305  EVT OpVT = Op.getValueType();
7306
7307  // If this is a 256-bit vector result, first insert into a 128-bit
7308  // vector and then insert into the 256-bit vector.
7309  if (!OpVT.is128BitVector()) {
7310    // Insert into a 128-bit vector.
7311    EVT VT128 = EVT::getVectorVT(*Context,
7312                                 OpVT.getVectorElementType(),
7313                                 OpVT.getVectorNumElements() / 2);
7314
7315    Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
7316
7317    // Insert the 128-bit vector.
7318    return Insert128BitVector(DAG.getUNDEF(OpVT), Op, 0, DAG, dl);
7319  }
7320
7321  if (OpVT == MVT::v1i64 &&
7322      Op.getOperand(0).getValueType() == MVT::i64)
7323    return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
7324
7325  SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
7326  assert(OpVT.is128BitVector() && "Expected an SSE type!");
7327  return DAG.getNode(ISD::BITCAST, dl, OpVT,
7328                     DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,AnyExt));
7329}
7330
7331// Lower a node with an EXTRACT_SUBVECTOR opcode.  This may result in
7332// a simple subregister reference or explicit instructions to grab
7333// upper bits of a vector.
7334static SDValue LowerEXTRACT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
7335                                      SelectionDAG &DAG) {
7336  if (Subtarget->hasFp256()) {
7337    DebugLoc dl = Op.getNode()->getDebugLoc();
7338    SDValue Vec = Op.getNode()->getOperand(0);
7339    SDValue Idx = Op.getNode()->getOperand(1);
7340
7341    if (Op.getNode()->getValueType(0).is128BitVector() &&
7342        Vec.getNode()->getValueType(0).is256BitVector() &&
7343        isa<ConstantSDNode>(Idx)) {
7344      unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
7345      return Extract128BitVector(Vec, IdxVal, DAG, dl);
7346    }
7347  }
7348  return SDValue();
7349}
7350
7351// Lower a node with an INSERT_SUBVECTOR opcode.  This may result in a
7352// simple superregister reference or explicit instructions to insert
7353// the upper bits of a vector.
7354static SDValue LowerINSERT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
7355                                     SelectionDAG &DAG) {
7356  if (Subtarget->hasFp256()) {
7357    DebugLoc dl = Op.getNode()->getDebugLoc();
7358    SDValue Vec = Op.getNode()->getOperand(0);
7359    SDValue SubVec = Op.getNode()->getOperand(1);
7360    SDValue Idx = Op.getNode()->getOperand(2);
7361
7362    if (Op.getNode()->getValueType(0).is256BitVector() &&
7363        SubVec.getNode()->getValueType(0).is128BitVector() &&
7364        isa<ConstantSDNode>(Idx)) {
7365      unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
7366      return Insert128BitVector(Vec, SubVec, IdxVal, DAG, dl);
7367    }
7368  }
7369  return SDValue();
7370}
7371
7372// ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
7373// their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
7374// one of the above mentioned nodes. It has to be wrapped because otherwise
7375// Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
7376// be used to form addressing mode. These wrapped nodes will be selected
7377// into MOV32ri.
7378SDValue
7379X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
7380  ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
7381
7382  // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7383  // global base reg.
7384  unsigned char OpFlag = 0;
7385  unsigned WrapperKind = X86ISD::Wrapper;
7386  CodeModel::Model M = getTargetMachine().getCodeModel();
7387
7388  if (Subtarget->isPICStyleRIPRel() &&
7389      (M == CodeModel::Small || M == CodeModel::Kernel))
7390    WrapperKind = X86ISD::WrapperRIP;
7391  else if (Subtarget->isPICStyleGOT())
7392    OpFlag = X86II::MO_GOTOFF;
7393  else if (Subtarget->isPICStyleStubPIC())
7394    OpFlag = X86II::MO_PIC_BASE_OFFSET;
7395
7396  SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
7397                                             CP->getAlignment(),
7398                                             CP->getOffset(), OpFlag);
7399  DebugLoc DL = CP->getDebugLoc();
7400  Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7401  // With PIC, the address is actually $g + Offset.
7402  if (OpFlag) {
7403    Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7404                         DAG.getNode(X86ISD::GlobalBaseReg,
7405                                     DebugLoc(), getPointerTy()),
7406                         Result);
7407  }
7408
7409  return Result;
7410}
7411
7412SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
7413  JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
7414
7415  // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7416  // global base reg.
7417  unsigned char OpFlag = 0;
7418  unsigned WrapperKind = X86ISD::Wrapper;
7419  CodeModel::Model M = getTargetMachine().getCodeModel();
7420
7421  if (Subtarget->isPICStyleRIPRel() &&
7422      (M == CodeModel::Small || M == CodeModel::Kernel))
7423    WrapperKind = X86ISD::WrapperRIP;
7424  else if (Subtarget->isPICStyleGOT())
7425    OpFlag = X86II::MO_GOTOFF;
7426  else if (Subtarget->isPICStyleStubPIC())
7427    OpFlag = X86II::MO_PIC_BASE_OFFSET;
7428
7429  SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
7430                                          OpFlag);
7431  DebugLoc DL = JT->getDebugLoc();
7432  Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7433
7434  // With PIC, the address is actually $g + Offset.
7435  if (OpFlag)
7436    Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7437                         DAG.getNode(X86ISD::GlobalBaseReg,
7438                                     DebugLoc(), getPointerTy()),
7439                         Result);
7440
7441  return Result;
7442}
7443
7444SDValue
7445X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
7446  const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
7447
7448  // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7449  // global base reg.
7450  unsigned char OpFlag = 0;
7451  unsigned WrapperKind = X86ISD::Wrapper;
7452  CodeModel::Model M = getTargetMachine().getCodeModel();
7453
7454  if (Subtarget->isPICStyleRIPRel() &&
7455      (M == CodeModel::Small || M == CodeModel::Kernel)) {
7456    if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
7457      OpFlag = X86II::MO_GOTPCREL;
7458    WrapperKind = X86ISD::WrapperRIP;
7459  } else if (Subtarget->isPICStyleGOT()) {
7460    OpFlag = X86II::MO_GOT;
7461  } else if (Subtarget->isPICStyleStubPIC()) {
7462    OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
7463  } else if (Subtarget->isPICStyleStubNoDynamic()) {
7464    OpFlag = X86II::MO_DARWIN_NONLAZY;
7465  }
7466
7467  SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
7468
7469  DebugLoc DL = Op.getDebugLoc();
7470  Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7471
7472  // With PIC, the address is actually $g + Offset.
7473  if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
7474      !Subtarget->is64Bit()) {
7475    Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7476                         DAG.getNode(X86ISD::GlobalBaseReg,
7477                                     DebugLoc(), getPointerTy()),
7478                         Result);
7479  }
7480
7481  // For symbols that require a load from a stub to get the address, emit the
7482  // load.
7483  if (isGlobalStubReference(OpFlag))
7484    Result = DAG.getLoad(getPointerTy(), DL, DAG.getEntryNode(), Result,
7485                         MachinePointerInfo::getGOT(), false, false, false, 0);
7486
7487  return Result;
7488}
7489
7490SDValue
7491X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
7492  // Create the TargetBlockAddressAddress node.
7493  unsigned char OpFlags =
7494    Subtarget->ClassifyBlockAddressReference();
7495  CodeModel::Model M = getTargetMachine().getCodeModel();
7496  const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
7497  int64_t Offset = cast<BlockAddressSDNode>(Op)->getOffset();
7498  DebugLoc dl = Op.getDebugLoc();
7499  SDValue Result = DAG.getTargetBlockAddress(BA, getPointerTy(), Offset,
7500                                             OpFlags);
7501
7502  if (Subtarget->isPICStyleRIPRel() &&
7503      (M == CodeModel::Small || M == CodeModel::Kernel))
7504    Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
7505  else
7506    Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
7507
7508  // With PIC, the address is actually $g + Offset.
7509  if (isGlobalRelativeToPICBase(OpFlags)) {
7510    Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
7511                         DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
7512                         Result);
7513  }
7514
7515  return Result;
7516}
7517
7518SDValue
7519X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, DebugLoc dl,
7520                                      int64_t Offset,
7521                                      SelectionDAG &DAG) const {
7522  // Create the TargetGlobalAddress node, folding in the constant
7523  // offset if it is legal.
7524  unsigned char OpFlags =
7525    Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
7526  CodeModel::Model M = getTargetMachine().getCodeModel();
7527  SDValue Result;
7528  if (OpFlags == X86II::MO_NO_FLAG &&
7529      X86::isOffsetSuitableForCodeModel(Offset, M)) {
7530    // A direct static reference to a global.
7531    Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
7532    Offset = 0;
7533  } else {
7534    Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
7535  }
7536
7537  if (Subtarget->isPICStyleRIPRel() &&
7538      (M == CodeModel::Small || M == CodeModel::Kernel))
7539    Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
7540  else
7541    Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
7542
7543  // With PIC, the address is actually $g + Offset.
7544  if (isGlobalRelativeToPICBase(OpFlags)) {
7545    Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
7546                         DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
7547                         Result);
7548  }
7549
7550  // For globals that require a load from a stub to get the address, emit the
7551  // load.
7552  if (isGlobalStubReference(OpFlags))
7553    Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
7554                         MachinePointerInfo::getGOT(), false, false, false, 0);
7555
7556  // If there was a non-zero offset that we didn't fold, create an explicit
7557  // addition for it.
7558  if (Offset != 0)
7559    Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
7560                         DAG.getConstant(Offset, getPointerTy()));
7561
7562  return Result;
7563}
7564
7565SDValue
7566X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
7567  const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
7568  int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
7569  return LowerGlobalAddress(GV, Op.getDebugLoc(), Offset, DAG);
7570}
7571
7572static SDValue
7573GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
7574           SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
7575           unsigned char OperandFlags, bool LocalDynamic = false) {
7576  MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7577  SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7578  DebugLoc dl = GA->getDebugLoc();
7579  SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7580                                           GA->getValueType(0),
7581                                           GA->getOffset(),
7582                                           OperandFlags);
7583
7584  X86ISD::NodeType CallType = LocalDynamic ? X86ISD::TLSBASEADDR
7585                                           : X86ISD::TLSADDR;
7586
7587  if (InFlag) {
7588    SDValue Ops[] = { Chain,  TGA, *InFlag };
7589    Chain = DAG.getNode(CallType, dl, NodeTys, Ops, 3);
7590  } else {
7591    SDValue Ops[]  = { Chain, TGA };
7592    Chain = DAG.getNode(CallType, dl, NodeTys, Ops, 2);
7593  }
7594
7595  // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
7596  MFI->setAdjustsStack(true);
7597
7598  SDValue Flag = Chain.getValue(1);
7599  return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
7600}
7601
7602// Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
7603static SDValue
7604LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7605                                const EVT PtrVT) {
7606  SDValue InFlag;
7607  DebugLoc dl = GA->getDebugLoc();  // ? function entry point might be better
7608  SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
7609                                   DAG.getNode(X86ISD::GlobalBaseReg,
7610                                               DebugLoc(), PtrVT), InFlag);
7611  InFlag = Chain.getValue(1);
7612
7613  return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
7614}
7615
7616// Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
7617static SDValue
7618LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7619                                const EVT PtrVT) {
7620  return GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT,
7621                    X86::RAX, X86II::MO_TLSGD);
7622}
7623
7624static SDValue LowerToTLSLocalDynamicModel(GlobalAddressSDNode *GA,
7625                                           SelectionDAG &DAG,
7626                                           const EVT PtrVT,
7627                                           bool is64Bit) {
7628  DebugLoc dl = GA->getDebugLoc();
7629
7630  // Get the start address of the TLS block for this module.
7631  X86MachineFunctionInfo* MFI = DAG.getMachineFunction()
7632      .getInfo<X86MachineFunctionInfo>();
7633  MFI->incNumLocalDynamicTLSAccesses();
7634
7635  SDValue Base;
7636  if (is64Bit) {
7637    Base = GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT, X86::RAX,
7638                      X86II::MO_TLSLD, /*LocalDynamic=*/true);
7639  } else {
7640    SDValue InFlag;
7641    SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
7642        DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), PtrVT), InFlag);
7643    InFlag = Chain.getValue(1);
7644    Base = GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX,
7645                      X86II::MO_TLSLDM, /*LocalDynamic=*/true);
7646  }
7647
7648  // Note: the CleanupLocalDynamicTLSPass will remove redundant computations
7649  // of Base.
7650
7651  // Build x@dtpoff.
7652  unsigned char OperandFlags = X86II::MO_DTPOFF;
7653  unsigned WrapperKind = X86ISD::Wrapper;
7654  SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7655                                           GA->getValueType(0),
7656                                           GA->getOffset(), OperandFlags);
7657  SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
7658
7659  // Add x@dtpoff with the base.
7660  return DAG.getNode(ISD::ADD, dl, PtrVT, Offset, Base);
7661}
7662
7663// Lower ISD::GlobalTLSAddress using the "initial exec" or "local exec" model.
7664static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7665                                   const EVT PtrVT, TLSModel::Model model,
7666                                   bool is64Bit, bool isPIC) {
7667  DebugLoc dl = GA->getDebugLoc();
7668
7669  // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
7670  Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
7671                                                         is64Bit ? 257 : 256));
7672
7673  SDValue ThreadPointer = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
7674                                      DAG.getIntPtrConstant(0),
7675                                      MachinePointerInfo(Ptr),
7676                                      false, false, false, 0);
7677
7678  unsigned char OperandFlags = 0;
7679  // Most TLS accesses are not RIP relative, even on x86-64.  One exception is
7680  // initialexec.
7681  unsigned WrapperKind = X86ISD::Wrapper;
7682  if (model == TLSModel::LocalExec) {
7683    OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
7684  } else if (model == TLSModel::InitialExec) {
7685    if (is64Bit) {
7686      OperandFlags = X86II::MO_GOTTPOFF;
7687      WrapperKind = X86ISD::WrapperRIP;
7688    } else {
7689      OperandFlags = isPIC ? X86II::MO_GOTNTPOFF : X86II::MO_INDNTPOFF;
7690    }
7691  } else {
7692    llvm_unreachable("Unexpected model");
7693  }
7694
7695  // emit "addl x@ntpoff,%eax" (local exec)
7696  // or "addl x@indntpoff,%eax" (initial exec)
7697  // or "addl x@gotntpoff(%ebx) ,%eax" (initial exec, 32-bit pic)
7698  SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7699                                           GA->getValueType(0),
7700                                           GA->getOffset(), OperandFlags);
7701  SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
7702
7703  if (model == TLSModel::InitialExec) {
7704    if (isPIC && !is64Bit) {
7705      Offset = DAG.getNode(ISD::ADD, dl, PtrVT,
7706                          DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), PtrVT),
7707                           Offset);
7708    }
7709
7710    Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
7711                         MachinePointerInfo::getGOT(), false, false, false,
7712                         0);
7713  }
7714
7715  // The address of the thread local variable is the add of the thread
7716  // pointer with the offset of the variable.
7717  return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
7718}
7719
7720SDValue
7721X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
7722
7723  GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
7724  const GlobalValue *GV = GA->getGlobal();
7725
7726  if (Subtarget->isTargetELF()) {
7727    TLSModel::Model model = getTargetMachine().getTLSModel(GV);
7728
7729    switch (model) {
7730      case TLSModel::GeneralDynamic:
7731        if (Subtarget->is64Bit())
7732          return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
7733        return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
7734      case TLSModel::LocalDynamic:
7735        return LowerToTLSLocalDynamicModel(GA, DAG, getPointerTy(),
7736                                           Subtarget->is64Bit());
7737      case TLSModel::InitialExec:
7738      case TLSModel::LocalExec:
7739        return LowerToTLSExecModel(GA, DAG, getPointerTy(), model,
7740                                   Subtarget->is64Bit(),
7741                         getTargetMachine().getRelocationModel() == Reloc::PIC_);
7742    }
7743    llvm_unreachable("Unknown TLS model.");
7744  }
7745
7746  if (Subtarget->isTargetDarwin()) {
7747    // Darwin only has one model of TLS.  Lower to that.
7748    unsigned char OpFlag = 0;
7749    unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
7750                           X86ISD::WrapperRIP : X86ISD::Wrapper;
7751
7752    // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7753    // global base reg.
7754    bool PIC32 = (getTargetMachine().getRelocationModel() == Reloc::PIC_) &&
7755                  !Subtarget->is64Bit();
7756    if (PIC32)
7757      OpFlag = X86II::MO_TLVP_PIC_BASE;
7758    else
7759      OpFlag = X86II::MO_TLVP;
7760    DebugLoc DL = Op.getDebugLoc();
7761    SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
7762                                                GA->getValueType(0),
7763                                                GA->getOffset(), OpFlag);
7764    SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7765
7766    // With PIC32, the address is actually $g + Offset.
7767    if (PIC32)
7768      Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7769                           DAG.getNode(X86ISD::GlobalBaseReg,
7770                                       DebugLoc(), getPointerTy()),
7771                           Offset);
7772
7773    // Lowering the machine isd will make sure everything is in the right
7774    // location.
7775    SDValue Chain = DAG.getEntryNode();
7776    SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7777    SDValue Args[] = { Chain, Offset };
7778    Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args, 2);
7779
7780    // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
7781    MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7782    MFI->setAdjustsStack(true);
7783
7784    // And our return value (tls address) is in the standard call return value
7785    // location.
7786    unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
7787    return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy(),
7788                              Chain.getValue(1));
7789  }
7790
7791  if (Subtarget->isTargetWindows()) {
7792    // Just use the implicit TLS architecture
7793    // Need to generate someting similar to:
7794    //   mov     rdx, qword [gs:abs 58H]; Load pointer to ThreadLocalStorage
7795    //                                  ; from TEB
7796    //   mov     ecx, dword [rel _tls_index]: Load index (from C runtime)
7797    //   mov     rcx, qword [rdx+rcx*8]
7798    //   mov     eax, .tls$:tlsvar
7799    //   [rax+rcx] contains the address
7800    // Windows 64bit: gs:0x58
7801    // Windows 32bit: fs:__tls_array
7802
7803    // If GV is an alias then use the aliasee for determining
7804    // thread-localness.
7805    if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
7806      GV = GA->resolveAliasedGlobal(false);
7807    DebugLoc dl = GA->getDebugLoc();
7808    SDValue Chain = DAG.getEntryNode();
7809
7810    // Get the Thread Pointer, which is %fs:__tls_array (32-bit) or
7811    // %gs:0x58 (64-bit).
7812    Value *Ptr = Constant::getNullValue(Subtarget->is64Bit()
7813                                        ? Type::getInt8PtrTy(*DAG.getContext(),
7814                                                             256)
7815                                        : Type::getInt32PtrTy(*DAG.getContext(),
7816                                                              257));
7817
7818    SDValue ThreadPointer = DAG.getLoad(getPointerTy(), dl, Chain,
7819                                        Subtarget->is64Bit()
7820                                        ? DAG.getIntPtrConstant(0x58)
7821                                        : DAG.getExternalSymbol("_tls_array",
7822                                                                getPointerTy()),
7823                                        MachinePointerInfo(Ptr),
7824                                        false, false, false, 0);
7825
7826    // Load the _tls_index variable
7827    SDValue IDX = DAG.getExternalSymbol("_tls_index", getPointerTy());
7828    if (Subtarget->is64Bit())
7829      IDX = DAG.getExtLoad(ISD::ZEXTLOAD, dl, getPointerTy(), Chain,
7830                           IDX, MachinePointerInfo(), MVT::i32,
7831                           false, false, 0);
7832    else
7833      IDX = DAG.getLoad(getPointerTy(), dl, Chain, IDX, MachinePointerInfo(),
7834                        false, false, false, 0);
7835
7836    SDValue Scale = DAG.getConstant(Log2_64_Ceil(TD->getPointerSize()),
7837                                    getPointerTy());
7838    IDX = DAG.getNode(ISD::SHL, dl, getPointerTy(), IDX, Scale);
7839
7840    SDValue res = DAG.getNode(ISD::ADD, dl, getPointerTy(), ThreadPointer, IDX);
7841    res = DAG.getLoad(getPointerTy(), dl, Chain, res, MachinePointerInfo(),
7842                      false, false, false, 0);
7843
7844    // Get the offset of start of .tls section
7845    SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7846                                             GA->getValueType(0),
7847                                             GA->getOffset(), X86II::MO_SECREL);
7848    SDValue Offset = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), TGA);
7849
7850    // The address of the thread local variable is the add of the thread
7851    // pointer with the offset of the variable.
7852    return DAG.getNode(ISD::ADD, dl, getPointerTy(), res, Offset);
7853  }
7854
7855  llvm_unreachable("TLS not implemented for this target.");
7856}
7857
7858/// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values
7859/// and take a 2 x i32 value to shift plus a shift amount.
7860SDValue X86TargetLowering::LowerShiftParts(SDValue Op, SelectionDAG &DAG) const{
7861  assert(Op.getNumOperands() == 3 && "Not a double-shift!");
7862  EVT VT = Op.getValueType();
7863  unsigned VTBits = VT.getSizeInBits();
7864  DebugLoc dl = Op.getDebugLoc();
7865  bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
7866  SDValue ShOpLo = Op.getOperand(0);
7867  SDValue ShOpHi = Op.getOperand(1);
7868  SDValue ShAmt  = Op.getOperand(2);
7869  SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
7870                                     DAG.getConstant(VTBits - 1, MVT::i8))
7871                       : DAG.getConstant(0, VT);
7872
7873  SDValue Tmp2, Tmp3;
7874  if (Op.getOpcode() == ISD::SHL_PARTS) {
7875    Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
7876    Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
7877  } else {
7878    Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
7879    Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, ShAmt);
7880  }
7881
7882  SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
7883                                DAG.getConstant(VTBits, MVT::i8));
7884  SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
7885                             AndNode, DAG.getConstant(0, MVT::i8));
7886
7887  SDValue Hi, Lo;
7888  SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
7889  SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
7890  SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
7891
7892  if (Op.getOpcode() == ISD::SHL_PARTS) {
7893    Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
7894    Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
7895  } else {
7896    Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
7897    Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
7898  }
7899
7900  SDValue Ops[2] = { Lo, Hi };
7901  return DAG.getMergeValues(Ops, 2, dl);
7902}
7903
7904SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
7905                                           SelectionDAG &DAG) const {
7906  EVT SrcVT = Op.getOperand(0).getValueType();
7907
7908  if (SrcVT.isVector())
7909    return SDValue();
7910
7911  assert(SrcVT.getSimpleVT() <= MVT::i64 && SrcVT.getSimpleVT() >= MVT::i16 &&
7912         "Unknown SINT_TO_FP to lower!");
7913
7914  // These are really Legal; return the operand so the caller accepts it as
7915  // Legal.
7916  if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
7917    return Op;
7918  if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
7919      Subtarget->is64Bit()) {
7920    return Op;
7921  }
7922
7923  DebugLoc dl = Op.getDebugLoc();
7924  unsigned Size = SrcVT.getSizeInBits()/8;
7925  MachineFunction &MF = DAG.getMachineFunction();
7926  int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
7927  SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7928  SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
7929                               StackSlot,
7930                               MachinePointerInfo::getFixedStack(SSFI),
7931                               false, false, 0);
7932  return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
7933}
7934
7935SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
7936                                     SDValue StackSlot,
7937                                     SelectionDAG &DAG) const {
7938  // Build the FILD
7939  DebugLoc DL = Op.getDebugLoc();
7940  SDVTList Tys;
7941  bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
7942  if (useSSE)
7943    Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
7944  else
7945    Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
7946
7947  unsigned ByteSize = SrcVT.getSizeInBits()/8;
7948
7949  FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
7950  MachineMemOperand *MMO;
7951  if (FI) {
7952    int SSFI = FI->getIndex();
7953    MMO =
7954      DAG.getMachineFunction()
7955      .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7956                            MachineMemOperand::MOLoad, ByteSize, ByteSize);
7957  } else {
7958    MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
7959    StackSlot = StackSlot.getOperand(1);
7960  }
7961  SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
7962  SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
7963                                           X86ISD::FILD, DL,
7964                                           Tys, Ops, array_lengthof(Ops),
7965                                           SrcVT, MMO);
7966
7967  if (useSSE) {
7968    Chain = Result.getValue(1);
7969    SDValue InFlag = Result.getValue(2);
7970
7971    // FIXME: Currently the FST is flagged to the FILD_FLAG. This
7972    // shouldn't be necessary except that RFP cannot be live across
7973    // multiple blocks. When stackifier is fixed, they can be uncoupled.
7974    MachineFunction &MF = DAG.getMachineFunction();
7975    unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
7976    int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
7977    SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7978    Tys = DAG.getVTList(MVT::Other);
7979    SDValue Ops[] = {
7980      Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
7981    };
7982    MachineMemOperand *MMO =
7983      DAG.getMachineFunction()
7984      .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7985                            MachineMemOperand::MOStore, SSFISize, SSFISize);
7986
7987    Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
7988                                    Ops, array_lengthof(Ops),
7989                                    Op.getValueType(), MMO);
7990    Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
7991                         MachinePointerInfo::getFixedStack(SSFI),
7992                         false, false, false, 0);
7993  }
7994
7995  return Result;
7996}
7997
7998// LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
7999SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
8000                                               SelectionDAG &DAG) const {
8001  // This algorithm is not obvious. Here it is what we're trying to output:
8002  /*
8003     movq       %rax,  %xmm0
8004     punpckldq  (c0),  %xmm0  // c0: (uint4){ 0x43300000U, 0x45300000U, 0U, 0U }
8005     subpd      (c1),  %xmm0  // c1: (double2){ 0x1.0p52, 0x1.0p52 * 0x1.0p32 }
8006     #ifdef __SSE3__
8007       haddpd   %xmm0, %xmm0
8008     #else
8009       pshufd   $0x4e, %xmm0, %xmm1
8010       addpd    %xmm1, %xmm0
8011     #endif
8012  */
8013
8014  DebugLoc dl = Op.getDebugLoc();
8015  LLVMContext *Context = DAG.getContext();
8016
8017  // Build some magic constants.
8018  const uint32_t CV0[] = { 0x43300000, 0x45300000, 0, 0 };
8019  Constant *C0 = ConstantDataVector::get(*Context, CV0);
8020  SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
8021
8022  SmallVector<Constant*,2> CV1;
8023  CV1.push_back(
8024        ConstantFP::get(*Context, APFloat(APInt(64, 0x4330000000000000ULL))));
8025  CV1.push_back(
8026        ConstantFP::get(*Context, APFloat(APInt(64, 0x4530000000000000ULL))));
8027  Constant *C1 = ConstantVector::get(CV1);
8028  SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
8029
8030  // Load the 64-bit value into an XMM register.
8031  SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
8032                            Op.getOperand(0));
8033  SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
8034                              MachinePointerInfo::getConstantPool(),
8035                              false, false, false, 16);
8036  SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32,
8037                              DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, XR1),
8038                              CLod0);
8039
8040  SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
8041                              MachinePointerInfo::getConstantPool(),
8042                              false, false, false, 16);
8043  SDValue XR2F = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Unpck1);
8044  SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
8045  SDValue Result;
8046
8047  if (Subtarget->hasSSE3()) {
8048    // FIXME: The 'haddpd' instruction may be slower than 'movhlps + addsd'.
8049    Result = DAG.getNode(X86ISD::FHADD, dl, MVT::v2f64, Sub, Sub);
8050  } else {
8051    SDValue S2F = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Sub);
8052    SDValue Shuffle = getTargetShuffleNode(X86ISD::PSHUFD, dl, MVT::v4i32,
8053                                           S2F, 0x4E, DAG);
8054    Result = DAG.getNode(ISD::FADD, dl, MVT::v2f64,
8055                         DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Shuffle),
8056                         Sub);
8057  }
8058
8059  return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Result,
8060                     DAG.getIntPtrConstant(0));
8061}
8062
8063// LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
8064SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
8065                                               SelectionDAG &DAG) const {
8066  DebugLoc dl = Op.getDebugLoc();
8067  // FP constant to bias correct the final result.
8068  SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
8069                                   MVT::f64);
8070
8071  // Load the 32-bit value into an XMM register.
8072  SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
8073                             Op.getOperand(0));
8074
8075  // Zero out the upper parts of the register.
8076  Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget, DAG);
8077
8078  Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
8079                     DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Load),
8080                     DAG.getIntPtrConstant(0));
8081
8082  // Or the load with the bias.
8083  SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
8084                           DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
8085                                       DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
8086                                                   MVT::v2f64, Load)),
8087                           DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
8088                                       DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
8089                                                   MVT::v2f64, Bias)));
8090  Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
8091                   DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or),
8092                   DAG.getIntPtrConstant(0));
8093
8094  // Subtract the bias.
8095  SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
8096
8097  // Handle final rounding.
8098  EVT DestVT = Op.getValueType();
8099
8100  if (DestVT.bitsLT(MVT::f64))
8101    return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
8102                       DAG.getIntPtrConstant(0));
8103  if (DestVT.bitsGT(MVT::f64))
8104    return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
8105
8106  // Handle final rounding.
8107  return Sub;
8108}
8109
8110SDValue X86TargetLowering::lowerUINT_TO_FP_vec(SDValue Op,
8111                                               SelectionDAG &DAG) const {
8112  SDValue N0 = Op.getOperand(0);
8113  EVT SVT = N0.getValueType();
8114  DebugLoc dl = Op.getDebugLoc();
8115
8116  assert((SVT == MVT::v4i8 || SVT == MVT::v4i16 ||
8117          SVT == MVT::v8i8 || SVT == MVT::v8i16) &&
8118         "Custom UINT_TO_FP is not supported!");
8119
8120  EVT NVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, SVT.getVectorNumElements());
8121  return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
8122                     DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, N0));
8123}
8124
8125SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
8126                                           SelectionDAG &DAG) const {
8127  SDValue N0 = Op.getOperand(0);
8128  DebugLoc dl = Op.getDebugLoc();
8129
8130  if (Op.getValueType().isVector())
8131    return lowerUINT_TO_FP_vec(Op, DAG);
8132
8133  // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
8134  // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
8135  // the optimization here.
8136  if (DAG.SignBitIsZero(N0))
8137    return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
8138
8139  EVT SrcVT = N0.getValueType();
8140  EVT DstVT = Op.getValueType();
8141  if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
8142    return LowerUINT_TO_FP_i64(Op, DAG);
8143  if (SrcVT == MVT::i32 && X86ScalarSSEf64)
8144    return LowerUINT_TO_FP_i32(Op, DAG);
8145  if (Subtarget->is64Bit() && SrcVT == MVT::i64 && DstVT == MVT::f32)
8146    return SDValue();
8147
8148  // Make a 64-bit buffer, and use it to build an FILD.
8149  SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
8150  if (SrcVT == MVT::i32) {
8151    SDValue WordOff = DAG.getConstant(4, getPointerTy());
8152    SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
8153                                     getPointerTy(), StackSlot, WordOff);
8154    SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
8155                                  StackSlot, MachinePointerInfo(),
8156                                  false, false, 0);
8157    SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
8158                                  OffsetSlot, MachinePointerInfo(),
8159                                  false, false, 0);
8160    SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
8161    return Fild;
8162  }
8163
8164  assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
8165  SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
8166                               StackSlot, MachinePointerInfo(),
8167                               false, false, 0);
8168  // For i64 source, we need to add the appropriate power of 2 if the input
8169  // was negative.  This is the same as the optimization in
8170  // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
8171  // we must be careful to do the computation in x87 extended precision, not
8172  // in SSE. (The generic code can't know it's OK to do this, or how to.)
8173  int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
8174  MachineMemOperand *MMO =
8175    DAG.getMachineFunction()
8176    .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8177                          MachineMemOperand::MOLoad, 8, 8);
8178
8179  SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
8180  SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
8181  SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops, 3,
8182                                         MVT::i64, MMO);
8183
8184  APInt FF(32, 0x5F800000ULL);
8185
8186  // Check whether the sign bit is set.
8187  SDValue SignSet = DAG.getSetCC(dl, getSetCCResultType(MVT::i64),
8188                                 Op.getOperand(0), DAG.getConstant(0, MVT::i64),
8189                                 ISD::SETLT);
8190
8191  // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
8192  SDValue FudgePtr = DAG.getConstantPool(
8193                             ConstantInt::get(*DAG.getContext(), FF.zext(64)),
8194                                         getPointerTy());
8195
8196  // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
8197  SDValue Zero = DAG.getIntPtrConstant(0);
8198  SDValue Four = DAG.getIntPtrConstant(4);
8199  SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
8200                               Zero, Four);
8201  FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
8202
8203  // Load the value out, extending it from f32 to f80.
8204  // FIXME: Avoid the extend by constructing the right constant pool?
8205  SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(),
8206                                 FudgePtr, MachinePointerInfo::getConstantPool(),
8207                                 MVT::f32, false, false, 4);
8208  // Extend everything to 80 bits to force it to be done on x87.
8209  SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
8210  return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add, DAG.getIntPtrConstant(0));
8211}
8212
8213std::pair<SDValue,SDValue> X86TargetLowering::
8214FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG, bool IsSigned, bool IsReplace) const {
8215  DebugLoc DL = Op.getDebugLoc();
8216
8217  EVT DstTy = Op.getValueType();
8218
8219  if (!IsSigned && !isIntegerTypeFTOL(DstTy)) {
8220    assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
8221    DstTy = MVT::i64;
8222  }
8223
8224  assert(DstTy.getSimpleVT() <= MVT::i64 &&
8225         DstTy.getSimpleVT() >= MVT::i16 &&
8226         "Unknown FP_TO_INT to lower!");
8227
8228  // These are really Legal.
8229  if (DstTy == MVT::i32 &&
8230      isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
8231    return std::make_pair(SDValue(), SDValue());
8232  if (Subtarget->is64Bit() &&
8233      DstTy == MVT::i64 &&
8234      isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
8235    return std::make_pair(SDValue(), SDValue());
8236
8237  // We lower FP->int64 either into FISTP64 followed by a load from a temporary
8238  // stack slot, or into the FTOL runtime function.
8239  MachineFunction &MF = DAG.getMachineFunction();
8240  unsigned MemSize = DstTy.getSizeInBits()/8;
8241  int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
8242  SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8243
8244  unsigned Opc;
8245  if (!IsSigned && isIntegerTypeFTOL(DstTy))
8246    Opc = X86ISD::WIN_FTOL;
8247  else
8248    switch (DstTy.getSimpleVT().SimpleTy) {
8249    default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
8250    case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
8251    case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
8252    case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
8253    }
8254
8255  SDValue Chain = DAG.getEntryNode();
8256  SDValue Value = Op.getOperand(0);
8257  EVT TheVT = Op.getOperand(0).getValueType();
8258  // FIXME This causes a redundant load/store if the SSE-class value is already
8259  // in memory, such as if it is on the callstack.
8260  if (isScalarFPTypeInSSEReg(TheVT)) {
8261    assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
8262    Chain = DAG.getStore(Chain, DL, Value, StackSlot,
8263                         MachinePointerInfo::getFixedStack(SSFI),
8264                         false, false, 0);
8265    SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
8266    SDValue Ops[] = {
8267      Chain, StackSlot, DAG.getValueType(TheVT)
8268    };
8269
8270    MachineMemOperand *MMO =
8271      MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8272                              MachineMemOperand::MOLoad, MemSize, MemSize);
8273    Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, 3,
8274                                    DstTy, MMO);
8275    Chain = Value.getValue(1);
8276    SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
8277    StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8278  }
8279
8280  MachineMemOperand *MMO =
8281    MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8282                            MachineMemOperand::MOStore, MemSize, MemSize);
8283
8284  if (Opc != X86ISD::WIN_FTOL) {
8285    // Build the FP_TO_INT*_IN_MEM
8286    SDValue Ops[] = { Chain, Value, StackSlot };
8287    SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
8288                                           Ops, 3, DstTy, MMO);
8289    return std::make_pair(FIST, StackSlot);
8290  } else {
8291    SDValue ftol = DAG.getNode(X86ISD::WIN_FTOL, DL,
8292      DAG.getVTList(MVT::Other, MVT::Glue),
8293      Chain, Value);
8294    SDValue eax = DAG.getCopyFromReg(ftol, DL, X86::EAX,
8295      MVT::i32, ftol.getValue(1));
8296    SDValue edx = DAG.getCopyFromReg(eax.getValue(1), DL, X86::EDX,
8297      MVT::i32, eax.getValue(2));
8298    SDValue Ops[] = { eax, edx };
8299    SDValue pair = IsReplace
8300      ? DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops, 2)
8301      : DAG.getMergeValues(Ops, 2, DL);
8302    return std::make_pair(pair, SDValue());
8303  }
8304}
8305
8306static SDValue LowerAVXExtend(SDValue Op, SelectionDAG &DAG,
8307                              const X86Subtarget *Subtarget) {
8308  EVT VT = Op->getValueType(0);
8309  SDValue In = Op->getOperand(0);
8310  EVT InVT = In.getValueType();
8311  DebugLoc dl = Op->getDebugLoc();
8312
8313  // Optimize vectors in AVX mode:
8314  //
8315  //   v8i16 -> v8i32
8316  //   Use vpunpcklwd for 4 lower elements  v8i16 -> v4i32.
8317  //   Use vpunpckhwd for 4 upper elements  v8i16 -> v4i32.
8318  //   Concat upper and lower parts.
8319  //
8320  //   v4i32 -> v4i64
8321  //   Use vpunpckldq for 4 lower elements  v4i32 -> v2i64.
8322  //   Use vpunpckhdq for 4 upper elements  v4i32 -> v2i64.
8323  //   Concat upper and lower parts.
8324  //
8325
8326  if (((VT != MVT::v8i32) || (InVT != MVT::v8i16)) &&
8327      ((VT != MVT::v4i64) || (InVT != MVT::v4i32)))
8328    return SDValue();
8329
8330  if (Subtarget->hasInt256())
8331    return DAG.getNode(X86ISD::VZEXT_MOVL, dl, VT, In);
8332
8333  SDValue ZeroVec = getZeroVector(InVT, Subtarget, DAG, dl);
8334  SDValue Undef = DAG.getUNDEF(InVT);
8335  bool NeedZero = Op.getOpcode() == ISD::ZERO_EXTEND;
8336  SDValue OpLo = getUnpackl(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
8337  SDValue OpHi = getUnpackh(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
8338
8339  EVT HVT = EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(),
8340                             VT.getVectorNumElements()/2);
8341
8342  OpLo = DAG.getNode(ISD::BITCAST, dl, HVT, OpLo);
8343  OpHi = DAG.getNode(ISD::BITCAST, dl, HVT, OpHi);
8344
8345  return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
8346}
8347
8348SDValue X86TargetLowering::LowerANY_EXTEND(SDValue Op,
8349                                           SelectionDAG &DAG) const {
8350  if (Subtarget->hasFp256()) {
8351    SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
8352    if (Res.getNode())
8353      return Res;
8354  }
8355
8356  return SDValue();
8357}
8358SDValue X86TargetLowering::LowerZERO_EXTEND(SDValue Op,
8359                                            SelectionDAG &DAG) const {
8360  DebugLoc DL = Op.getDebugLoc();
8361  EVT VT = Op.getValueType();
8362  SDValue In = Op.getOperand(0);
8363  EVT SVT = In.getValueType();
8364
8365  if (Subtarget->hasFp256()) {
8366    SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
8367    if (Res.getNode())
8368      return Res;
8369  }
8370
8371  if (!VT.is256BitVector() || !SVT.is128BitVector() ||
8372      VT.getVectorNumElements() != SVT.getVectorNumElements())
8373    return SDValue();
8374
8375  assert(Subtarget->hasFp256() && "256-bit vector is observed without AVX!");
8376
8377  // AVX2 has better support of integer extending.
8378  if (Subtarget->hasInt256())
8379    return DAG.getNode(X86ISD::VZEXT, DL, VT, In);
8380
8381  SDValue Lo = DAG.getNode(X86ISD::VZEXT, DL, MVT::v4i32, In);
8382  static const int Mask[] = {4, 5, 6, 7, -1, -1, -1, -1};
8383  SDValue Hi = DAG.getNode(X86ISD::VZEXT, DL, MVT::v4i32,
8384                           DAG.getVectorShuffle(MVT::v8i16, DL, In,
8385                                                DAG.getUNDEF(MVT::v8i16),
8386                                                &Mask[0]));
8387
8388  return DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v8i32, Lo, Hi);
8389}
8390
8391SDValue X86TargetLowering::lowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
8392  DebugLoc DL = Op.getDebugLoc();
8393  EVT VT = Op.getValueType();
8394  SDValue In = Op.getOperand(0);
8395  EVT SVT = In.getValueType();
8396
8397  if ((VT == MVT::v4i32) && (SVT == MVT::v4i64)) {
8398    // On AVX2, v4i64 -> v4i32 becomes VPERMD.
8399    if (Subtarget->hasInt256()) {
8400      static const int ShufMask[] = {0, 2, 4, 6, -1, -1, -1, -1};
8401      In = DAG.getNode(ISD::BITCAST, DL, MVT::v8i32, In);
8402      In = DAG.getVectorShuffle(MVT::v8i32, DL, In, DAG.getUNDEF(MVT::v8i32),
8403                                ShufMask);
8404      return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, In,
8405                         DAG.getIntPtrConstant(0));
8406    }
8407
8408    // On AVX, v4i64 -> v4i32 becomes a sequence that uses PSHUFD and MOVLHPS.
8409    SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
8410                               DAG.getIntPtrConstant(0));
8411    SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
8412                               DAG.getIntPtrConstant(2));
8413
8414    OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
8415    OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
8416
8417    // The PSHUFD mask:
8418    static const int ShufMask1[] = {0, 2, 0, 0};
8419    SDValue Undef = DAG.getUNDEF(VT);
8420    OpLo = DAG.getVectorShuffle(VT, DL, OpLo, Undef, ShufMask1);
8421    OpHi = DAG.getVectorShuffle(VT, DL, OpHi, Undef, ShufMask1);
8422
8423    // The MOVLHPS mask:
8424    static const int ShufMask2[] = {0, 1, 4, 5};
8425    return DAG.getVectorShuffle(VT, DL, OpLo, OpHi, ShufMask2);
8426  }
8427
8428  if ((VT == MVT::v8i16) && (SVT == MVT::v8i32)) {
8429    // On AVX2, v8i32 -> v8i16 becomed PSHUFB.
8430    if (Subtarget->hasInt256()) {
8431      In = DAG.getNode(ISD::BITCAST, DL, MVT::v32i8, In);
8432
8433      SmallVector<SDValue,32> pshufbMask;
8434      for (unsigned i = 0; i < 2; ++i) {
8435        pshufbMask.push_back(DAG.getConstant(0x0, MVT::i8));
8436        pshufbMask.push_back(DAG.getConstant(0x1, MVT::i8));
8437        pshufbMask.push_back(DAG.getConstant(0x4, MVT::i8));
8438        pshufbMask.push_back(DAG.getConstant(0x5, MVT::i8));
8439        pshufbMask.push_back(DAG.getConstant(0x8, MVT::i8));
8440        pshufbMask.push_back(DAG.getConstant(0x9, MVT::i8));
8441        pshufbMask.push_back(DAG.getConstant(0xc, MVT::i8));
8442        pshufbMask.push_back(DAG.getConstant(0xd, MVT::i8));
8443        for (unsigned j = 0; j < 8; ++j)
8444          pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
8445      }
8446      SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8,
8447                               &pshufbMask[0], 32);
8448      In = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v32i8, In, BV);
8449      In = DAG.getNode(ISD::BITCAST, DL, MVT::v4i64, In);
8450
8451      static const int ShufMask[] = {0,  2,  -1,  -1};
8452      In = DAG.getVectorShuffle(MVT::v4i64, DL,  In, DAG.getUNDEF(MVT::v4i64),
8453                                &ShufMask[0]);
8454      In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
8455                       DAG.getIntPtrConstant(0));
8456      return DAG.getNode(ISD::BITCAST, DL, VT, In);
8457    }
8458
8459    SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
8460                               DAG.getIntPtrConstant(0));
8461
8462    SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
8463                               DAG.getIntPtrConstant(4));
8464
8465    OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpLo);
8466    OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpHi);
8467
8468    // The PSHUFB mask:
8469    static const int ShufMask1[] = {0,  1,  4,  5,  8,  9, 12, 13,
8470                                   -1, -1, -1, -1, -1, -1, -1, -1};
8471
8472    SDValue Undef = DAG.getUNDEF(MVT::v16i8);
8473    OpLo = DAG.getVectorShuffle(MVT::v16i8, DL, OpLo, Undef, ShufMask1);
8474    OpHi = DAG.getVectorShuffle(MVT::v16i8, DL, OpHi, Undef, ShufMask1);
8475
8476    OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
8477    OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
8478
8479    // The MOVLHPS Mask:
8480    static const int ShufMask2[] = {0, 1, 4, 5};
8481    SDValue res = DAG.getVectorShuffle(MVT::v4i32, DL, OpLo, OpHi, ShufMask2);
8482    return DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, res);
8483  }
8484
8485  // Handle truncation of V256 to V128 using shuffles.
8486  if (!VT.is128BitVector() || !SVT.is256BitVector())
8487    return SDValue();
8488
8489  assert(VT.getVectorNumElements() != SVT.getVectorNumElements() &&
8490         "Invalid op");
8491  assert(Subtarget->hasFp256() && "256-bit vector without AVX!");
8492
8493  unsigned NumElems = VT.getVectorNumElements();
8494  EVT NVT = EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(),
8495                             NumElems * 2);
8496
8497  SmallVector<int, 16> MaskVec(NumElems * 2, -1);
8498  // Prepare truncation shuffle mask
8499  for (unsigned i = 0; i != NumElems; ++i)
8500    MaskVec[i] = i * 2;
8501  SDValue V = DAG.getVectorShuffle(NVT, DL,
8502                                   DAG.getNode(ISD::BITCAST, DL, NVT, In),
8503                                   DAG.getUNDEF(NVT), &MaskVec[0]);
8504  return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V,
8505                     DAG.getIntPtrConstant(0));
8506}
8507
8508SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
8509                                           SelectionDAG &DAG) const {
8510  if (Op.getValueType().isVector()) {
8511    if (Op.getValueType() == MVT::v8i16)
8512      return DAG.getNode(ISD::TRUNCATE, Op.getDebugLoc(), Op.getValueType(),
8513                         DAG.getNode(ISD::FP_TO_SINT, Op.getDebugLoc(),
8514                                     MVT::v8i32, Op.getOperand(0)));
8515    return SDValue();
8516  }
8517
8518  std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
8519    /*IsSigned=*/ true, /*IsReplace=*/ false);
8520  SDValue FIST = Vals.first, StackSlot = Vals.second;
8521  // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
8522  if (FIST.getNode() == 0) return Op;
8523
8524  if (StackSlot.getNode())
8525    // Load the result.
8526    return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
8527                       FIST, StackSlot, MachinePointerInfo(),
8528                       false, false, false, 0);
8529
8530  // The node is the result.
8531  return FIST;
8532}
8533
8534SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
8535                                           SelectionDAG &DAG) const {
8536  std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
8537    /*IsSigned=*/ false, /*IsReplace=*/ false);
8538  SDValue FIST = Vals.first, StackSlot = Vals.second;
8539  assert(FIST.getNode() && "Unexpected failure");
8540
8541  if (StackSlot.getNode())
8542    // Load the result.
8543    return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
8544                       FIST, StackSlot, MachinePointerInfo(),
8545                       false, false, false, 0);
8546
8547  // The node is the result.
8548  return FIST;
8549}
8550
8551SDValue X86TargetLowering::lowerFP_EXTEND(SDValue Op,
8552                                          SelectionDAG &DAG) const {
8553  DebugLoc DL = Op.getDebugLoc();
8554  EVT VT = Op.getValueType();
8555  SDValue In = Op.getOperand(0);
8556  EVT SVT = In.getValueType();
8557
8558  assert(SVT == MVT::v2f32 && "Only customize MVT::v2f32 type legalization!");
8559
8560  return DAG.getNode(X86ISD::VFPEXT, DL, VT,
8561                     DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4f32,
8562                                 In, DAG.getUNDEF(SVT)));
8563}
8564
8565SDValue X86TargetLowering::LowerFABS(SDValue Op, SelectionDAG &DAG) const {
8566  LLVMContext *Context = DAG.getContext();
8567  DebugLoc dl = Op.getDebugLoc();
8568  EVT VT = Op.getValueType();
8569  EVT EltVT = VT;
8570  unsigned NumElts = VT == MVT::f64 ? 2 : 4;
8571  if (VT.isVector()) {
8572    EltVT = VT.getVectorElementType();
8573    NumElts = VT.getVectorNumElements();
8574  }
8575  Constant *C;
8576  if (EltVT == MVT::f64)
8577    C = ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63))));
8578  else
8579    C = ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31))));
8580  C = ConstantVector::getSplat(NumElts, C);
8581  SDValue CPIdx = DAG.getConstantPool(C, getPointerTy());
8582  unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
8583  SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8584                             MachinePointerInfo::getConstantPool(),
8585                             false, false, false, Alignment);
8586  if (VT.isVector()) {
8587    MVT ANDVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
8588    return DAG.getNode(ISD::BITCAST, dl, VT,
8589                       DAG.getNode(ISD::AND, dl, ANDVT,
8590                                   DAG.getNode(ISD::BITCAST, dl, ANDVT,
8591                                               Op.getOperand(0)),
8592                                   DAG.getNode(ISD::BITCAST, dl, ANDVT, Mask)));
8593  }
8594  return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
8595}
8596
8597SDValue X86TargetLowering::LowerFNEG(SDValue Op, SelectionDAG &DAG) const {
8598  LLVMContext *Context = DAG.getContext();
8599  DebugLoc dl = Op.getDebugLoc();
8600  EVT VT = Op.getValueType();
8601  EVT EltVT = VT;
8602  unsigned NumElts = VT == MVT::f64 ? 2 : 4;
8603  if (VT.isVector()) {
8604    EltVT = VT.getVectorElementType();
8605    NumElts = VT.getVectorNumElements();
8606  }
8607  Constant *C;
8608  if (EltVT == MVT::f64)
8609    C = ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63)));
8610  else
8611    C = ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31)));
8612  C = ConstantVector::getSplat(NumElts, C);
8613  SDValue CPIdx = DAG.getConstantPool(C, getPointerTy());
8614  unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
8615  SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8616                             MachinePointerInfo::getConstantPool(),
8617                             false, false, false, Alignment);
8618  if (VT.isVector()) {
8619    MVT XORVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
8620    return DAG.getNode(ISD::BITCAST, dl, VT,
8621                       DAG.getNode(ISD::XOR, dl, XORVT,
8622                                   DAG.getNode(ISD::BITCAST, dl, XORVT,
8623                                               Op.getOperand(0)),
8624                                   DAG.getNode(ISD::BITCAST, dl, XORVT, Mask)));
8625  }
8626
8627  return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
8628}
8629
8630SDValue X86TargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
8631  LLVMContext *Context = DAG.getContext();
8632  SDValue Op0 = Op.getOperand(0);
8633  SDValue Op1 = Op.getOperand(1);
8634  DebugLoc dl = Op.getDebugLoc();
8635  EVT VT = Op.getValueType();
8636  EVT SrcVT = Op1.getValueType();
8637
8638  // If second operand is smaller, extend it first.
8639  if (SrcVT.bitsLT(VT)) {
8640    Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
8641    SrcVT = VT;
8642  }
8643  // And if it is bigger, shrink it first.
8644  if (SrcVT.bitsGT(VT)) {
8645    Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
8646    SrcVT = VT;
8647  }
8648
8649  // At this point the operands and the result should have the same
8650  // type, and that won't be f80 since that is not custom lowered.
8651
8652  // First get the sign bit of second operand.
8653  SmallVector<Constant*,4> CV;
8654  if (SrcVT == MVT::f64) {
8655    CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63))));
8656    CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
8657  } else {
8658    CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31))));
8659    CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8660    CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8661    CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8662  }
8663  Constant *C = ConstantVector::get(CV);
8664  SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8665  SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
8666                              MachinePointerInfo::getConstantPool(),
8667                              false, false, false, 16);
8668  SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
8669
8670  // Shift sign bit right or left if the two operands have different types.
8671  if (SrcVT.bitsGT(VT)) {
8672    // Op0 is MVT::f32, Op1 is MVT::f64.
8673    SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
8674    SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
8675                          DAG.getConstant(32, MVT::i32));
8676    SignBit = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, SignBit);
8677    SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
8678                          DAG.getIntPtrConstant(0));
8679  }
8680
8681  // Clear first operand sign bit.
8682  CV.clear();
8683  if (VT == MVT::f64) {
8684    CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63)))));
8685    CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
8686  } else {
8687    CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31)))));
8688    CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8689    CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8690    CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8691  }
8692  C = ConstantVector::get(CV);
8693  CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8694  SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8695                              MachinePointerInfo::getConstantPool(),
8696                              false, false, false, 16);
8697  SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
8698
8699  // Or the value with the sign bit.
8700  return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
8701}
8702
8703static SDValue LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) {
8704  SDValue N0 = Op.getOperand(0);
8705  DebugLoc dl = Op.getDebugLoc();
8706  EVT VT = Op.getValueType();
8707
8708  // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
8709  SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
8710                                  DAG.getConstant(1, VT));
8711  return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, VT));
8712}
8713
8714// LowerVectorAllZeroTest - Check whether an OR'd tree is PTEST-able.
8715//
8716SDValue X86TargetLowering::LowerVectorAllZeroTest(SDValue Op, SelectionDAG &DAG) const {
8717  assert(Op.getOpcode() == ISD::OR && "Only check OR'd tree.");
8718
8719  if (!Subtarget->hasSSE41())
8720    return SDValue();
8721
8722  if (!Op->hasOneUse())
8723    return SDValue();
8724
8725  SDNode *N = Op.getNode();
8726  DebugLoc DL = N->getDebugLoc();
8727
8728  SmallVector<SDValue, 8> Opnds;
8729  DenseMap<SDValue, unsigned> VecInMap;
8730  EVT VT = MVT::Other;
8731
8732  // Recognize a special case where a vector is casted into wide integer to
8733  // test all 0s.
8734  Opnds.push_back(N->getOperand(0));
8735  Opnds.push_back(N->getOperand(1));
8736
8737  for (unsigned Slot = 0, e = Opnds.size(); Slot < e; ++Slot) {
8738    SmallVector<SDValue, 8>::const_iterator I = Opnds.begin() + Slot;
8739    // BFS traverse all OR'd operands.
8740    if (I->getOpcode() == ISD::OR) {
8741      Opnds.push_back(I->getOperand(0));
8742      Opnds.push_back(I->getOperand(1));
8743      // Re-evaluate the number of nodes to be traversed.
8744      e += 2; // 2 more nodes (LHS and RHS) are pushed.
8745      continue;
8746    }
8747
8748    // Quit if a non-EXTRACT_VECTOR_ELT
8749    if (I->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
8750      return SDValue();
8751
8752    // Quit if without a constant index.
8753    SDValue Idx = I->getOperand(1);
8754    if (!isa<ConstantSDNode>(Idx))
8755      return SDValue();
8756
8757    SDValue ExtractedFromVec = I->getOperand(0);
8758    DenseMap<SDValue, unsigned>::iterator M = VecInMap.find(ExtractedFromVec);
8759    if (M == VecInMap.end()) {
8760      VT = ExtractedFromVec.getValueType();
8761      // Quit if not 128/256-bit vector.
8762      if (!VT.is128BitVector() && !VT.is256BitVector())
8763        return SDValue();
8764      // Quit if not the same type.
8765      if (VecInMap.begin() != VecInMap.end() &&
8766          VT != VecInMap.begin()->first.getValueType())
8767        return SDValue();
8768      M = VecInMap.insert(std::make_pair(ExtractedFromVec, 0)).first;
8769    }
8770    M->second |= 1U << cast<ConstantSDNode>(Idx)->getZExtValue();
8771  }
8772
8773  assert((VT.is128BitVector() || VT.is256BitVector()) &&
8774         "Not extracted from 128-/256-bit vector.");
8775
8776  unsigned FullMask = (1U << VT.getVectorNumElements()) - 1U;
8777  SmallVector<SDValue, 8> VecIns;
8778
8779  for (DenseMap<SDValue, unsigned>::const_iterator
8780        I = VecInMap.begin(), E = VecInMap.end(); I != E; ++I) {
8781    // Quit if not all elements are used.
8782    if (I->second != FullMask)
8783      return SDValue();
8784    VecIns.push_back(I->first);
8785  }
8786
8787  EVT TestVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
8788
8789  // Cast all vectors into TestVT for PTEST.
8790  for (unsigned i = 0, e = VecIns.size(); i < e; ++i)
8791    VecIns[i] = DAG.getNode(ISD::BITCAST, DL, TestVT, VecIns[i]);
8792
8793  // If more than one full vectors are evaluated, OR them first before PTEST.
8794  for (unsigned Slot = 0, e = VecIns.size(); e - Slot > 1; Slot += 2, e += 1) {
8795    // Each iteration will OR 2 nodes and append the result until there is only
8796    // 1 node left, i.e. the final OR'd value of all vectors.
8797    SDValue LHS = VecIns[Slot];
8798    SDValue RHS = VecIns[Slot + 1];
8799    VecIns.push_back(DAG.getNode(ISD::OR, DL, TestVT, LHS, RHS));
8800  }
8801
8802  return DAG.getNode(X86ISD::PTEST, DL, MVT::i32,
8803                     VecIns.back(), VecIns.back());
8804}
8805
8806/// Emit nodes that will be selected as "test Op0,Op0", or something
8807/// equivalent.
8808SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC,
8809                                    SelectionDAG &DAG) const {
8810  DebugLoc dl = Op.getDebugLoc();
8811
8812  // CF and OF aren't always set the way we want. Determine which
8813  // of these we need.
8814  bool NeedCF = false;
8815  bool NeedOF = false;
8816  switch (X86CC) {
8817  default: break;
8818  case X86::COND_A: case X86::COND_AE:
8819  case X86::COND_B: case X86::COND_BE:
8820    NeedCF = true;
8821    break;
8822  case X86::COND_G: case X86::COND_GE:
8823  case X86::COND_L: case X86::COND_LE:
8824  case X86::COND_O: case X86::COND_NO:
8825    NeedOF = true;
8826    break;
8827  }
8828
8829  // See if we can use the EFLAGS value from the operand instead of
8830  // doing a separate TEST. TEST always sets OF and CF to 0, so unless
8831  // we prove that the arithmetic won't overflow, we can't use OF or CF.
8832  if (Op.getResNo() != 0 || NeedOF || NeedCF)
8833    // Emit a CMP with 0, which is the TEST pattern.
8834    return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
8835                       DAG.getConstant(0, Op.getValueType()));
8836
8837  unsigned Opcode = 0;
8838  unsigned NumOperands = 0;
8839
8840  // Truncate operations may prevent the merge of the SETCC instruction
8841  // and the arithmetic intruction before it. Attempt to truncate the operands
8842  // of the arithmetic instruction and use a reduced bit-width instruction.
8843  bool NeedTruncation = false;
8844  SDValue ArithOp = Op;
8845  if (Op->getOpcode() == ISD::TRUNCATE && Op->hasOneUse()) {
8846    SDValue Arith = Op->getOperand(0);
8847    // Both the trunc and the arithmetic op need to have one user each.
8848    if (Arith->hasOneUse())
8849      switch (Arith.getOpcode()) {
8850        default: break;
8851        case ISD::ADD:
8852        case ISD::SUB:
8853        case ISD::AND:
8854        case ISD::OR:
8855        case ISD::XOR: {
8856          NeedTruncation = true;
8857          ArithOp = Arith;
8858        }
8859      }
8860  }
8861
8862  // NOTICE: In the code below we use ArithOp to hold the arithmetic operation
8863  // which may be the result of a CAST.  We use the variable 'Op', which is the
8864  // non-casted variable when we check for possible users.
8865  switch (ArithOp.getOpcode()) {
8866  case ISD::ADD:
8867    // Due to an isel shortcoming, be conservative if this add is likely to be
8868    // selected as part of a load-modify-store instruction. When the root node
8869    // in a match is a store, isel doesn't know how to remap non-chain non-flag
8870    // uses of other nodes in the match, such as the ADD in this case. This
8871    // leads to the ADD being left around and reselected, with the result being
8872    // two adds in the output.  Alas, even if none our users are stores, that
8873    // doesn't prove we're O.K.  Ergo, if we have any parents that aren't
8874    // CopyToReg or SETCC, eschew INC/DEC.  A better fix seems to require
8875    // climbing the DAG back to the root, and it doesn't seem to be worth the
8876    // effort.
8877    for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
8878         UE = Op.getNode()->use_end(); UI != UE; ++UI)
8879      if (UI->getOpcode() != ISD::CopyToReg &&
8880          UI->getOpcode() != ISD::SETCC &&
8881          UI->getOpcode() != ISD::STORE)
8882        goto default_case;
8883
8884    if (ConstantSDNode *C =
8885        dyn_cast<ConstantSDNode>(ArithOp.getNode()->getOperand(1))) {
8886      // An add of one will be selected as an INC.
8887      if (C->getAPIntValue() == 1) {
8888        Opcode = X86ISD::INC;
8889        NumOperands = 1;
8890        break;
8891      }
8892
8893      // An add of negative one (subtract of one) will be selected as a DEC.
8894      if (C->getAPIntValue().isAllOnesValue()) {
8895        Opcode = X86ISD::DEC;
8896        NumOperands = 1;
8897        break;
8898      }
8899    }
8900
8901    // Otherwise use a regular EFLAGS-setting add.
8902    Opcode = X86ISD::ADD;
8903    NumOperands = 2;
8904    break;
8905  case ISD::AND: {
8906    // If the primary and result isn't used, don't bother using X86ISD::AND,
8907    // because a TEST instruction will be better.
8908    bool NonFlagUse = false;
8909    for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
8910           UE = Op.getNode()->use_end(); UI != UE; ++UI) {
8911      SDNode *User = *UI;
8912      unsigned UOpNo = UI.getOperandNo();
8913      if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
8914        // Look pass truncate.
8915        UOpNo = User->use_begin().getOperandNo();
8916        User = *User->use_begin();
8917      }
8918
8919      if (User->getOpcode() != ISD::BRCOND &&
8920          User->getOpcode() != ISD::SETCC &&
8921          !(User->getOpcode() == ISD::SELECT && UOpNo == 0)) {
8922        NonFlagUse = true;
8923        break;
8924      }
8925    }
8926
8927    if (!NonFlagUse)
8928      break;
8929  }
8930    // FALL THROUGH
8931  case ISD::SUB:
8932  case ISD::OR:
8933  case ISD::XOR:
8934    // Due to the ISEL shortcoming noted above, be conservative if this op is
8935    // likely to be selected as part of a load-modify-store instruction.
8936    for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
8937           UE = Op.getNode()->use_end(); UI != UE; ++UI)
8938      if (UI->getOpcode() == ISD::STORE)
8939        goto default_case;
8940
8941    // Otherwise use a regular EFLAGS-setting instruction.
8942    switch (ArithOp.getOpcode()) {
8943    default: llvm_unreachable("unexpected operator!");
8944    case ISD::SUB: Opcode = X86ISD::SUB; break;
8945    case ISD::XOR: Opcode = X86ISD::XOR; break;
8946    case ISD::AND: Opcode = X86ISD::AND; break;
8947    case ISD::OR: {
8948      if (!NeedTruncation && (X86CC == X86::COND_E || X86CC == X86::COND_NE)) {
8949        SDValue EFLAGS = LowerVectorAllZeroTest(Op, DAG);
8950        if (EFLAGS.getNode())
8951          return EFLAGS;
8952      }
8953      Opcode = X86ISD::OR;
8954      break;
8955    }
8956    }
8957
8958    NumOperands = 2;
8959    break;
8960  case X86ISD::ADD:
8961  case X86ISD::SUB:
8962  case X86ISD::INC:
8963  case X86ISD::DEC:
8964  case X86ISD::OR:
8965  case X86ISD::XOR:
8966  case X86ISD::AND:
8967    return SDValue(Op.getNode(), 1);
8968  default:
8969  default_case:
8970    break;
8971  }
8972
8973  // If we found that truncation is beneficial, perform the truncation and
8974  // update 'Op'.
8975  if (NeedTruncation) {
8976    EVT VT = Op.getValueType();
8977    SDValue WideVal = Op->getOperand(0);
8978    EVT WideVT = WideVal.getValueType();
8979    unsigned ConvertedOp = 0;
8980    // Use a target machine opcode to prevent further DAGCombine
8981    // optimizations that may separate the arithmetic operations
8982    // from the setcc node.
8983    switch (WideVal.getOpcode()) {
8984      default: break;
8985      case ISD::ADD: ConvertedOp = X86ISD::ADD; break;
8986      case ISD::SUB: ConvertedOp = X86ISD::SUB; break;
8987      case ISD::AND: ConvertedOp = X86ISD::AND; break;
8988      case ISD::OR:  ConvertedOp = X86ISD::OR;  break;
8989      case ISD::XOR: ConvertedOp = X86ISD::XOR; break;
8990    }
8991
8992    if (ConvertedOp) {
8993      const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8994      if (TLI.isOperationLegal(WideVal.getOpcode(), WideVT)) {
8995        SDValue V0 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(0));
8996        SDValue V1 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(1));
8997        Op = DAG.getNode(ConvertedOp, dl, VT, V0, V1);
8998      }
8999    }
9000  }
9001
9002  if (Opcode == 0)
9003    // Emit a CMP with 0, which is the TEST pattern.
9004    return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
9005                       DAG.getConstant(0, Op.getValueType()));
9006
9007  SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
9008  SmallVector<SDValue, 4> Ops;
9009  for (unsigned i = 0; i != NumOperands; ++i)
9010    Ops.push_back(Op.getOperand(i));
9011
9012  SDValue New = DAG.getNode(Opcode, dl, VTs, &Ops[0], NumOperands);
9013  DAG.ReplaceAllUsesWith(Op, New);
9014  return SDValue(New.getNode(), 1);
9015}
9016
9017/// Emit nodes that will be selected as "cmp Op0,Op1", or something
9018/// equivalent.
9019SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
9020                                   SelectionDAG &DAG) const {
9021  if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1))
9022    if (C->getAPIntValue() == 0)
9023      return EmitTest(Op0, X86CC, DAG);
9024
9025  DebugLoc dl = Op0.getDebugLoc();
9026  if ((Op0.getValueType() == MVT::i8 || Op0.getValueType() == MVT::i16 ||
9027       Op0.getValueType() == MVT::i32 || Op0.getValueType() == MVT::i64)) {
9028    // Use SUB instead of CMP to enable CSE between SUB and CMP.
9029    SDVTList VTs = DAG.getVTList(Op0.getValueType(), MVT::i32);
9030    SDValue Sub = DAG.getNode(X86ISD::SUB, dl, VTs,
9031                              Op0, Op1);
9032    return SDValue(Sub.getNode(), 1);
9033  }
9034  return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
9035}
9036
9037/// Convert a comparison if required by the subtarget.
9038SDValue X86TargetLowering::ConvertCmpIfNecessary(SDValue Cmp,
9039                                                 SelectionDAG &DAG) const {
9040  // If the subtarget does not support the FUCOMI instruction, floating-point
9041  // comparisons have to be converted.
9042  if (Subtarget->hasCMov() ||
9043      Cmp.getOpcode() != X86ISD::CMP ||
9044      !Cmp.getOperand(0).getValueType().isFloatingPoint() ||
9045      !Cmp.getOperand(1).getValueType().isFloatingPoint())
9046    return Cmp;
9047
9048  // The instruction selector will select an FUCOM instruction instead of
9049  // FUCOMI, which writes the comparison result to FPSW instead of EFLAGS. Hence
9050  // build an SDNode sequence that transfers the result from FPSW into EFLAGS:
9051  // (X86sahf (trunc (srl (X86fp_stsw (trunc (X86cmp ...)), 8))))
9052  DebugLoc dl = Cmp.getDebugLoc();
9053  SDValue TruncFPSW = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, Cmp);
9054  SDValue FNStSW = DAG.getNode(X86ISD::FNSTSW16r, dl, MVT::i16, TruncFPSW);
9055  SDValue Srl = DAG.getNode(ISD::SRL, dl, MVT::i16, FNStSW,
9056                            DAG.getConstant(8, MVT::i8));
9057  SDValue TruncSrl = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Srl);
9058  return DAG.getNode(X86ISD::SAHF, dl, MVT::i32, TruncSrl);
9059}
9060
9061static bool isAllOnes(SDValue V) {
9062  ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
9063  return C && C->isAllOnesValue();
9064}
9065
9066/// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
9067/// if it's possible.
9068SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
9069                                     DebugLoc dl, SelectionDAG &DAG) const {
9070  SDValue Op0 = And.getOperand(0);
9071  SDValue Op1 = And.getOperand(1);
9072  if (Op0.getOpcode() == ISD::TRUNCATE)
9073    Op0 = Op0.getOperand(0);
9074  if (Op1.getOpcode() == ISD::TRUNCATE)
9075    Op1 = Op1.getOperand(0);
9076
9077  SDValue LHS, RHS;
9078  if (Op1.getOpcode() == ISD::SHL)
9079    std::swap(Op0, Op1);
9080  if (Op0.getOpcode() == ISD::SHL) {
9081    if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
9082      if (And00C->getZExtValue() == 1) {
9083        // If we looked past a truncate, check that it's only truncating away
9084        // known zeros.
9085        unsigned BitWidth = Op0.getValueSizeInBits();
9086        unsigned AndBitWidth = And.getValueSizeInBits();
9087        if (BitWidth > AndBitWidth) {
9088          APInt Zeros, Ones;
9089          DAG.ComputeMaskedBits(Op0, Zeros, Ones);
9090          if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
9091            return SDValue();
9092        }
9093        LHS = Op1;
9094        RHS = Op0.getOperand(1);
9095      }
9096  } else if (Op1.getOpcode() == ISD::Constant) {
9097    ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
9098    uint64_t AndRHSVal = AndRHS->getZExtValue();
9099    SDValue AndLHS = Op0;
9100
9101    if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) {
9102      LHS = AndLHS.getOperand(0);
9103      RHS = AndLHS.getOperand(1);
9104    }
9105
9106    // Use BT if the immediate can't be encoded in a TEST instruction.
9107    if (!isUInt<32>(AndRHSVal) && isPowerOf2_64(AndRHSVal)) {
9108      LHS = AndLHS;
9109      RHS = DAG.getConstant(Log2_64_Ceil(AndRHSVal), LHS.getValueType());
9110    }
9111  }
9112
9113  if (LHS.getNode()) {
9114    // If the LHS is of the form (x ^ -1) then replace the LHS with x and flip
9115    // the condition code later.
9116    bool Invert = false;
9117    if (LHS.getOpcode() == ISD::XOR && isAllOnes(LHS.getOperand(1))) {
9118      Invert = true;
9119      LHS = LHS.getOperand(0);
9120    }
9121
9122    // If LHS is i8, promote it to i32 with any_extend.  There is no i8 BT
9123    // instruction.  Since the shift amount is in-range-or-undefined, we know
9124    // that doing a bittest on the i32 value is ok.  We extend to i32 because
9125    // the encoding for the i16 version is larger than the i32 version.
9126    // Also promote i16 to i32 for performance / code size reason.
9127    if (LHS.getValueType() == MVT::i8 ||
9128        LHS.getValueType() == MVT::i16)
9129      LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
9130
9131    // If the operand types disagree, extend the shift amount to match.  Since
9132    // BT ignores high bits (like shifts) we can use anyextend.
9133    if (LHS.getValueType() != RHS.getValueType())
9134      RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
9135
9136    SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
9137    X86::CondCode Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
9138    // Flip the condition if the LHS was a not instruction
9139    if (Invert)
9140      Cond = X86::GetOppositeBranchCondition(Cond);
9141    return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
9142                       DAG.getConstant(Cond, MVT::i8), BT);
9143  }
9144
9145  return SDValue();
9146}
9147
9148SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
9149
9150  if (Op.getValueType().isVector()) return LowerVSETCC(Op, DAG);
9151
9152  assert(Op.getValueType() == MVT::i8 && "SetCC type must be 8-bit integer");
9153  SDValue Op0 = Op.getOperand(0);
9154  SDValue Op1 = Op.getOperand(1);
9155  DebugLoc dl = Op.getDebugLoc();
9156  ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
9157
9158  // Optimize to BT if possible.
9159  // Lower (X & (1 << N)) == 0 to BT(X, N).
9160  // Lower ((X >>u N) & 1) != 0 to BT(X, N).
9161  // Lower ((X >>s N) & 1) != 0 to BT(X, N).
9162  if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
9163      Op1.getOpcode() == ISD::Constant &&
9164      cast<ConstantSDNode>(Op1)->isNullValue() &&
9165      (CC == ISD::SETEQ || CC == ISD::SETNE)) {
9166    SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
9167    if (NewSetCC.getNode())
9168      return NewSetCC;
9169  }
9170
9171  // Look for X == 0, X == 1, X != 0, or X != 1.  We can simplify some forms of
9172  // these.
9173  if (Op1.getOpcode() == ISD::Constant &&
9174      (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
9175       cast<ConstantSDNode>(Op1)->isNullValue()) &&
9176      (CC == ISD::SETEQ || CC == ISD::SETNE)) {
9177
9178    // If the input is a setcc, then reuse the input setcc or use a new one with
9179    // the inverted condition.
9180    if (Op0.getOpcode() == X86ISD::SETCC) {
9181      X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
9182      bool Invert = (CC == ISD::SETNE) ^
9183        cast<ConstantSDNode>(Op1)->isNullValue();
9184      if (!Invert) return Op0;
9185
9186      CCode = X86::GetOppositeBranchCondition(CCode);
9187      return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
9188                         DAG.getConstant(CCode, MVT::i8), Op0.getOperand(1));
9189    }
9190  }
9191
9192  bool isFP = Op1.getValueType().isFloatingPoint();
9193  unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
9194  if (X86CC == X86::COND_INVALID)
9195    return SDValue();
9196
9197  SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, DAG);
9198  EFLAGS = ConvertCmpIfNecessary(EFLAGS, DAG);
9199  return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
9200                     DAG.getConstant(X86CC, MVT::i8), EFLAGS);
9201}
9202
9203// Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
9204// ones, and then concatenate the result back.
9205static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
9206  EVT VT = Op.getValueType();
9207
9208  assert(VT.is256BitVector() && Op.getOpcode() == ISD::SETCC &&
9209         "Unsupported value type for operation");
9210
9211  unsigned NumElems = VT.getVectorNumElements();
9212  DebugLoc dl = Op.getDebugLoc();
9213  SDValue CC = Op.getOperand(2);
9214
9215  // Extract the LHS vectors
9216  SDValue LHS = Op.getOperand(0);
9217  SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
9218  SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
9219
9220  // Extract the RHS vectors
9221  SDValue RHS = Op.getOperand(1);
9222  SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
9223  SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
9224
9225  // Issue the operation on the smaller types and concatenate the result back
9226  MVT EltVT = VT.getVectorElementType().getSimpleVT();
9227  EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
9228  return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
9229                     DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
9230                     DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
9231}
9232
9233SDValue X86TargetLowering::LowerVSETCC(SDValue Op, SelectionDAG &DAG) const {
9234  SDValue Cond;
9235  SDValue Op0 = Op.getOperand(0);
9236  SDValue Op1 = Op.getOperand(1);
9237  SDValue CC = Op.getOperand(2);
9238  EVT VT = Op.getValueType();
9239  ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
9240  bool isFP = Op.getOperand(1).getValueType().isFloatingPoint();
9241  DebugLoc dl = Op.getDebugLoc();
9242
9243  if (isFP) {
9244#ifndef NDEBUG
9245    EVT EltVT = Op0.getValueType().getVectorElementType();
9246    assert(EltVT == MVT::f32 || EltVT == MVT::f64);
9247#endif
9248
9249    unsigned SSECC;
9250    bool Swap = false;
9251
9252    // SSE Condition code mapping:
9253    //  0 - EQ
9254    //  1 - LT
9255    //  2 - LE
9256    //  3 - UNORD
9257    //  4 - NEQ
9258    //  5 - NLT
9259    //  6 - NLE
9260    //  7 - ORD
9261    switch (SetCCOpcode) {
9262    default: llvm_unreachable("Unexpected SETCC condition");
9263    case ISD::SETOEQ:
9264    case ISD::SETEQ:  SSECC = 0; break;
9265    case ISD::SETOGT:
9266    case ISD::SETGT: Swap = true; // Fallthrough
9267    case ISD::SETLT:
9268    case ISD::SETOLT: SSECC = 1; break;
9269    case ISD::SETOGE:
9270    case ISD::SETGE: Swap = true; // Fallthrough
9271    case ISD::SETLE:
9272    case ISD::SETOLE: SSECC = 2; break;
9273    case ISD::SETUO:  SSECC = 3; break;
9274    case ISD::SETUNE:
9275    case ISD::SETNE:  SSECC = 4; break;
9276    case ISD::SETULE: Swap = true; // Fallthrough
9277    case ISD::SETUGE: SSECC = 5; break;
9278    case ISD::SETULT: Swap = true; // Fallthrough
9279    case ISD::SETUGT: SSECC = 6; break;
9280    case ISD::SETO:   SSECC = 7; break;
9281    case ISD::SETUEQ:
9282    case ISD::SETONE: SSECC = 8; break;
9283    }
9284    if (Swap)
9285      std::swap(Op0, Op1);
9286
9287    // In the two special cases we can't handle, emit two comparisons.
9288    if (SSECC == 8) {
9289      unsigned CC0, CC1;
9290      unsigned CombineOpc;
9291      if (SetCCOpcode == ISD::SETUEQ) {
9292        CC0 = 3; CC1 = 0; CombineOpc = ISD::OR;
9293      } else {
9294        assert(SetCCOpcode == ISD::SETONE);
9295        CC0 = 7; CC1 = 4; CombineOpc = ISD::AND;
9296      }
9297
9298      SDValue Cmp0 = DAG.getNode(X86ISD::CMPP, dl, VT, Op0, Op1,
9299                                 DAG.getConstant(CC0, MVT::i8));
9300      SDValue Cmp1 = DAG.getNode(X86ISD::CMPP, dl, VT, Op0, Op1,
9301                                 DAG.getConstant(CC1, MVT::i8));
9302      return DAG.getNode(CombineOpc, dl, VT, Cmp0, Cmp1);
9303    }
9304    // Handle all other FP comparisons here.
9305    return DAG.getNode(X86ISD::CMPP, dl, VT, Op0, Op1,
9306                       DAG.getConstant(SSECC, MVT::i8));
9307  }
9308
9309  // Break 256-bit integer vector compare into smaller ones.
9310  if (VT.is256BitVector() && !Subtarget->hasInt256())
9311    return Lower256IntVSETCC(Op, DAG);
9312
9313  // We are handling one of the integer comparisons here.  Since SSE only has
9314  // GT and EQ comparisons for integer, swapping operands and multiple
9315  // operations may be required for some comparisons.
9316  unsigned Opc;
9317  bool Swap = false, Invert = false, FlipSigns = false;
9318
9319  switch (SetCCOpcode) {
9320  default: llvm_unreachable("Unexpected SETCC condition");
9321  case ISD::SETNE:  Invert = true;
9322  case ISD::SETEQ:  Opc = X86ISD::PCMPEQ; break;
9323  case ISD::SETLT:  Swap = true;
9324  case ISD::SETGT:  Opc = X86ISD::PCMPGT; break;
9325  case ISD::SETGE:  Swap = true;
9326  case ISD::SETLE:  Opc = X86ISD::PCMPGT; Invert = true; break;
9327  case ISD::SETULT: Swap = true;
9328  case ISD::SETUGT: Opc = X86ISD::PCMPGT; FlipSigns = true; break;
9329  case ISD::SETUGE: Swap = true;
9330  case ISD::SETULE: Opc = X86ISD::PCMPGT; FlipSigns = true; Invert = true; break;
9331  }
9332  if (Swap)
9333    std::swap(Op0, Op1);
9334
9335  // Check that the operation in question is available (most are plain SSE2,
9336  // but PCMPGTQ and PCMPEQQ have different requirements).
9337  if (VT == MVT::v2i64) {
9338    if (Opc == X86ISD::PCMPGT && !Subtarget->hasSSE42())
9339      return SDValue();
9340    if (Opc == X86ISD::PCMPEQ && !Subtarget->hasSSE41()) {
9341      // If pcmpeqq is missing but pcmpeqd is available synthesize pcmpeqq with
9342      // pcmpeqd + pshufd + pand.
9343      assert(Subtarget->hasSSE2() && !FlipSigns && "Don't know how to lower!");
9344
9345      // First cast everything to the right type,
9346      Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
9347      Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
9348
9349      // Do the compare.
9350      SDValue Result = DAG.getNode(Opc, dl, MVT::v4i32, Op0, Op1);
9351
9352      // Make sure the lower and upper halves are both all-ones.
9353      const int Mask[] = { 1, 0, 3, 2 };
9354      SDValue Shuf = DAG.getVectorShuffle(MVT::v4i32, dl, Result, Result, Mask);
9355      Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, Result, Shuf);
9356
9357      if (Invert)
9358        Result = DAG.getNOT(dl, Result, MVT::v4i32);
9359
9360      return DAG.getNode(ISD::BITCAST, dl, VT, Result);
9361    }
9362  }
9363
9364  // Since SSE has no unsigned integer comparisons, we need to flip  the sign
9365  // bits of the inputs before performing those operations.
9366  if (FlipSigns) {
9367    EVT EltVT = VT.getVectorElementType();
9368    SDValue SignBit = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()),
9369                                      EltVT);
9370    std::vector<SDValue> SignBits(VT.getVectorNumElements(), SignBit);
9371    SDValue SignVec = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &SignBits[0],
9372                                    SignBits.size());
9373    Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SignVec);
9374    Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SignVec);
9375  }
9376
9377  SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
9378
9379  // If the logical-not of the result is required, perform that now.
9380  if (Invert)
9381    Result = DAG.getNOT(dl, Result, VT);
9382
9383  return Result;
9384}
9385
9386// isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
9387static bool isX86LogicalCmp(SDValue Op) {
9388  unsigned Opc = Op.getNode()->getOpcode();
9389  if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI ||
9390      Opc == X86ISD::SAHF)
9391    return true;
9392  if (Op.getResNo() == 1 &&
9393      (Opc == X86ISD::ADD ||
9394       Opc == X86ISD::SUB ||
9395       Opc == X86ISD::ADC ||
9396       Opc == X86ISD::SBB ||
9397       Opc == X86ISD::SMUL ||
9398       Opc == X86ISD::UMUL ||
9399       Opc == X86ISD::INC ||
9400       Opc == X86ISD::DEC ||
9401       Opc == X86ISD::OR ||
9402       Opc == X86ISD::XOR ||
9403       Opc == X86ISD::AND))
9404    return true;
9405
9406  if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
9407    return true;
9408
9409  return false;
9410}
9411
9412static bool isZero(SDValue V) {
9413  ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
9414  return C && C->isNullValue();
9415}
9416
9417static bool isTruncWithZeroHighBitsInput(SDValue V, SelectionDAG &DAG) {
9418  if (V.getOpcode() != ISD::TRUNCATE)
9419    return false;
9420
9421  SDValue VOp0 = V.getOperand(0);
9422  unsigned InBits = VOp0.getValueSizeInBits();
9423  unsigned Bits = V.getValueSizeInBits();
9424  return DAG.MaskedValueIsZero(VOp0, APInt::getHighBitsSet(InBits,InBits-Bits));
9425}
9426
9427SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
9428  bool addTest = true;
9429  SDValue Cond  = Op.getOperand(0);
9430  SDValue Op1 = Op.getOperand(1);
9431  SDValue Op2 = Op.getOperand(2);
9432  DebugLoc DL = Op.getDebugLoc();
9433  SDValue CC;
9434
9435  if (Cond.getOpcode() == ISD::SETCC) {
9436    SDValue NewCond = LowerSETCC(Cond, DAG);
9437    if (NewCond.getNode())
9438      Cond = NewCond;
9439  }
9440
9441  // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
9442  // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
9443  // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
9444  // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
9445  if (Cond.getOpcode() == X86ISD::SETCC &&
9446      Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
9447      isZero(Cond.getOperand(1).getOperand(1))) {
9448    SDValue Cmp = Cond.getOperand(1);
9449
9450    unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
9451
9452    if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
9453        (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
9454      SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
9455
9456      SDValue CmpOp0 = Cmp.getOperand(0);
9457      // Apply further optimizations for special cases
9458      // (select (x != 0), -1, 0) -> neg & sbb
9459      // (select (x == 0), 0, -1) -> neg & sbb
9460      if (ConstantSDNode *YC = dyn_cast<ConstantSDNode>(Y))
9461        if (YC->isNullValue() &&
9462            (isAllOnes(Op1) == (CondCode == X86::COND_NE))) {
9463          SDVTList VTs = DAG.getVTList(CmpOp0.getValueType(), MVT::i32);
9464          SDValue Neg = DAG.getNode(X86ISD::SUB, DL, VTs,
9465                                    DAG.getConstant(0, CmpOp0.getValueType()),
9466                                    CmpOp0);
9467          SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
9468                                    DAG.getConstant(X86::COND_B, MVT::i8),
9469                                    SDValue(Neg.getNode(), 1));
9470          return Res;
9471        }
9472
9473      Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
9474                        CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
9475      Cmp = ConvertCmpIfNecessary(Cmp, DAG);
9476
9477      SDValue Res =   // Res = 0 or -1.
9478        DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
9479                    DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
9480
9481      if (isAllOnes(Op1) != (CondCode == X86::COND_E))
9482        Res = DAG.getNOT(DL, Res, Res.getValueType());
9483
9484      ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
9485      if (N2C == 0 || !N2C->isNullValue())
9486        Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
9487      return Res;
9488    }
9489  }
9490
9491  // Look past (and (setcc_carry (cmp ...)), 1).
9492  if (Cond.getOpcode() == ISD::AND &&
9493      Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
9494    ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
9495    if (C && C->getAPIntValue() == 1)
9496      Cond = Cond.getOperand(0);
9497  }
9498
9499  // If condition flag is set by a X86ISD::CMP, then use it as the condition
9500  // setting operand in place of the X86ISD::SETCC.
9501  unsigned CondOpcode = Cond.getOpcode();
9502  if (CondOpcode == X86ISD::SETCC ||
9503      CondOpcode == X86ISD::SETCC_CARRY) {
9504    CC = Cond.getOperand(0);
9505
9506    SDValue Cmp = Cond.getOperand(1);
9507    unsigned Opc = Cmp.getOpcode();
9508    EVT VT = Op.getValueType();
9509
9510    bool IllegalFPCMov = false;
9511    if (VT.isFloatingPoint() && !VT.isVector() &&
9512        !isScalarFPTypeInSSEReg(VT))  // FPStack?
9513      IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
9514
9515    if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
9516        Opc == X86ISD::BT) { // FIXME
9517      Cond = Cmp;
9518      addTest = false;
9519    }
9520  } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
9521             CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
9522             ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
9523              Cond.getOperand(0).getValueType() != MVT::i8)) {
9524    SDValue LHS = Cond.getOperand(0);
9525    SDValue RHS = Cond.getOperand(1);
9526    unsigned X86Opcode;
9527    unsigned X86Cond;
9528    SDVTList VTs;
9529    switch (CondOpcode) {
9530    case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
9531    case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
9532    case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
9533    case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
9534    case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
9535    case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
9536    default: llvm_unreachable("unexpected overflowing operator");
9537    }
9538    if (CondOpcode == ISD::UMULO)
9539      VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
9540                          MVT::i32);
9541    else
9542      VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
9543
9544    SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS);
9545
9546    if (CondOpcode == ISD::UMULO)
9547      Cond = X86Op.getValue(2);
9548    else
9549      Cond = X86Op.getValue(1);
9550
9551    CC = DAG.getConstant(X86Cond, MVT::i8);
9552    addTest = false;
9553  }
9554
9555  if (addTest) {
9556    // Look pass the truncate if the high bits are known zero.
9557    if (isTruncWithZeroHighBitsInput(Cond, DAG))
9558        Cond = Cond.getOperand(0);
9559
9560    // We know the result of AND is compared against zero. Try to match
9561    // it to BT.
9562    if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
9563      SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
9564      if (NewSetCC.getNode()) {
9565        CC = NewSetCC.getOperand(0);
9566        Cond = NewSetCC.getOperand(1);
9567        addTest = false;
9568      }
9569    }
9570  }
9571
9572  if (addTest) {
9573    CC = DAG.getConstant(X86::COND_NE, MVT::i8);
9574    Cond = EmitTest(Cond, X86::COND_NE, DAG);
9575  }
9576
9577  // a <  b ? -1 :  0 -> RES = ~setcc_carry
9578  // a <  b ?  0 : -1 -> RES = setcc_carry
9579  // a >= b ? -1 :  0 -> RES = setcc_carry
9580  // a >= b ?  0 : -1 -> RES = ~setcc_carry
9581  if (Cond.getOpcode() == X86ISD::SUB) {
9582    Cond = ConvertCmpIfNecessary(Cond, DAG);
9583    unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
9584
9585    if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
9586        (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
9587      SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
9588                                DAG.getConstant(X86::COND_B, MVT::i8), Cond);
9589      if (isAllOnes(Op1) != (CondCode == X86::COND_B))
9590        return DAG.getNOT(DL, Res, Res.getValueType());
9591      return Res;
9592    }
9593  }
9594
9595  // X86 doesn't have an i8 cmov. If both operands are the result of a truncate
9596  // widen the cmov and push the truncate through. This avoids introducing a new
9597  // branch during isel and doesn't add any extensions.
9598  if (Op.getValueType() == MVT::i8 &&
9599      Op1.getOpcode() == ISD::TRUNCATE && Op2.getOpcode() == ISD::TRUNCATE) {
9600    SDValue T1 = Op1.getOperand(0), T2 = Op2.getOperand(0);
9601    if (T1.getValueType() == T2.getValueType() &&
9602        // Blacklist CopyFromReg to avoid partial register stalls.
9603        T1.getOpcode() != ISD::CopyFromReg && T2.getOpcode()!=ISD::CopyFromReg){
9604      SDVTList VTs = DAG.getVTList(T1.getValueType(), MVT::Glue);
9605      SDValue Cmov = DAG.getNode(X86ISD::CMOV, DL, VTs, T2, T1, CC, Cond);
9606      return DAG.getNode(ISD::TRUNCATE, DL, Op.getValueType(), Cmov);
9607    }
9608  }
9609
9610  // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
9611  // condition is true.
9612  SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
9613  SDValue Ops[] = { Op2, Op1, CC, Cond };
9614  return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops, array_lengthof(Ops));
9615}
9616
9617SDValue X86TargetLowering::LowerSIGN_EXTEND(SDValue Op,
9618                                            SelectionDAG &DAG) const {
9619  EVT VT = Op->getValueType(0);
9620  SDValue In = Op->getOperand(0);
9621  EVT InVT = In.getValueType();
9622  DebugLoc dl = Op->getDebugLoc();
9623
9624  if ((VT != MVT::v4i64 || InVT != MVT::v4i32) &&
9625      (VT != MVT::v8i32 || InVT != MVT::v8i16))
9626    return SDValue();
9627
9628  if (Subtarget->hasInt256())
9629    return DAG.getNode(X86ISD::VSEXT_MOVL, dl, VT, In);
9630
9631  // Optimize vectors in AVX mode
9632  // Sign extend  v8i16 to v8i32 and
9633  //              v4i32 to v4i64
9634  //
9635  // Divide input vector into two parts
9636  // for v4i32 the shuffle mask will be { 0, 1, -1, -1} {2, 3, -1, -1}
9637  // use vpmovsx instruction to extend v4i32 -> v2i64; v8i16 -> v4i32
9638  // concat the vectors to original VT
9639
9640  unsigned NumElems = InVT.getVectorNumElements();
9641  SDValue Undef = DAG.getUNDEF(InVT);
9642
9643  SmallVector<int,8> ShufMask1(NumElems, -1);
9644  for (unsigned i = 0; i != NumElems/2; ++i)
9645    ShufMask1[i] = i;
9646
9647  SDValue OpLo = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask1[0]);
9648
9649  SmallVector<int,8> ShufMask2(NumElems, -1);
9650  for (unsigned i = 0; i != NumElems/2; ++i)
9651    ShufMask2[i] = i + NumElems/2;
9652
9653  SDValue OpHi = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask2[0]);
9654
9655  EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), VT.getScalarType(),
9656                                VT.getVectorNumElements()/2);
9657
9658  OpLo = DAG.getNode(X86ISD::VSEXT_MOVL, dl, HalfVT, OpLo);
9659  OpHi = DAG.getNode(X86ISD::VSEXT_MOVL, dl, HalfVT, OpHi);
9660
9661  return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
9662}
9663
9664// isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
9665// ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
9666// from the AND / OR.
9667static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
9668  Opc = Op.getOpcode();
9669  if (Opc != ISD::OR && Opc != ISD::AND)
9670    return false;
9671  return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
9672          Op.getOperand(0).hasOneUse() &&
9673          Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
9674          Op.getOperand(1).hasOneUse());
9675}
9676
9677// isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
9678// 1 and that the SETCC node has a single use.
9679static bool isXor1OfSetCC(SDValue Op) {
9680  if (Op.getOpcode() != ISD::XOR)
9681    return false;
9682  ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
9683  if (N1C && N1C->getAPIntValue() == 1) {
9684    return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
9685      Op.getOperand(0).hasOneUse();
9686  }
9687  return false;
9688}
9689
9690SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
9691  bool addTest = true;
9692  SDValue Chain = Op.getOperand(0);
9693  SDValue Cond  = Op.getOperand(1);
9694  SDValue Dest  = Op.getOperand(2);
9695  DebugLoc dl = Op.getDebugLoc();
9696  SDValue CC;
9697  bool Inverted = false;
9698
9699  if (Cond.getOpcode() == ISD::SETCC) {
9700    // Check for setcc([su]{add,sub,mul}o == 0).
9701    if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
9702        isa<ConstantSDNode>(Cond.getOperand(1)) &&
9703        cast<ConstantSDNode>(Cond.getOperand(1))->isNullValue() &&
9704        Cond.getOperand(0).getResNo() == 1 &&
9705        (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
9706         Cond.getOperand(0).getOpcode() == ISD::UADDO ||
9707         Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
9708         Cond.getOperand(0).getOpcode() == ISD::USUBO ||
9709         Cond.getOperand(0).getOpcode() == ISD::SMULO ||
9710         Cond.getOperand(0).getOpcode() == ISD::UMULO)) {
9711      Inverted = true;
9712      Cond = Cond.getOperand(0);
9713    } else {
9714      SDValue NewCond = LowerSETCC(Cond, DAG);
9715      if (NewCond.getNode())
9716        Cond = NewCond;
9717    }
9718  }
9719#if 0
9720  // FIXME: LowerXALUO doesn't handle these!!
9721  else if (Cond.getOpcode() == X86ISD::ADD  ||
9722           Cond.getOpcode() == X86ISD::SUB  ||
9723           Cond.getOpcode() == X86ISD::SMUL ||
9724           Cond.getOpcode() == X86ISD::UMUL)
9725    Cond = LowerXALUO(Cond, DAG);
9726#endif
9727
9728  // Look pass (and (setcc_carry (cmp ...)), 1).
9729  if (Cond.getOpcode() == ISD::AND &&
9730      Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
9731    ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
9732    if (C && C->getAPIntValue() == 1)
9733      Cond = Cond.getOperand(0);
9734  }
9735
9736  // If condition flag is set by a X86ISD::CMP, then use it as the condition
9737  // setting operand in place of the X86ISD::SETCC.
9738  unsigned CondOpcode = Cond.getOpcode();
9739  if (CondOpcode == X86ISD::SETCC ||
9740      CondOpcode == X86ISD::SETCC_CARRY) {
9741    CC = Cond.getOperand(0);
9742
9743    SDValue Cmp = Cond.getOperand(1);
9744    unsigned Opc = Cmp.getOpcode();
9745    // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
9746    if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
9747      Cond = Cmp;
9748      addTest = false;
9749    } else {
9750      switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
9751      default: break;
9752      case X86::COND_O:
9753      case X86::COND_B:
9754        // These can only come from an arithmetic instruction with overflow,
9755        // e.g. SADDO, UADDO.
9756        Cond = Cond.getNode()->getOperand(1);
9757        addTest = false;
9758        break;
9759      }
9760    }
9761  }
9762  CondOpcode = Cond.getOpcode();
9763  if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
9764      CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
9765      ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
9766       Cond.getOperand(0).getValueType() != MVT::i8)) {
9767    SDValue LHS = Cond.getOperand(0);
9768    SDValue RHS = Cond.getOperand(1);
9769    unsigned X86Opcode;
9770    unsigned X86Cond;
9771    SDVTList VTs;
9772    switch (CondOpcode) {
9773    case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
9774    case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
9775    case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
9776    case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
9777    case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
9778    case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
9779    default: llvm_unreachable("unexpected overflowing operator");
9780    }
9781    if (Inverted)
9782      X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond);
9783    if (CondOpcode == ISD::UMULO)
9784      VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
9785                          MVT::i32);
9786    else
9787      VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
9788
9789    SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS);
9790
9791    if (CondOpcode == ISD::UMULO)
9792      Cond = X86Op.getValue(2);
9793    else
9794      Cond = X86Op.getValue(1);
9795
9796    CC = DAG.getConstant(X86Cond, MVT::i8);
9797    addTest = false;
9798  } else {
9799    unsigned CondOpc;
9800    if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
9801      SDValue Cmp = Cond.getOperand(0).getOperand(1);
9802      if (CondOpc == ISD::OR) {
9803        // Also, recognize the pattern generated by an FCMP_UNE. We can emit
9804        // two branches instead of an explicit OR instruction with a
9805        // separate test.
9806        if (Cmp == Cond.getOperand(1).getOperand(1) &&
9807            isX86LogicalCmp(Cmp)) {
9808          CC = Cond.getOperand(0).getOperand(0);
9809          Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9810                              Chain, Dest, CC, Cmp);
9811          CC = Cond.getOperand(1).getOperand(0);
9812          Cond = Cmp;
9813          addTest = false;
9814        }
9815      } else { // ISD::AND
9816        // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
9817        // two branches instead of an explicit AND instruction with a
9818        // separate test. However, we only do this if this block doesn't
9819        // have a fall-through edge, because this requires an explicit
9820        // jmp when the condition is false.
9821        if (Cmp == Cond.getOperand(1).getOperand(1) &&
9822            isX86LogicalCmp(Cmp) &&
9823            Op.getNode()->hasOneUse()) {
9824          X86::CondCode CCode =
9825            (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
9826          CCode = X86::GetOppositeBranchCondition(CCode);
9827          CC = DAG.getConstant(CCode, MVT::i8);
9828          SDNode *User = *Op.getNode()->use_begin();
9829          // Look for an unconditional branch following this conditional branch.
9830          // We need this because we need to reverse the successors in order
9831          // to implement FCMP_OEQ.
9832          if (User->getOpcode() == ISD::BR) {
9833            SDValue FalseBB = User->getOperand(1);
9834            SDNode *NewBR =
9835              DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
9836            assert(NewBR == User);
9837            (void)NewBR;
9838            Dest = FalseBB;
9839
9840            Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9841                                Chain, Dest, CC, Cmp);
9842            X86::CondCode CCode =
9843              (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
9844            CCode = X86::GetOppositeBranchCondition(CCode);
9845            CC = DAG.getConstant(CCode, MVT::i8);
9846            Cond = Cmp;
9847            addTest = false;
9848          }
9849        }
9850      }
9851    } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
9852      // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
9853      // It should be transformed during dag combiner except when the condition
9854      // is set by a arithmetics with overflow node.
9855      X86::CondCode CCode =
9856        (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
9857      CCode = X86::GetOppositeBranchCondition(CCode);
9858      CC = DAG.getConstant(CCode, MVT::i8);
9859      Cond = Cond.getOperand(0).getOperand(1);
9860      addTest = false;
9861    } else if (Cond.getOpcode() == ISD::SETCC &&
9862               cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) {
9863      // For FCMP_OEQ, we can emit
9864      // two branches instead of an explicit AND instruction with a
9865      // separate test. However, we only do this if this block doesn't
9866      // have a fall-through edge, because this requires an explicit
9867      // jmp when the condition is false.
9868      if (Op.getNode()->hasOneUse()) {
9869        SDNode *User = *Op.getNode()->use_begin();
9870        // Look for an unconditional branch following this conditional branch.
9871        // We need this because we need to reverse the successors in order
9872        // to implement FCMP_OEQ.
9873        if (User->getOpcode() == ISD::BR) {
9874          SDValue FalseBB = User->getOperand(1);
9875          SDNode *NewBR =
9876            DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
9877          assert(NewBR == User);
9878          (void)NewBR;
9879          Dest = FalseBB;
9880
9881          SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
9882                                    Cond.getOperand(0), Cond.getOperand(1));
9883          Cmp = ConvertCmpIfNecessary(Cmp, DAG);
9884          CC = DAG.getConstant(X86::COND_NE, MVT::i8);
9885          Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9886                              Chain, Dest, CC, Cmp);
9887          CC = DAG.getConstant(X86::COND_P, MVT::i8);
9888          Cond = Cmp;
9889          addTest = false;
9890        }
9891      }
9892    } else if (Cond.getOpcode() == ISD::SETCC &&
9893               cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) {
9894      // For FCMP_UNE, we can emit
9895      // two branches instead of an explicit AND instruction with a
9896      // separate test. However, we only do this if this block doesn't
9897      // have a fall-through edge, because this requires an explicit
9898      // jmp when the condition is false.
9899      if (Op.getNode()->hasOneUse()) {
9900        SDNode *User = *Op.getNode()->use_begin();
9901        // Look for an unconditional branch following this conditional branch.
9902        // We need this because we need to reverse the successors in order
9903        // to implement FCMP_UNE.
9904        if (User->getOpcode() == ISD::BR) {
9905          SDValue FalseBB = User->getOperand(1);
9906          SDNode *NewBR =
9907            DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
9908          assert(NewBR == User);
9909          (void)NewBR;
9910
9911          SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
9912                                    Cond.getOperand(0), Cond.getOperand(1));
9913          Cmp = ConvertCmpIfNecessary(Cmp, DAG);
9914          CC = DAG.getConstant(X86::COND_NE, MVT::i8);
9915          Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9916                              Chain, Dest, CC, Cmp);
9917          CC = DAG.getConstant(X86::COND_NP, MVT::i8);
9918          Cond = Cmp;
9919          addTest = false;
9920          Dest = FalseBB;
9921        }
9922      }
9923    }
9924  }
9925
9926  if (addTest) {
9927    // Look pass the truncate if the high bits are known zero.
9928    if (isTruncWithZeroHighBitsInput(Cond, DAG))
9929        Cond = Cond.getOperand(0);
9930
9931    // We know the result of AND is compared against zero. Try to match
9932    // it to BT.
9933    if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
9934      SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
9935      if (NewSetCC.getNode()) {
9936        CC = NewSetCC.getOperand(0);
9937        Cond = NewSetCC.getOperand(1);
9938        addTest = false;
9939      }
9940    }
9941  }
9942
9943  if (addTest) {
9944    CC = DAG.getConstant(X86::COND_NE, MVT::i8);
9945    Cond = EmitTest(Cond, X86::COND_NE, DAG);
9946  }
9947  Cond = ConvertCmpIfNecessary(Cond, DAG);
9948  return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9949                     Chain, Dest, CC, Cond);
9950}
9951
9952// Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
9953// Calls to _alloca is needed to probe the stack when allocating more than 4k
9954// bytes in one go. Touching the stack at 4K increments is necessary to ensure
9955// that the guard pages used by the OS virtual memory manager are allocated in
9956// correct sequence.
9957SDValue
9958X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
9959                                           SelectionDAG &DAG) const {
9960  assert((Subtarget->isTargetCygMing() || Subtarget->isTargetWindows() ||
9961          getTargetMachine().Options.EnableSegmentedStacks) &&
9962         "This should be used only on Windows targets or when segmented stacks "
9963         "are being used");
9964  assert(!Subtarget->isTargetEnvMacho() && "Not implemented");
9965  DebugLoc dl = Op.getDebugLoc();
9966
9967  // Get the inputs.
9968  SDValue Chain = Op.getOperand(0);
9969  SDValue Size  = Op.getOperand(1);
9970  // FIXME: Ensure alignment here
9971
9972  bool Is64Bit = Subtarget->is64Bit();
9973  EVT SPTy = Is64Bit ? MVT::i64 : MVT::i32;
9974
9975  if (getTargetMachine().Options.EnableSegmentedStacks) {
9976    MachineFunction &MF = DAG.getMachineFunction();
9977    MachineRegisterInfo &MRI = MF.getRegInfo();
9978
9979    if (Is64Bit) {
9980      // The 64 bit implementation of segmented stacks needs to clobber both r10
9981      // r11. This makes it impossible to use it along with nested parameters.
9982      const Function *F = MF.getFunction();
9983
9984      for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
9985           I != E; ++I)
9986        if (I->hasNestAttr())
9987          report_fatal_error("Cannot use segmented stacks with functions that "
9988                             "have nested arguments.");
9989    }
9990
9991    const TargetRegisterClass *AddrRegClass =
9992      getRegClassFor(Subtarget->is64Bit() ? MVT::i64:MVT::i32);
9993    unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
9994    Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
9995    SDValue Value = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
9996                                DAG.getRegister(Vreg, SPTy));
9997    SDValue Ops1[2] = { Value, Chain };
9998    return DAG.getMergeValues(Ops1, 2, dl);
9999  } else {
10000    SDValue Flag;
10001    unsigned Reg = (Subtarget->is64Bit() ? X86::RAX : X86::EAX);
10002
10003    Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
10004    Flag = Chain.getValue(1);
10005    SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
10006
10007    Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
10008    Flag = Chain.getValue(1);
10009
10010    Chain = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
10011                               SPTy).getValue(1);
10012
10013    SDValue Ops1[2] = { Chain.getValue(0), Chain };
10014    return DAG.getMergeValues(Ops1, 2, dl);
10015  }
10016}
10017
10018SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
10019  MachineFunction &MF = DAG.getMachineFunction();
10020  X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
10021
10022  const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
10023  DebugLoc DL = Op.getDebugLoc();
10024
10025  if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
10026    // vastart just stores the address of the VarArgsFrameIndex slot into the
10027    // memory location argument.
10028    SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
10029                                   getPointerTy());
10030    return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
10031                        MachinePointerInfo(SV), false, false, 0);
10032  }
10033
10034  // __va_list_tag:
10035  //   gp_offset         (0 - 6 * 8)
10036  //   fp_offset         (48 - 48 + 8 * 16)
10037  //   overflow_arg_area (point to parameters coming in memory).
10038  //   reg_save_area
10039  SmallVector<SDValue, 8> MemOps;
10040  SDValue FIN = Op.getOperand(1);
10041  // Store gp_offset
10042  SDValue Store = DAG.getStore(Op.getOperand(0), DL,
10043                               DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
10044                                               MVT::i32),
10045                               FIN, MachinePointerInfo(SV), false, false, 0);
10046  MemOps.push_back(Store);
10047
10048  // Store fp_offset
10049  FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
10050                    FIN, DAG.getIntPtrConstant(4));
10051  Store = DAG.getStore(Op.getOperand(0), DL,
10052                       DAG.getConstant(FuncInfo->getVarArgsFPOffset(),
10053                                       MVT::i32),
10054                       FIN, MachinePointerInfo(SV, 4), false, false, 0);
10055  MemOps.push_back(Store);
10056
10057  // Store ptr to overflow_arg_area
10058  FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
10059                    FIN, DAG.getIntPtrConstant(4));
10060  SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
10061                                    getPointerTy());
10062  Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
10063                       MachinePointerInfo(SV, 8),
10064                       false, false, 0);
10065  MemOps.push_back(Store);
10066
10067  // Store ptr to reg_save_area.
10068  FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
10069                    FIN, DAG.getIntPtrConstant(8));
10070  SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
10071                                    getPointerTy());
10072  Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
10073                       MachinePointerInfo(SV, 16), false, false, 0);
10074  MemOps.push_back(Store);
10075  return DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
10076                     &MemOps[0], MemOps.size());
10077}
10078
10079SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
10080  assert(Subtarget->is64Bit() &&
10081         "LowerVAARG only handles 64-bit va_arg!");
10082  assert((Subtarget->isTargetLinux() ||
10083          Subtarget->isTargetDarwin()) &&
10084          "Unhandled target in LowerVAARG");
10085  assert(Op.getNode()->getNumOperands() == 4);
10086  SDValue Chain = Op.getOperand(0);
10087  SDValue SrcPtr = Op.getOperand(1);
10088  const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
10089  unsigned Align = Op.getConstantOperandVal(3);
10090  DebugLoc dl = Op.getDebugLoc();
10091
10092  EVT ArgVT = Op.getNode()->getValueType(0);
10093  Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
10094  uint32_t ArgSize = getDataLayout()->getTypeAllocSize(ArgTy);
10095  uint8_t ArgMode;
10096
10097  // Decide which area this value should be read from.
10098  // TODO: Implement the AMD64 ABI in its entirety. This simple
10099  // selection mechanism works only for the basic types.
10100  if (ArgVT == MVT::f80) {
10101    llvm_unreachable("va_arg for f80 not yet implemented");
10102  } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
10103    ArgMode = 2;  // Argument passed in XMM register. Use fp_offset.
10104  } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
10105    ArgMode = 1;  // Argument passed in GPR64 register(s). Use gp_offset.
10106  } else {
10107    llvm_unreachable("Unhandled argument type in LowerVAARG");
10108  }
10109
10110  if (ArgMode == 2) {
10111    // Sanity Check: Make sure using fp_offset makes sense.
10112    assert(!getTargetMachine().Options.UseSoftFloat &&
10113           !(DAG.getMachineFunction()
10114                .getFunction()->getAttributes()
10115                .hasAttribute(AttributeSet::FunctionIndex,
10116                              Attribute::NoImplicitFloat)) &&
10117           Subtarget->hasSSE1());
10118  }
10119
10120  // Insert VAARG_64 node into the DAG
10121  // VAARG_64 returns two values: Variable Argument Address, Chain
10122  SmallVector<SDValue, 11> InstOps;
10123  InstOps.push_back(Chain);
10124  InstOps.push_back(SrcPtr);
10125  InstOps.push_back(DAG.getConstant(ArgSize, MVT::i32));
10126  InstOps.push_back(DAG.getConstant(ArgMode, MVT::i8));
10127  InstOps.push_back(DAG.getConstant(Align, MVT::i32));
10128  SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other);
10129  SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
10130                                          VTs, &InstOps[0], InstOps.size(),
10131                                          MVT::i64,
10132                                          MachinePointerInfo(SV),
10133                                          /*Align=*/0,
10134                                          /*Volatile=*/false,
10135                                          /*ReadMem=*/true,
10136                                          /*WriteMem=*/true);
10137  Chain = VAARG.getValue(1);
10138
10139  // Load the next argument and return it
10140  return DAG.getLoad(ArgVT, dl,
10141                     Chain,
10142                     VAARG,
10143                     MachinePointerInfo(),
10144                     false, false, false, 0);
10145}
10146
10147static SDValue LowerVACOPY(SDValue Op, const X86Subtarget *Subtarget,
10148                           SelectionDAG &DAG) {
10149  // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
10150  assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
10151  SDValue Chain = Op.getOperand(0);
10152  SDValue DstPtr = Op.getOperand(1);
10153  SDValue SrcPtr = Op.getOperand(2);
10154  const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
10155  const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
10156  DebugLoc DL = Op.getDebugLoc();
10157
10158  return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
10159                       DAG.getIntPtrConstant(24), 8, /*isVolatile*/false,
10160                       false,
10161                       MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
10162}
10163
10164// getTargetVShiftNOde - Handle vector element shifts where the shift amount
10165// may or may not be a constant. Takes immediate version of shift as input.
10166static SDValue getTargetVShiftNode(unsigned Opc, DebugLoc dl, EVT VT,
10167                                   SDValue SrcOp, SDValue ShAmt,
10168                                   SelectionDAG &DAG) {
10169  assert(ShAmt.getValueType() == MVT::i32 && "ShAmt is not i32");
10170
10171  if (isa<ConstantSDNode>(ShAmt)) {
10172    // Constant may be a TargetConstant. Use a regular constant.
10173    uint32_t ShiftAmt = cast<ConstantSDNode>(ShAmt)->getZExtValue();
10174    switch (Opc) {
10175      default: llvm_unreachable("Unknown target vector shift node");
10176      case X86ISD::VSHLI:
10177      case X86ISD::VSRLI:
10178      case X86ISD::VSRAI:
10179        return DAG.getNode(Opc, dl, VT, SrcOp,
10180                           DAG.getConstant(ShiftAmt, MVT::i32));
10181    }
10182  }
10183
10184  // Change opcode to non-immediate version
10185  switch (Opc) {
10186    default: llvm_unreachable("Unknown target vector shift node");
10187    case X86ISD::VSHLI: Opc = X86ISD::VSHL; break;
10188    case X86ISD::VSRLI: Opc = X86ISD::VSRL; break;
10189    case X86ISD::VSRAI: Opc = X86ISD::VSRA; break;
10190  }
10191
10192  // Need to build a vector containing shift amount
10193  // Shift amount is 32-bits, but SSE instructions read 64-bit, so fill with 0
10194  SDValue ShOps[4];
10195  ShOps[0] = ShAmt;
10196  ShOps[1] = DAG.getConstant(0, MVT::i32);
10197  ShOps[2] = ShOps[3] = DAG.getUNDEF(MVT::i32);
10198  ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, &ShOps[0], 4);
10199
10200  // The return type has to be a 128-bit type with the same element
10201  // type as the input type.
10202  MVT EltVT = VT.getVectorElementType().getSimpleVT();
10203  EVT ShVT = MVT::getVectorVT(EltVT, 128/EltVT.getSizeInBits());
10204
10205  ShAmt = DAG.getNode(ISD::BITCAST, dl, ShVT, ShAmt);
10206  return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
10207}
10208
10209static SDValue LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) {
10210  DebugLoc dl = Op.getDebugLoc();
10211  unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
10212  switch (IntNo) {
10213  default: return SDValue();    // Don't custom lower most intrinsics.
10214  // Comparison intrinsics.
10215  case Intrinsic::x86_sse_comieq_ss:
10216  case Intrinsic::x86_sse_comilt_ss:
10217  case Intrinsic::x86_sse_comile_ss:
10218  case Intrinsic::x86_sse_comigt_ss:
10219  case Intrinsic::x86_sse_comige_ss:
10220  case Intrinsic::x86_sse_comineq_ss:
10221  case Intrinsic::x86_sse_ucomieq_ss:
10222  case Intrinsic::x86_sse_ucomilt_ss:
10223  case Intrinsic::x86_sse_ucomile_ss:
10224  case Intrinsic::x86_sse_ucomigt_ss:
10225  case Intrinsic::x86_sse_ucomige_ss:
10226  case Intrinsic::x86_sse_ucomineq_ss:
10227  case Intrinsic::x86_sse2_comieq_sd:
10228  case Intrinsic::x86_sse2_comilt_sd:
10229  case Intrinsic::x86_sse2_comile_sd:
10230  case Intrinsic::x86_sse2_comigt_sd:
10231  case Intrinsic::x86_sse2_comige_sd:
10232  case Intrinsic::x86_sse2_comineq_sd:
10233  case Intrinsic::x86_sse2_ucomieq_sd:
10234  case Intrinsic::x86_sse2_ucomilt_sd:
10235  case Intrinsic::x86_sse2_ucomile_sd:
10236  case Intrinsic::x86_sse2_ucomigt_sd:
10237  case Intrinsic::x86_sse2_ucomige_sd:
10238  case Intrinsic::x86_sse2_ucomineq_sd: {
10239    unsigned Opc;
10240    ISD::CondCode CC;
10241    switch (IntNo) {
10242    default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
10243    case Intrinsic::x86_sse_comieq_ss:
10244    case Intrinsic::x86_sse2_comieq_sd:
10245      Opc = X86ISD::COMI;
10246      CC = ISD::SETEQ;
10247      break;
10248    case Intrinsic::x86_sse_comilt_ss:
10249    case Intrinsic::x86_sse2_comilt_sd:
10250      Opc = X86ISD::COMI;
10251      CC = ISD::SETLT;
10252      break;
10253    case Intrinsic::x86_sse_comile_ss:
10254    case Intrinsic::x86_sse2_comile_sd:
10255      Opc = X86ISD::COMI;
10256      CC = ISD::SETLE;
10257      break;
10258    case Intrinsic::x86_sse_comigt_ss:
10259    case Intrinsic::x86_sse2_comigt_sd:
10260      Opc = X86ISD::COMI;
10261      CC = ISD::SETGT;
10262      break;
10263    case Intrinsic::x86_sse_comige_ss:
10264    case Intrinsic::x86_sse2_comige_sd:
10265      Opc = X86ISD::COMI;
10266      CC = ISD::SETGE;
10267      break;
10268    case Intrinsic::x86_sse_comineq_ss:
10269    case Intrinsic::x86_sse2_comineq_sd:
10270      Opc = X86ISD::COMI;
10271      CC = ISD::SETNE;
10272      break;
10273    case Intrinsic::x86_sse_ucomieq_ss:
10274    case Intrinsic::x86_sse2_ucomieq_sd:
10275      Opc = X86ISD::UCOMI;
10276      CC = ISD::SETEQ;
10277      break;
10278    case Intrinsic::x86_sse_ucomilt_ss:
10279    case Intrinsic::x86_sse2_ucomilt_sd:
10280      Opc = X86ISD::UCOMI;
10281      CC = ISD::SETLT;
10282      break;
10283    case Intrinsic::x86_sse_ucomile_ss:
10284    case Intrinsic::x86_sse2_ucomile_sd:
10285      Opc = X86ISD::UCOMI;
10286      CC = ISD::SETLE;
10287      break;
10288    case Intrinsic::x86_sse_ucomigt_ss:
10289    case Intrinsic::x86_sse2_ucomigt_sd:
10290      Opc = X86ISD::UCOMI;
10291      CC = ISD::SETGT;
10292      break;
10293    case Intrinsic::x86_sse_ucomige_ss:
10294    case Intrinsic::x86_sse2_ucomige_sd:
10295      Opc = X86ISD::UCOMI;
10296      CC = ISD::SETGE;
10297      break;
10298    case Intrinsic::x86_sse_ucomineq_ss:
10299    case Intrinsic::x86_sse2_ucomineq_sd:
10300      Opc = X86ISD::UCOMI;
10301      CC = ISD::SETNE;
10302      break;
10303    }
10304
10305    SDValue LHS = Op.getOperand(1);
10306    SDValue RHS = Op.getOperand(2);
10307    unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
10308    assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
10309    SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS);
10310    SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
10311                                DAG.getConstant(X86CC, MVT::i8), Cond);
10312    return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
10313  }
10314
10315  // Arithmetic intrinsics.
10316  case Intrinsic::x86_sse2_pmulu_dq:
10317  case Intrinsic::x86_avx2_pmulu_dq:
10318    return DAG.getNode(X86ISD::PMULUDQ, dl, Op.getValueType(),
10319                       Op.getOperand(1), Op.getOperand(2));
10320
10321  // SSE2/AVX2 sub with unsigned saturation intrinsics
10322  case Intrinsic::x86_sse2_psubus_b:
10323  case Intrinsic::x86_sse2_psubus_w:
10324  case Intrinsic::x86_avx2_psubus_b:
10325  case Intrinsic::x86_avx2_psubus_w:
10326    return DAG.getNode(X86ISD::SUBUS, dl, Op.getValueType(),
10327                       Op.getOperand(1), Op.getOperand(2));
10328
10329  // SSE3/AVX horizontal add/sub intrinsics
10330  case Intrinsic::x86_sse3_hadd_ps:
10331  case Intrinsic::x86_sse3_hadd_pd:
10332  case Intrinsic::x86_avx_hadd_ps_256:
10333  case Intrinsic::x86_avx_hadd_pd_256:
10334  case Intrinsic::x86_sse3_hsub_ps:
10335  case Intrinsic::x86_sse3_hsub_pd:
10336  case Intrinsic::x86_avx_hsub_ps_256:
10337  case Intrinsic::x86_avx_hsub_pd_256:
10338  case Intrinsic::x86_ssse3_phadd_w_128:
10339  case Intrinsic::x86_ssse3_phadd_d_128:
10340  case Intrinsic::x86_avx2_phadd_w:
10341  case Intrinsic::x86_avx2_phadd_d:
10342  case Intrinsic::x86_ssse3_phsub_w_128:
10343  case Intrinsic::x86_ssse3_phsub_d_128:
10344  case Intrinsic::x86_avx2_phsub_w:
10345  case Intrinsic::x86_avx2_phsub_d: {
10346    unsigned Opcode;
10347    switch (IntNo) {
10348    default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
10349    case Intrinsic::x86_sse3_hadd_ps:
10350    case Intrinsic::x86_sse3_hadd_pd:
10351    case Intrinsic::x86_avx_hadd_ps_256:
10352    case Intrinsic::x86_avx_hadd_pd_256:
10353      Opcode = X86ISD::FHADD;
10354      break;
10355    case Intrinsic::x86_sse3_hsub_ps:
10356    case Intrinsic::x86_sse3_hsub_pd:
10357    case Intrinsic::x86_avx_hsub_ps_256:
10358    case Intrinsic::x86_avx_hsub_pd_256:
10359      Opcode = X86ISD::FHSUB;
10360      break;
10361    case Intrinsic::x86_ssse3_phadd_w_128:
10362    case Intrinsic::x86_ssse3_phadd_d_128:
10363    case Intrinsic::x86_avx2_phadd_w:
10364    case Intrinsic::x86_avx2_phadd_d:
10365      Opcode = X86ISD::HADD;
10366      break;
10367    case Intrinsic::x86_ssse3_phsub_w_128:
10368    case Intrinsic::x86_ssse3_phsub_d_128:
10369    case Intrinsic::x86_avx2_phsub_w:
10370    case Intrinsic::x86_avx2_phsub_d:
10371      Opcode = X86ISD::HSUB;
10372      break;
10373    }
10374    return DAG.getNode(Opcode, dl, Op.getValueType(),
10375                       Op.getOperand(1), Op.getOperand(2));
10376  }
10377
10378  // SSE2/SSE41/AVX2 integer max/min intrinsics.
10379  case Intrinsic::x86_sse2_pmaxu_b:
10380  case Intrinsic::x86_sse41_pmaxuw:
10381  case Intrinsic::x86_sse41_pmaxud:
10382  case Intrinsic::x86_avx2_pmaxu_b:
10383  case Intrinsic::x86_avx2_pmaxu_w:
10384  case Intrinsic::x86_avx2_pmaxu_d:
10385  case Intrinsic::x86_sse2_pminu_b:
10386  case Intrinsic::x86_sse41_pminuw:
10387  case Intrinsic::x86_sse41_pminud:
10388  case Intrinsic::x86_avx2_pminu_b:
10389  case Intrinsic::x86_avx2_pminu_w:
10390  case Intrinsic::x86_avx2_pminu_d:
10391  case Intrinsic::x86_sse41_pmaxsb:
10392  case Intrinsic::x86_sse2_pmaxs_w:
10393  case Intrinsic::x86_sse41_pmaxsd:
10394  case Intrinsic::x86_avx2_pmaxs_b:
10395  case Intrinsic::x86_avx2_pmaxs_w:
10396  case Intrinsic::x86_avx2_pmaxs_d:
10397  case Intrinsic::x86_sse41_pminsb:
10398  case Intrinsic::x86_sse2_pmins_w:
10399  case Intrinsic::x86_sse41_pminsd:
10400  case Intrinsic::x86_avx2_pmins_b:
10401  case Intrinsic::x86_avx2_pmins_w:
10402  case Intrinsic::x86_avx2_pmins_d: {
10403    unsigned Opcode;
10404    switch (IntNo) {
10405    default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
10406    case Intrinsic::x86_sse2_pmaxu_b:
10407    case Intrinsic::x86_sse41_pmaxuw:
10408    case Intrinsic::x86_sse41_pmaxud:
10409    case Intrinsic::x86_avx2_pmaxu_b:
10410    case Intrinsic::x86_avx2_pmaxu_w:
10411    case Intrinsic::x86_avx2_pmaxu_d:
10412      Opcode = X86ISD::UMAX;
10413      break;
10414    case Intrinsic::x86_sse2_pminu_b:
10415    case Intrinsic::x86_sse41_pminuw:
10416    case Intrinsic::x86_sse41_pminud:
10417    case Intrinsic::x86_avx2_pminu_b:
10418    case Intrinsic::x86_avx2_pminu_w:
10419    case Intrinsic::x86_avx2_pminu_d:
10420      Opcode = X86ISD::UMIN;
10421      break;
10422    case Intrinsic::x86_sse41_pmaxsb:
10423    case Intrinsic::x86_sse2_pmaxs_w:
10424    case Intrinsic::x86_sse41_pmaxsd:
10425    case Intrinsic::x86_avx2_pmaxs_b:
10426    case Intrinsic::x86_avx2_pmaxs_w:
10427    case Intrinsic::x86_avx2_pmaxs_d:
10428      Opcode = X86ISD::SMAX;
10429      break;
10430    case Intrinsic::x86_sse41_pminsb:
10431    case Intrinsic::x86_sse2_pmins_w:
10432    case Intrinsic::x86_sse41_pminsd:
10433    case Intrinsic::x86_avx2_pmins_b:
10434    case Intrinsic::x86_avx2_pmins_w:
10435    case Intrinsic::x86_avx2_pmins_d:
10436      Opcode = X86ISD::SMIN;
10437      break;
10438    }
10439    return DAG.getNode(Opcode, dl, Op.getValueType(),
10440                       Op.getOperand(1), Op.getOperand(2));
10441  }
10442
10443  // SSE/SSE2/AVX floating point max/min intrinsics.
10444  case Intrinsic::x86_sse_max_ps:
10445  case Intrinsic::x86_sse2_max_pd:
10446  case Intrinsic::x86_avx_max_ps_256:
10447  case Intrinsic::x86_avx_max_pd_256:
10448  case Intrinsic::x86_sse_min_ps:
10449  case Intrinsic::x86_sse2_min_pd:
10450  case Intrinsic::x86_avx_min_ps_256:
10451  case Intrinsic::x86_avx_min_pd_256: {
10452    unsigned Opcode;
10453    switch (IntNo) {
10454    default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
10455    case Intrinsic::x86_sse_max_ps:
10456    case Intrinsic::x86_sse2_max_pd:
10457    case Intrinsic::x86_avx_max_ps_256:
10458    case Intrinsic::x86_avx_max_pd_256:
10459      Opcode = X86ISD::FMAX;
10460      break;
10461    case Intrinsic::x86_sse_min_ps:
10462    case Intrinsic::x86_sse2_min_pd:
10463    case Intrinsic::x86_avx_min_ps_256:
10464    case Intrinsic::x86_avx_min_pd_256:
10465      Opcode = X86ISD::FMIN;
10466      break;
10467    }
10468    return DAG.getNode(Opcode, dl, Op.getValueType(),
10469                       Op.getOperand(1), Op.getOperand(2));
10470  }
10471
10472  // AVX2 variable shift intrinsics
10473  case Intrinsic::x86_avx2_psllv_d:
10474  case Intrinsic::x86_avx2_psllv_q:
10475  case Intrinsic::x86_avx2_psllv_d_256:
10476  case Intrinsic::x86_avx2_psllv_q_256:
10477  case Intrinsic::x86_avx2_psrlv_d:
10478  case Intrinsic::x86_avx2_psrlv_q:
10479  case Intrinsic::x86_avx2_psrlv_d_256:
10480  case Intrinsic::x86_avx2_psrlv_q_256:
10481  case Intrinsic::x86_avx2_psrav_d:
10482  case Intrinsic::x86_avx2_psrav_d_256: {
10483    unsigned Opcode;
10484    switch (IntNo) {
10485    default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
10486    case Intrinsic::x86_avx2_psllv_d:
10487    case Intrinsic::x86_avx2_psllv_q:
10488    case Intrinsic::x86_avx2_psllv_d_256:
10489    case Intrinsic::x86_avx2_psllv_q_256:
10490      Opcode = ISD::SHL;
10491      break;
10492    case Intrinsic::x86_avx2_psrlv_d:
10493    case Intrinsic::x86_avx2_psrlv_q:
10494    case Intrinsic::x86_avx2_psrlv_d_256:
10495    case Intrinsic::x86_avx2_psrlv_q_256:
10496      Opcode = ISD::SRL;
10497      break;
10498    case Intrinsic::x86_avx2_psrav_d:
10499    case Intrinsic::x86_avx2_psrav_d_256:
10500      Opcode = ISD::SRA;
10501      break;
10502    }
10503    return DAG.getNode(Opcode, dl, Op.getValueType(),
10504                       Op.getOperand(1), Op.getOperand(2));
10505  }
10506
10507  case Intrinsic::x86_ssse3_pshuf_b_128:
10508  case Intrinsic::x86_avx2_pshuf_b:
10509    return DAG.getNode(X86ISD::PSHUFB, dl, Op.getValueType(),
10510                       Op.getOperand(1), Op.getOperand(2));
10511
10512  case Intrinsic::x86_ssse3_psign_b_128:
10513  case Intrinsic::x86_ssse3_psign_w_128:
10514  case Intrinsic::x86_ssse3_psign_d_128:
10515  case Intrinsic::x86_avx2_psign_b:
10516  case Intrinsic::x86_avx2_psign_w:
10517  case Intrinsic::x86_avx2_psign_d:
10518    return DAG.getNode(X86ISD::PSIGN, dl, Op.getValueType(),
10519                       Op.getOperand(1), Op.getOperand(2));
10520
10521  case Intrinsic::x86_sse41_insertps:
10522    return DAG.getNode(X86ISD::INSERTPS, dl, Op.getValueType(),
10523                       Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
10524
10525  case Intrinsic::x86_avx_vperm2f128_ps_256:
10526  case Intrinsic::x86_avx_vperm2f128_pd_256:
10527  case Intrinsic::x86_avx_vperm2f128_si_256:
10528  case Intrinsic::x86_avx2_vperm2i128:
10529    return DAG.getNode(X86ISD::VPERM2X128, dl, Op.getValueType(),
10530                       Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
10531
10532  case Intrinsic::x86_avx2_permd:
10533  case Intrinsic::x86_avx2_permps:
10534    // Operands intentionally swapped. Mask is last operand to intrinsic,
10535    // but second operand for node/intruction.
10536    return DAG.getNode(X86ISD::VPERMV, dl, Op.getValueType(),
10537                       Op.getOperand(2), Op.getOperand(1));
10538
10539  case Intrinsic::x86_sse_sqrt_ps:
10540  case Intrinsic::x86_sse2_sqrt_pd:
10541  case Intrinsic::x86_avx_sqrt_ps_256:
10542  case Intrinsic::x86_avx_sqrt_pd_256:
10543    return DAG.getNode(ISD::FSQRT, dl, Op.getValueType(), Op.getOperand(1));
10544
10545  // ptest and testp intrinsics. The intrinsic these come from are designed to
10546  // return an integer value, not just an instruction so lower it to the ptest
10547  // or testp pattern and a setcc for the result.
10548  case Intrinsic::x86_sse41_ptestz:
10549  case Intrinsic::x86_sse41_ptestc:
10550  case Intrinsic::x86_sse41_ptestnzc:
10551  case Intrinsic::x86_avx_ptestz_256:
10552  case Intrinsic::x86_avx_ptestc_256:
10553  case Intrinsic::x86_avx_ptestnzc_256:
10554  case Intrinsic::x86_avx_vtestz_ps:
10555  case Intrinsic::x86_avx_vtestc_ps:
10556  case Intrinsic::x86_avx_vtestnzc_ps:
10557  case Intrinsic::x86_avx_vtestz_pd:
10558  case Intrinsic::x86_avx_vtestc_pd:
10559  case Intrinsic::x86_avx_vtestnzc_pd:
10560  case Intrinsic::x86_avx_vtestz_ps_256:
10561  case Intrinsic::x86_avx_vtestc_ps_256:
10562  case Intrinsic::x86_avx_vtestnzc_ps_256:
10563  case Intrinsic::x86_avx_vtestz_pd_256:
10564  case Intrinsic::x86_avx_vtestc_pd_256:
10565  case Intrinsic::x86_avx_vtestnzc_pd_256: {
10566    bool IsTestPacked = false;
10567    unsigned X86CC;
10568    switch (IntNo) {
10569    default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
10570    case Intrinsic::x86_avx_vtestz_ps:
10571    case Intrinsic::x86_avx_vtestz_pd:
10572    case Intrinsic::x86_avx_vtestz_ps_256:
10573    case Intrinsic::x86_avx_vtestz_pd_256:
10574      IsTestPacked = true; // Fallthrough
10575    case Intrinsic::x86_sse41_ptestz:
10576    case Intrinsic::x86_avx_ptestz_256:
10577      // ZF = 1
10578      X86CC = X86::COND_E;
10579      break;
10580    case Intrinsic::x86_avx_vtestc_ps:
10581    case Intrinsic::x86_avx_vtestc_pd:
10582    case Intrinsic::x86_avx_vtestc_ps_256:
10583    case Intrinsic::x86_avx_vtestc_pd_256:
10584      IsTestPacked = true; // Fallthrough
10585    case Intrinsic::x86_sse41_ptestc:
10586    case Intrinsic::x86_avx_ptestc_256:
10587      // CF = 1
10588      X86CC = X86::COND_B;
10589      break;
10590    case Intrinsic::x86_avx_vtestnzc_ps:
10591    case Intrinsic::x86_avx_vtestnzc_pd:
10592    case Intrinsic::x86_avx_vtestnzc_ps_256:
10593    case Intrinsic::x86_avx_vtestnzc_pd_256:
10594      IsTestPacked = true; // Fallthrough
10595    case Intrinsic::x86_sse41_ptestnzc:
10596    case Intrinsic::x86_avx_ptestnzc_256:
10597      // ZF and CF = 0
10598      X86CC = X86::COND_A;
10599      break;
10600    }
10601
10602    SDValue LHS = Op.getOperand(1);
10603    SDValue RHS = Op.getOperand(2);
10604    unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
10605    SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
10606    SDValue CC = DAG.getConstant(X86CC, MVT::i8);
10607    SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
10608    return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
10609  }
10610
10611  // SSE/AVX shift intrinsics
10612  case Intrinsic::x86_sse2_psll_w:
10613  case Intrinsic::x86_sse2_psll_d:
10614  case Intrinsic::x86_sse2_psll_q:
10615  case Intrinsic::x86_avx2_psll_w:
10616  case Intrinsic::x86_avx2_psll_d:
10617  case Intrinsic::x86_avx2_psll_q:
10618  case Intrinsic::x86_sse2_psrl_w:
10619  case Intrinsic::x86_sse2_psrl_d:
10620  case Intrinsic::x86_sse2_psrl_q:
10621  case Intrinsic::x86_avx2_psrl_w:
10622  case Intrinsic::x86_avx2_psrl_d:
10623  case Intrinsic::x86_avx2_psrl_q:
10624  case Intrinsic::x86_sse2_psra_w:
10625  case Intrinsic::x86_sse2_psra_d:
10626  case Intrinsic::x86_avx2_psra_w:
10627  case Intrinsic::x86_avx2_psra_d: {
10628    unsigned Opcode;
10629    switch (IntNo) {
10630    default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
10631    case Intrinsic::x86_sse2_psll_w:
10632    case Intrinsic::x86_sse2_psll_d:
10633    case Intrinsic::x86_sse2_psll_q:
10634    case Intrinsic::x86_avx2_psll_w:
10635    case Intrinsic::x86_avx2_psll_d:
10636    case Intrinsic::x86_avx2_psll_q:
10637      Opcode = X86ISD::VSHL;
10638      break;
10639    case Intrinsic::x86_sse2_psrl_w:
10640    case Intrinsic::x86_sse2_psrl_d:
10641    case Intrinsic::x86_sse2_psrl_q:
10642    case Intrinsic::x86_avx2_psrl_w:
10643    case Intrinsic::x86_avx2_psrl_d:
10644    case Intrinsic::x86_avx2_psrl_q:
10645      Opcode = X86ISD::VSRL;
10646      break;
10647    case Intrinsic::x86_sse2_psra_w:
10648    case Intrinsic::x86_sse2_psra_d:
10649    case Intrinsic::x86_avx2_psra_w:
10650    case Intrinsic::x86_avx2_psra_d:
10651      Opcode = X86ISD::VSRA;
10652      break;
10653    }
10654    return DAG.getNode(Opcode, dl, Op.getValueType(),
10655                       Op.getOperand(1), Op.getOperand(2));
10656  }
10657
10658  // SSE/AVX immediate shift intrinsics
10659  case Intrinsic::x86_sse2_pslli_w:
10660  case Intrinsic::x86_sse2_pslli_d:
10661  case Intrinsic::x86_sse2_pslli_q:
10662  case Intrinsic::x86_avx2_pslli_w:
10663  case Intrinsic::x86_avx2_pslli_d:
10664  case Intrinsic::x86_avx2_pslli_q:
10665  case Intrinsic::x86_sse2_psrli_w:
10666  case Intrinsic::x86_sse2_psrli_d:
10667  case Intrinsic::x86_sse2_psrli_q:
10668  case Intrinsic::x86_avx2_psrli_w:
10669  case Intrinsic::x86_avx2_psrli_d:
10670  case Intrinsic::x86_avx2_psrli_q:
10671  case Intrinsic::x86_sse2_psrai_w:
10672  case Intrinsic::x86_sse2_psrai_d:
10673  case Intrinsic::x86_avx2_psrai_w:
10674  case Intrinsic::x86_avx2_psrai_d: {
10675    unsigned Opcode;
10676    switch (IntNo) {
10677    default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
10678    case Intrinsic::x86_sse2_pslli_w:
10679    case Intrinsic::x86_sse2_pslli_d:
10680    case Intrinsic::x86_sse2_pslli_q:
10681    case Intrinsic::x86_avx2_pslli_w:
10682    case Intrinsic::x86_avx2_pslli_d:
10683    case Intrinsic::x86_avx2_pslli_q:
10684      Opcode = X86ISD::VSHLI;
10685      break;
10686    case Intrinsic::x86_sse2_psrli_w:
10687    case Intrinsic::x86_sse2_psrli_d:
10688    case Intrinsic::x86_sse2_psrli_q:
10689    case Intrinsic::x86_avx2_psrli_w:
10690    case Intrinsic::x86_avx2_psrli_d:
10691    case Intrinsic::x86_avx2_psrli_q:
10692      Opcode = X86ISD::VSRLI;
10693      break;
10694    case Intrinsic::x86_sse2_psrai_w:
10695    case Intrinsic::x86_sse2_psrai_d:
10696    case Intrinsic::x86_avx2_psrai_w:
10697    case Intrinsic::x86_avx2_psrai_d:
10698      Opcode = X86ISD::VSRAI;
10699      break;
10700    }
10701    return getTargetVShiftNode(Opcode, dl, Op.getValueType(),
10702                               Op.getOperand(1), Op.getOperand(2), DAG);
10703  }
10704
10705  case Intrinsic::x86_sse42_pcmpistria128:
10706  case Intrinsic::x86_sse42_pcmpestria128:
10707  case Intrinsic::x86_sse42_pcmpistric128:
10708  case Intrinsic::x86_sse42_pcmpestric128:
10709  case Intrinsic::x86_sse42_pcmpistrio128:
10710  case Intrinsic::x86_sse42_pcmpestrio128:
10711  case Intrinsic::x86_sse42_pcmpistris128:
10712  case Intrinsic::x86_sse42_pcmpestris128:
10713  case Intrinsic::x86_sse42_pcmpistriz128:
10714  case Intrinsic::x86_sse42_pcmpestriz128: {
10715    unsigned Opcode;
10716    unsigned X86CC;
10717    switch (IntNo) {
10718    default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
10719    case Intrinsic::x86_sse42_pcmpistria128:
10720      Opcode = X86ISD::PCMPISTRI;
10721      X86CC = X86::COND_A;
10722      break;
10723    case Intrinsic::x86_sse42_pcmpestria128:
10724      Opcode = X86ISD::PCMPESTRI;
10725      X86CC = X86::COND_A;
10726      break;
10727    case Intrinsic::x86_sse42_pcmpistric128:
10728      Opcode = X86ISD::PCMPISTRI;
10729      X86CC = X86::COND_B;
10730      break;
10731    case Intrinsic::x86_sse42_pcmpestric128:
10732      Opcode = X86ISD::PCMPESTRI;
10733      X86CC = X86::COND_B;
10734      break;
10735    case Intrinsic::x86_sse42_pcmpistrio128:
10736      Opcode = X86ISD::PCMPISTRI;
10737      X86CC = X86::COND_O;
10738      break;
10739    case Intrinsic::x86_sse42_pcmpestrio128:
10740      Opcode = X86ISD::PCMPESTRI;
10741      X86CC = X86::COND_O;
10742      break;
10743    case Intrinsic::x86_sse42_pcmpistris128:
10744      Opcode = X86ISD::PCMPISTRI;
10745      X86CC = X86::COND_S;
10746      break;
10747    case Intrinsic::x86_sse42_pcmpestris128:
10748      Opcode = X86ISD::PCMPESTRI;
10749      X86CC = X86::COND_S;
10750      break;
10751    case Intrinsic::x86_sse42_pcmpistriz128:
10752      Opcode = X86ISD::PCMPISTRI;
10753      X86CC = X86::COND_E;
10754      break;
10755    case Intrinsic::x86_sse42_pcmpestriz128:
10756      Opcode = X86ISD::PCMPESTRI;
10757      X86CC = X86::COND_E;
10758      break;
10759    }
10760    SmallVector<SDValue, 5> NewOps;
10761    NewOps.append(Op->op_begin()+1, Op->op_end());
10762    SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
10763    SDValue PCMP = DAG.getNode(Opcode, dl, VTs, NewOps.data(), NewOps.size());
10764    SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
10765                                DAG.getConstant(X86CC, MVT::i8),
10766                                SDValue(PCMP.getNode(), 1));
10767    return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
10768  }
10769
10770  case Intrinsic::x86_sse42_pcmpistri128:
10771  case Intrinsic::x86_sse42_pcmpestri128: {
10772    unsigned Opcode;
10773    if (IntNo == Intrinsic::x86_sse42_pcmpistri128)
10774      Opcode = X86ISD::PCMPISTRI;
10775    else
10776      Opcode = X86ISD::PCMPESTRI;
10777
10778    SmallVector<SDValue, 5> NewOps;
10779    NewOps.append(Op->op_begin()+1, Op->op_end());
10780    SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
10781    return DAG.getNode(Opcode, dl, VTs, NewOps.data(), NewOps.size());
10782  }
10783  case Intrinsic::x86_fma_vfmadd_ps:
10784  case Intrinsic::x86_fma_vfmadd_pd:
10785  case Intrinsic::x86_fma_vfmsub_ps:
10786  case Intrinsic::x86_fma_vfmsub_pd:
10787  case Intrinsic::x86_fma_vfnmadd_ps:
10788  case Intrinsic::x86_fma_vfnmadd_pd:
10789  case Intrinsic::x86_fma_vfnmsub_ps:
10790  case Intrinsic::x86_fma_vfnmsub_pd:
10791  case Intrinsic::x86_fma_vfmaddsub_ps:
10792  case Intrinsic::x86_fma_vfmaddsub_pd:
10793  case Intrinsic::x86_fma_vfmsubadd_ps:
10794  case Intrinsic::x86_fma_vfmsubadd_pd:
10795  case Intrinsic::x86_fma_vfmadd_ps_256:
10796  case Intrinsic::x86_fma_vfmadd_pd_256:
10797  case Intrinsic::x86_fma_vfmsub_ps_256:
10798  case Intrinsic::x86_fma_vfmsub_pd_256:
10799  case Intrinsic::x86_fma_vfnmadd_ps_256:
10800  case Intrinsic::x86_fma_vfnmadd_pd_256:
10801  case Intrinsic::x86_fma_vfnmsub_ps_256:
10802  case Intrinsic::x86_fma_vfnmsub_pd_256:
10803  case Intrinsic::x86_fma_vfmaddsub_ps_256:
10804  case Intrinsic::x86_fma_vfmaddsub_pd_256:
10805  case Intrinsic::x86_fma_vfmsubadd_ps_256:
10806  case Intrinsic::x86_fma_vfmsubadd_pd_256: {
10807    unsigned Opc;
10808    switch (IntNo) {
10809    default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
10810    case Intrinsic::x86_fma_vfmadd_ps:
10811    case Intrinsic::x86_fma_vfmadd_pd:
10812    case Intrinsic::x86_fma_vfmadd_ps_256:
10813    case Intrinsic::x86_fma_vfmadd_pd_256:
10814      Opc = X86ISD::FMADD;
10815      break;
10816    case Intrinsic::x86_fma_vfmsub_ps:
10817    case Intrinsic::x86_fma_vfmsub_pd:
10818    case Intrinsic::x86_fma_vfmsub_ps_256:
10819    case Intrinsic::x86_fma_vfmsub_pd_256:
10820      Opc = X86ISD::FMSUB;
10821      break;
10822    case Intrinsic::x86_fma_vfnmadd_ps:
10823    case Intrinsic::x86_fma_vfnmadd_pd:
10824    case Intrinsic::x86_fma_vfnmadd_ps_256:
10825    case Intrinsic::x86_fma_vfnmadd_pd_256:
10826      Opc = X86ISD::FNMADD;
10827      break;
10828    case Intrinsic::x86_fma_vfnmsub_ps:
10829    case Intrinsic::x86_fma_vfnmsub_pd:
10830    case Intrinsic::x86_fma_vfnmsub_ps_256:
10831    case Intrinsic::x86_fma_vfnmsub_pd_256:
10832      Opc = X86ISD::FNMSUB;
10833      break;
10834    case Intrinsic::x86_fma_vfmaddsub_ps:
10835    case Intrinsic::x86_fma_vfmaddsub_pd:
10836    case Intrinsic::x86_fma_vfmaddsub_ps_256:
10837    case Intrinsic::x86_fma_vfmaddsub_pd_256:
10838      Opc = X86ISD::FMADDSUB;
10839      break;
10840    case Intrinsic::x86_fma_vfmsubadd_ps:
10841    case Intrinsic::x86_fma_vfmsubadd_pd:
10842    case Intrinsic::x86_fma_vfmsubadd_ps_256:
10843    case Intrinsic::x86_fma_vfmsubadd_pd_256:
10844      Opc = X86ISD::FMSUBADD;
10845      break;
10846    }
10847
10848    return DAG.getNode(Opc, dl, Op.getValueType(), Op.getOperand(1),
10849                       Op.getOperand(2), Op.getOperand(3));
10850  }
10851  }
10852}
10853
10854static SDValue LowerINTRINSIC_W_CHAIN(SDValue Op, SelectionDAG &DAG) {
10855  DebugLoc dl = Op.getDebugLoc();
10856  unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10857  switch (IntNo) {
10858  default: return SDValue();    // Don't custom lower most intrinsics.
10859
10860  // RDRAND intrinsics.
10861  case Intrinsic::x86_rdrand_16:
10862  case Intrinsic::x86_rdrand_32:
10863  case Intrinsic::x86_rdrand_64: {
10864    // Emit the node with the right value type.
10865    SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Glue, MVT::Other);
10866    SDValue Result = DAG.getNode(X86ISD::RDRAND, dl, VTs, Op.getOperand(0));
10867
10868    // If the value returned by RDRAND was valid (CF=1), return 1. Otherwise
10869    // return the value from Rand, which is always 0, casted to i32.
10870    SDValue Ops[] = { DAG.getZExtOrTrunc(Result, dl, Op->getValueType(1)),
10871                      DAG.getConstant(1, Op->getValueType(1)),
10872                      DAG.getConstant(X86::COND_B, MVT::i32),
10873                      SDValue(Result.getNode(), 1) };
10874    SDValue isValid = DAG.getNode(X86ISD::CMOV, dl,
10875                                  DAG.getVTList(Op->getValueType(1), MVT::Glue),
10876                                  Ops, 4);
10877
10878    // Return { result, isValid, chain }.
10879    return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), Result, isValid,
10880                       SDValue(Result.getNode(), 2));
10881  }
10882  }
10883}
10884
10885SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
10886                                           SelectionDAG &DAG) const {
10887  MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
10888  MFI->setReturnAddressIsTaken(true);
10889
10890  unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
10891  DebugLoc dl = Op.getDebugLoc();
10892  EVT PtrVT = getPointerTy();
10893
10894  if (Depth > 0) {
10895    SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
10896    SDValue Offset =
10897      DAG.getConstant(RegInfo->getSlotSize(), PtrVT);
10898    return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
10899                       DAG.getNode(ISD::ADD, dl, PtrVT,
10900                                   FrameAddr, Offset),
10901                       MachinePointerInfo(), false, false, false, 0);
10902  }
10903
10904  // Just load the return address.
10905  SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
10906  return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
10907                     RetAddrFI, MachinePointerInfo(), false, false, false, 0);
10908}
10909
10910SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
10911  MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
10912  MFI->setFrameAddressIsTaken(true);
10913
10914  EVT VT = Op.getValueType();
10915  DebugLoc dl = Op.getDebugLoc();  // FIXME probably not meaningful
10916  unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
10917  unsigned FrameReg = Subtarget->is64Bit() ? X86::RBP : X86::EBP;
10918  SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
10919  while (Depth--)
10920    FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
10921                            MachinePointerInfo(),
10922                            false, false, false, 0);
10923  return FrameAddr;
10924}
10925
10926SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
10927                                                     SelectionDAG &DAG) const {
10928  return DAG.getIntPtrConstant(2 * RegInfo->getSlotSize());
10929}
10930
10931SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
10932  SDValue Chain     = Op.getOperand(0);
10933  SDValue Offset    = Op.getOperand(1);
10934  SDValue Handler   = Op.getOperand(2);
10935  DebugLoc dl       = Op.getDebugLoc();
10936
10937  SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl,
10938                                     Subtarget->is64Bit() ? X86::RBP : X86::EBP,
10939                                     getPointerTy());
10940  unsigned StoreAddrReg = (Subtarget->is64Bit() ? X86::RCX : X86::ECX);
10941
10942  SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), Frame,
10943                                  DAG.getIntPtrConstant(RegInfo->getSlotSize()));
10944  StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), StoreAddr, Offset);
10945  Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
10946                       false, false, 0);
10947  Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
10948
10949  return DAG.getNode(X86ISD::EH_RETURN, dl,
10950                     MVT::Other,
10951                     Chain, DAG.getRegister(StoreAddrReg, getPointerTy()));
10952}
10953
10954SDValue X86TargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
10955                                               SelectionDAG &DAG) const {
10956  DebugLoc DL = Op.getDebugLoc();
10957  return DAG.getNode(X86ISD::EH_SJLJ_SETJMP, DL,
10958                     DAG.getVTList(MVT::i32, MVT::Other),
10959                     Op.getOperand(0), Op.getOperand(1));
10960}
10961
10962SDValue X86TargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
10963                                                SelectionDAG &DAG) const {
10964  DebugLoc DL = Op.getDebugLoc();
10965  return DAG.getNode(X86ISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
10966                     Op.getOperand(0), Op.getOperand(1));
10967}
10968
10969static SDValue LowerADJUST_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) {
10970  return Op.getOperand(0);
10971}
10972
10973SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
10974                                                SelectionDAG &DAG) const {
10975  SDValue Root = Op.getOperand(0);
10976  SDValue Trmp = Op.getOperand(1); // trampoline
10977  SDValue FPtr = Op.getOperand(2); // nested function
10978  SDValue Nest = Op.getOperand(3); // 'nest' parameter value
10979  DebugLoc dl  = Op.getDebugLoc();
10980
10981  const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
10982  const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
10983
10984  if (Subtarget->is64Bit()) {
10985    SDValue OutChains[6];
10986
10987    // Large code-model.
10988    const unsigned char JMP64r  = 0xFF; // 64-bit jmp through register opcode.
10989    const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
10990
10991    const unsigned char N86R10 = TRI->getEncodingValue(X86::R10) & 0x7;
10992    const unsigned char N86R11 = TRI->getEncodingValue(X86::R11) & 0x7;
10993
10994    const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
10995
10996    // Load the pointer to the nested function into R11.
10997    unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
10998    SDValue Addr = Trmp;
10999    OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
11000                                Addr, MachinePointerInfo(TrmpAddr),
11001                                false, false, 0);
11002
11003    Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
11004                       DAG.getConstant(2, MVT::i64));
11005    OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
11006                                MachinePointerInfo(TrmpAddr, 2),
11007                                false, false, 2);
11008
11009    // Load the 'nest' parameter value into R10.
11010    // R10 is specified in X86CallingConv.td
11011    OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
11012    Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
11013                       DAG.getConstant(10, MVT::i64));
11014    OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
11015                                Addr, MachinePointerInfo(TrmpAddr, 10),
11016                                false, false, 0);
11017
11018    Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
11019                       DAG.getConstant(12, MVT::i64));
11020    OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
11021                                MachinePointerInfo(TrmpAddr, 12),
11022                                false, false, 2);
11023
11024    // Jump to the nested function.
11025    OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
11026    Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
11027                       DAG.getConstant(20, MVT::i64));
11028    OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
11029                                Addr, MachinePointerInfo(TrmpAddr, 20),
11030                                false, false, 0);
11031
11032    unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
11033    Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
11034                       DAG.getConstant(22, MVT::i64));
11035    OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
11036                                MachinePointerInfo(TrmpAddr, 22),
11037                                false, false, 0);
11038
11039    return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 6);
11040  } else {
11041    const Function *Func =
11042      cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
11043    CallingConv::ID CC = Func->getCallingConv();
11044    unsigned NestReg;
11045
11046    switch (CC) {
11047    default:
11048      llvm_unreachable("Unsupported calling convention");
11049    case CallingConv::C:
11050    case CallingConv::X86_StdCall: {
11051      // Pass 'nest' parameter in ECX.
11052      // Must be kept in sync with X86CallingConv.td
11053      NestReg = X86::ECX;
11054
11055      // Check that ECX wasn't needed by an 'inreg' parameter.
11056      FunctionType *FTy = Func->getFunctionType();
11057      const AttributeSet &Attrs = Func->getAttributes();
11058
11059      if (!Attrs.isEmpty() && !Func->isVarArg()) {
11060        unsigned InRegCount = 0;
11061        unsigned Idx = 1;
11062
11063        for (FunctionType::param_iterator I = FTy->param_begin(),
11064             E = FTy->param_end(); I != E; ++I, ++Idx)
11065          if (Attrs.hasAttribute(Idx, Attribute::InReg))
11066            // FIXME: should only count parameters that are lowered to integers.
11067            InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
11068
11069        if (InRegCount > 2) {
11070          report_fatal_error("Nest register in use - reduce number of inreg"
11071                             " parameters!");
11072        }
11073      }
11074      break;
11075    }
11076    case CallingConv::X86_FastCall:
11077    case CallingConv::X86_ThisCall:
11078    case CallingConv::Fast:
11079      // Pass 'nest' parameter in EAX.
11080      // Must be kept in sync with X86CallingConv.td
11081      NestReg = X86::EAX;
11082      break;
11083    }
11084
11085    SDValue OutChains[4];
11086    SDValue Addr, Disp;
11087
11088    Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
11089                       DAG.getConstant(10, MVT::i32));
11090    Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
11091
11092    // This is storing the opcode for MOV32ri.
11093    const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
11094    const unsigned char N86Reg = TRI->getEncodingValue(NestReg) & 0x7;
11095    OutChains[0] = DAG.getStore(Root, dl,
11096                                DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
11097                                Trmp, MachinePointerInfo(TrmpAddr),
11098                                false, false, 0);
11099
11100    Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
11101                       DAG.getConstant(1, MVT::i32));
11102    OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
11103                                MachinePointerInfo(TrmpAddr, 1),
11104                                false, false, 1);
11105
11106    const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
11107    Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
11108                       DAG.getConstant(5, MVT::i32));
11109    OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
11110                                MachinePointerInfo(TrmpAddr, 5),
11111                                false, false, 1);
11112
11113    Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
11114                       DAG.getConstant(6, MVT::i32));
11115    OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
11116                                MachinePointerInfo(TrmpAddr, 6),
11117                                false, false, 1);
11118
11119    return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 4);
11120  }
11121}
11122
11123SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
11124                                            SelectionDAG &DAG) const {
11125  /*
11126   The rounding mode is in bits 11:10 of FPSR, and has the following
11127   settings:
11128     00 Round to nearest
11129     01 Round to -inf
11130     10 Round to +inf
11131     11 Round to 0
11132
11133  FLT_ROUNDS, on the other hand, expects the following:
11134    -1 Undefined
11135     0 Round to 0
11136     1 Round to nearest
11137     2 Round to +inf
11138     3 Round to -inf
11139
11140  To perform the conversion, we do:
11141    (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
11142  */
11143
11144  MachineFunction &MF = DAG.getMachineFunction();
11145  const TargetMachine &TM = MF.getTarget();
11146  const TargetFrameLowering &TFI = *TM.getFrameLowering();
11147  unsigned StackAlignment = TFI.getStackAlignment();
11148  EVT VT = Op.getValueType();
11149  DebugLoc DL = Op.getDebugLoc();
11150
11151  // Save FP Control Word to stack slot
11152  int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
11153  SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
11154
11155  MachineMemOperand *MMO =
11156   MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11157                           MachineMemOperand::MOStore, 2, 2);
11158
11159  SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
11160  SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
11161                                          DAG.getVTList(MVT::Other),
11162                                          Ops, 2, MVT::i16, MMO);
11163
11164  // Load FP Control Word from stack slot
11165  SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
11166                            MachinePointerInfo(), false, false, false, 0);
11167
11168  // Transform as necessary
11169  SDValue CWD1 =
11170    DAG.getNode(ISD::SRL, DL, MVT::i16,
11171                DAG.getNode(ISD::AND, DL, MVT::i16,
11172                            CWD, DAG.getConstant(0x800, MVT::i16)),
11173                DAG.getConstant(11, MVT::i8));
11174  SDValue CWD2 =
11175    DAG.getNode(ISD::SRL, DL, MVT::i16,
11176                DAG.getNode(ISD::AND, DL, MVT::i16,
11177                            CWD, DAG.getConstant(0x400, MVT::i16)),
11178                DAG.getConstant(9, MVT::i8));
11179
11180  SDValue RetVal =
11181    DAG.getNode(ISD::AND, DL, MVT::i16,
11182                DAG.getNode(ISD::ADD, DL, MVT::i16,
11183                            DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
11184                            DAG.getConstant(1, MVT::i16)),
11185                DAG.getConstant(3, MVT::i16));
11186
11187  return DAG.getNode((VT.getSizeInBits() < 16 ?
11188                      ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
11189}
11190
11191static SDValue LowerCTLZ(SDValue Op, SelectionDAG &DAG) {
11192  EVT VT = Op.getValueType();
11193  EVT OpVT = VT;
11194  unsigned NumBits = VT.getSizeInBits();
11195  DebugLoc dl = Op.getDebugLoc();
11196
11197  Op = Op.getOperand(0);
11198  if (VT == MVT::i8) {
11199    // Zero extend to i32 since there is not an i8 bsr.
11200    OpVT = MVT::i32;
11201    Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
11202  }
11203
11204  // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
11205  SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
11206  Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
11207
11208  // If src is zero (i.e. bsr sets ZF), returns NumBits.
11209  SDValue Ops[] = {
11210    Op,
11211    DAG.getConstant(NumBits+NumBits-1, OpVT),
11212    DAG.getConstant(X86::COND_E, MVT::i8),
11213    Op.getValue(1)
11214  };
11215  Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
11216
11217  // Finally xor with NumBits-1.
11218  Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
11219
11220  if (VT == MVT::i8)
11221    Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
11222  return Op;
11223}
11224
11225static SDValue LowerCTLZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) {
11226  EVT VT = Op.getValueType();
11227  EVT OpVT = VT;
11228  unsigned NumBits = VT.getSizeInBits();
11229  DebugLoc dl = Op.getDebugLoc();
11230
11231  Op = Op.getOperand(0);
11232  if (VT == MVT::i8) {
11233    // Zero extend to i32 since there is not an i8 bsr.
11234    OpVT = MVT::i32;
11235    Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
11236  }
11237
11238  // Issue a bsr (scan bits in reverse).
11239  SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
11240  Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
11241
11242  // And xor with NumBits-1.
11243  Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
11244
11245  if (VT == MVT::i8)
11246    Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
11247  return Op;
11248}
11249
11250static SDValue LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
11251  EVT VT = Op.getValueType();
11252  unsigned NumBits = VT.getSizeInBits();
11253  DebugLoc dl = Op.getDebugLoc();
11254  Op = Op.getOperand(0);
11255
11256  // Issue a bsf (scan bits forward) which also sets EFLAGS.
11257  SDVTList VTs = DAG.getVTList(VT, MVT::i32);
11258  Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
11259
11260  // If src is zero (i.e. bsf sets ZF), returns NumBits.
11261  SDValue Ops[] = {
11262    Op,
11263    DAG.getConstant(NumBits, VT),
11264    DAG.getConstant(X86::COND_E, MVT::i8),
11265    Op.getValue(1)
11266  };
11267  return DAG.getNode(X86ISD::CMOV, dl, VT, Ops, array_lengthof(Ops));
11268}
11269
11270// Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
11271// ones, and then concatenate the result back.
11272static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
11273  EVT VT = Op.getValueType();
11274
11275  assert(VT.is256BitVector() && VT.isInteger() &&
11276         "Unsupported value type for operation");
11277
11278  unsigned NumElems = VT.getVectorNumElements();
11279  DebugLoc dl = Op.getDebugLoc();
11280
11281  // Extract the LHS vectors
11282  SDValue LHS = Op.getOperand(0);
11283  SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
11284  SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
11285
11286  // Extract the RHS vectors
11287  SDValue RHS = Op.getOperand(1);
11288  SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
11289  SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
11290
11291  MVT EltVT = VT.getVectorElementType().getSimpleVT();
11292  EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
11293
11294  return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
11295                     DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
11296                     DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
11297}
11298
11299static SDValue LowerADD(SDValue Op, SelectionDAG &DAG) {
11300  assert(Op.getValueType().is256BitVector() &&
11301         Op.getValueType().isInteger() &&
11302         "Only handle AVX 256-bit vector integer operation");
11303  return Lower256IntArith(Op, DAG);
11304}
11305
11306static SDValue LowerSUB(SDValue Op, SelectionDAG &DAG) {
11307  assert(Op.getValueType().is256BitVector() &&
11308         Op.getValueType().isInteger() &&
11309         "Only handle AVX 256-bit vector integer operation");
11310  return Lower256IntArith(Op, DAG);
11311}
11312
11313static SDValue LowerMUL(SDValue Op, const X86Subtarget *Subtarget,
11314                        SelectionDAG &DAG) {
11315  DebugLoc dl = Op.getDebugLoc();
11316  EVT VT = Op.getValueType();
11317
11318  // Decompose 256-bit ops into smaller 128-bit ops.
11319  if (VT.is256BitVector() && !Subtarget->hasInt256())
11320    return Lower256IntArith(Op, DAG);
11321
11322  SDValue A = Op.getOperand(0);
11323  SDValue B = Op.getOperand(1);
11324
11325  // Lower v4i32 mul as 2x shuffle, 2x pmuludq, 2x shuffle.
11326  if (VT == MVT::v4i32) {
11327    assert(Subtarget->hasSSE2() && !Subtarget->hasSSE41() &&
11328           "Should not custom lower when pmuldq is available!");
11329
11330    // Extract the odd parts.
11331    const int UnpackMask[] = { 1, -1, 3, -1 };
11332    SDValue Aodds = DAG.getVectorShuffle(VT, dl, A, A, UnpackMask);
11333    SDValue Bodds = DAG.getVectorShuffle(VT, dl, B, B, UnpackMask);
11334
11335    // Multiply the even parts.
11336    SDValue Evens = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, A, B);
11337    // Now multiply odd parts.
11338    SDValue Odds = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, Aodds, Bodds);
11339
11340    Evens = DAG.getNode(ISD::BITCAST, dl, VT, Evens);
11341    Odds = DAG.getNode(ISD::BITCAST, dl, VT, Odds);
11342
11343    // Merge the two vectors back together with a shuffle. This expands into 2
11344    // shuffles.
11345    const int ShufMask[] = { 0, 4, 2, 6 };
11346    return DAG.getVectorShuffle(VT, dl, Evens, Odds, ShufMask);
11347  }
11348
11349  assert((VT == MVT::v2i64 || VT == MVT::v4i64) &&
11350         "Only know how to lower V2I64/V4I64 multiply");
11351
11352  //  Ahi = psrlqi(a, 32);
11353  //  Bhi = psrlqi(b, 32);
11354  //
11355  //  AloBlo = pmuludq(a, b);
11356  //  AloBhi = pmuludq(a, Bhi);
11357  //  AhiBlo = pmuludq(Ahi, b);
11358
11359  //  AloBhi = psllqi(AloBhi, 32);
11360  //  AhiBlo = psllqi(AhiBlo, 32);
11361  //  return AloBlo + AloBhi + AhiBlo;
11362
11363  SDValue ShAmt = DAG.getConstant(32, MVT::i32);
11364
11365  SDValue Ahi = DAG.getNode(X86ISD::VSRLI, dl, VT, A, ShAmt);
11366  SDValue Bhi = DAG.getNode(X86ISD::VSRLI, dl, VT, B, ShAmt);
11367
11368  // Bit cast to 32-bit vectors for MULUDQ
11369  EVT MulVT = (VT == MVT::v2i64) ? MVT::v4i32 : MVT::v8i32;
11370  A = DAG.getNode(ISD::BITCAST, dl, MulVT, A);
11371  B = DAG.getNode(ISD::BITCAST, dl, MulVT, B);
11372  Ahi = DAG.getNode(ISD::BITCAST, dl, MulVT, Ahi);
11373  Bhi = DAG.getNode(ISD::BITCAST, dl, MulVT, Bhi);
11374
11375  SDValue AloBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, B);
11376  SDValue AloBhi = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, Bhi);
11377  SDValue AhiBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, Ahi, B);
11378
11379  AloBhi = DAG.getNode(X86ISD::VSHLI, dl, VT, AloBhi, ShAmt);
11380  AhiBlo = DAG.getNode(X86ISD::VSHLI, dl, VT, AhiBlo, ShAmt);
11381
11382  SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
11383  return DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
11384}
11385
11386SDValue X86TargetLowering::LowerSDIV(SDValue Op, SelectionDAG &DAG) const {
11387  EVT VT = Op.getValueType();
11388  EVT EltTy = VT.getVectorElementType();
11389  unsigned NumElts = VT.getVectorNumElements();
11390  SDValue N0 = Op.getOperand(0);
11391  DebugLoc dl = Op.getDebugLoc();
11392
11393  // Lower sdiv X, pow2-const.
11394  BuildVectorSDNode *C = dyn_cast<BuildVectorSDNode>(Op.getOperand(1));
11395  if (!C)
11396    return SDValue();
11397
11398  APInt SplatValue, SplatUndef;
11399  unsigned MinSplatBits;
11400  bool HasAnyUndefs;
11401  if (!C->isConstantSplat(SplatValue, SplatUndef, MinSplatBits, HasAnyUndefs))
11402    return SDValue();
11403
11404  if ((SplatValue != 0) &&
11405      (SplatValue.isPowerOf2() || (-SplatValue).isPowerOf2())) {
11406    unsigned lg2 = SplatValue.countTrailingZeros();
11407    // Splat the sign bit.
11408    SDValue Sz = DAG.getConstant(EltTy.getSizeInBits()-1, MVT::i32);
11409    SDValue SGN = getTargetVShiftNode(X86ISD::VSRAI, dl, VT, N0, Sz, DAG);
11410    // Add (N0 < 0) ? abs2 - 1 : 0;
11411    SDValue Amt = DAG.getConstant(EltTy.getSizeInBits() - lg2, MVT::i32);
11412    SDValue SRL = getTargetVShiftNode(X86ISD::VSRLI, dl, VT, SGN, Amt, DAG);
11413    SDValue ADD = DAG.getNode(ISD::ADD, dl, VT, N0, SRL);
11414    SDValue Lg2Amt = DAG.getConstant(lg2, MVT::i32);
11415    SDValue SRA = getTargetVShiftNode(X86ISD::VSRAI, dl, VT, ADD, Lg2Amt, DAG);
11416
11417    // If we're dividing by a positive value, we're done.  Otherwise, we must
11418    // negate the result.
11419    if (SplatValue.isNonNegative())
11420      return SRA;
11421
11422    SmallVector<SDValue, 16> V(NumElts, DAG.getConstant(0, EltTy));
11423    SDValue Zero = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], NumElts);
11424    return DAG.getNode(ISD::SUB, dl, VT, Zero, SRA);
11425  }
11426  return SDValue();
11427}
11428
11429SDValue X86TargetLowering::LowerShift(SDValue Op, SelectionDAG &DAG) const {
11430
11431  EVT VT = Op.getValueType();
11432  DebugLoc dl = Op.getDebugLoc();
11433  SDValue R = Op.getOperand(0);
11434  SDValue Amt = Op.getOperand(1);
11435  LLVMContext *Context = DAG.getContext();
11436
11437  if (!Subtarget->hasSSE2())
11438    return SDValue();
11439
11440  // Optimize shl/srl/sra with constant shift amount.
11441  if (isSplatVector(Amt.getNode())) {
11442    SDValue SclrAmt = Amt->getOperand(0);
11443    if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt)) {
11444      uint64_t ShiftAmt = C->getZExtValue();
11445
11446      if (VT == MVT::v2i64 || VT == MVT::v4i32 || VT == MVT::v8i16 ||
11447          (Subtarget->hasInt256() &&
11448           (VT == MVT::v4i64 || VT == MVT::v8i32 || VT == MVT::v16i16))) {
11449        if (Op.getOpcode() == ISD::SHL)
11450          return DAG.getNode(X86ISD::VSHLI, dl, VT, R,
11451                             DAG.getConstant(ShiftAmt, MVT::i32));
11452        if (Op.getOpcode() == ISD::SRL)
11453          return DAG.getNode(X86ISD::VSRLI, dl, VT, R,
11454                             DAG.getConstant(ShiftAmt, MVT::i32));
11455        if (Op.getOpcode() == ISD::SRA && VT != MVT::v2i64 && VT != MVT::v4i64)
11456          return DAG.getNode(X86ISD::VSRAI, dl, VT, R,
11457                             DAG.getConstant(ShiftAmt, MVT::i32));
11458      }
11459
11460      if (VT == MVT::v16i8) {
11461        if (Op.getOpcode() == ISD::SHL) {
11462          // Make a large shift.
11463          SDValue SHL = DAG.getNode(X86ISD::VSHLI, dl, MVT::v8i16, R,
11464                                    DAG.getConstant(ShiftAmt, MVT::i32));
11465          SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
11466          // Zero out the rightmost bits.
11467          SmallVector<SDValue, 16> V(16,
11468                                     DAG.getConstant(uint8_t(-1U << ShiftAmt),
11469                                                     MVT::i8));
11470          return DAG.getNode(ISD::AND, dl, VT, SHL,
11471                             DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16));
11472        }
11473        if (Op.getOpcode() == ISD::SRL) {
11474          // Make a large shift.
11475          SDValue SRL = DAG.getNode(X86ISD::VSRLI, dl, MVT::v8i16, R,
11476                                    DAG.getConstant(ShiftAmt, MVT::i32));
11477          SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
11478          // Zero out the leftmost bits.
11479          SmallVector<SDValue, 16> V(16,
11480                                     DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
11481                                                     MVT::i8));
11482          return DAG.getNode(ISD::AND, dl, VT, SRL,
11483                             DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16));
11484        }
11485        if (Op.getOpcode() == ISD::SRA) {
11486          if (ShiftAmt == 7) {
11487            // R s>> 7  ===  R s< 0
11488            SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
11489            return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
11490          }
11491
11492          // R s>> a === ((R u>> a) ^ m) - m
11493          SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
11494          SmallVector<SDValue, 16> V(16, DAG.getConstant(128 >> ShiftAmt,
11495                                                         MVT::i8));
11496          SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16);
11497          Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
11498          Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
11499          return Res;
11500        }
11501        llvm_unreachable("Unknown shift opcode.");
11502      }
11503
11504      if (Subtarget->hasInt256() && VT == MVT::v32i8) {
11505        if (Op.getOpcode() == ISD::SHL) {
11506          // Make a large shift.
11507          SDValue SHL = DAG.getNode(X86ISD::VSHLI, dl, MVT::v16i16, R,
11508                                    DAG.getConstant(ShiftAmt, MVT::i32));
11509          SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
11510          // Zero out the rightmost bits.
11511          SmallVector<SDValue, 32> V(32,
11512                                     DAG.getConstant(uint8_t(-1U << ShiftAmt),
11513                                                     MVT::i8));
11514          return DAG.getNode(ISD::AND, dl, VT, SHL,
11515                             DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32));
11516        }
11517        if (Op.getOpcode() == ISD::SRL) {
11518          // Make a large shift.
11519          SDValue SRL = DAG.getNode(X86ISD::VSRLI, dl, MVT::v16i16, R,
11520                                    DAG.getConstant(ShiftAmt, MVT::i32));
11521          SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
11522          // Zero out the leftmost bits.
11523          SmallVector<SDValue, 32> V(32,
11524                                     DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
11525                                                     MVT::i8));
11526          return DAG.getNode(ISD::AND, dl, VT, SRL,
11527                             DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32));
11528        }
11529        if (Op.getOpcode() == ISD::SRA) {
11530          if (ShiftAmt == 7) {
11531            // R s>> 7  ===  R s< 0
11532            SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
11533            return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
11534          }
11535
11536          // R s>> a === ((R u>> a) ^ m) - m
11537          SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
11538          SmallVector<SDValue, 32> V(32, DAG.getConstant(128 >> ShiftAmt,
11539                                                         MVT::i8));
11540          SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32);
11541          Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
11542          Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
11543          return Res;
11544        }
11545        llvm_unreachable("Unknown shift opcode.");
11546      }
11547    }
11548  }
11549
11550  // Lower SHL with variable shift amount.
11551  if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
11552    Op = DAG.getNode(X86ISD::VSHLI, dl, VT, Op.getOperand(1),
11553                     DAG.getConstant(23, MVT::i32));
11554
11555    const uint32_t CV[] = { 0x3f800000U, 0x3f800000U, 0x3f800000U, 0x3f800000U};
11556    Constant *C = ConstantDataVector::get(*Context, CV);
11557    SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
11558    SDValue Addend = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
11559                                 MachinePointerInfo::getConstantPool(),
11560                                 false, false, false, 16);
11561
11562    Op = DAG.getNode(ISD::ADD, dl, VT, Op, Addend);
11563    Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, Op);
11564    Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
11565    return DAG.getNode(ISD::MUL, dl, VT, Op, R);
11566  }
11567  if (VT == MVT::v16i8 && Op->getOpcode() == ISD::SHL) {
11568    assert(Subtarget->hasSSE2() && "Need SSE2 for pslli/pcmpeq.");
11569
11570    // a = a << 5;
11571    Op = DAG.getNode(X86ISD::VSHLI, dl, MVT::v8i16, Op.getOperand(1),
11572                     DAG.getConstant(5, MVT::i32));
11573    Op = DAG.getNode(ISD::BITCAST, dl, VT, Op);
11574
11575    // Turn 'a' into a mask suitable for VSELECT
11576    SDValue VSelM = DAG.getConstant(0x80, VT);
11577    SDValue OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
11578    OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
11579
11580    SDValue CM1 = DAG.getConstant(0x0f, VT);
11581    SDValue CM2 = DAG.getConstant(0x3f, VT);
11582
11583    // r = VSELECT(r, psllw(r & (char16)15, 4), a);
11584    SDValue M = DAG.getNode(ISD::AND, dl, VT, R, CM1);
11585    M = getTargetVShiftNode(X86ISD::VSHLI, dl, MVT::v8i16, M,
11586                            DAG.getConstant(4, MVT::i32), DAG);
11587    M = DAG.getNode(ISD::BITCAST, dl, VT, M);
11588    R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
11589
11590    // a += a
11591    Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
11592    OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
11593    OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
11594
11595    // r = VSELECT(r, psllw(r & (char16)63, 2), a);
11596    M = DAG.getNode(ISD::AND, dl, VT, R, CM2);
11597    M = getTargetVShiftNode(X86ISD::VSHLI, dl, MVT::v8i16, M,
11598                            DAG.getConstant(2, MVT::i32), DAG);
11599    M = DAG.getNode(ISD::BITCAST, dl, VT, M);
11600    R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
11601
11602    // a += a
11603    Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
11604    OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
11605    OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
11606
11607    // return VSELECT(r, r+r, a);
11608    R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel,
11609                    DAG.getNode(ISD::ADD, dl, VT, R, R), R);
11610    return R;
11611  }
11612
11613  // Decompose 256-bit shifts into smaller 128-bit shifts.
11614  if (VT.is256BitVector()) {
11615    unsigned NumElems = VT.getVectorNumElements();
11616    MVT EltVT = VT.getVectorElementType().getSimpleVT();
11617    EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
11618
11619    // Extract the two vectors
11620    SDValue V1 = Extract128BitVector(R, 0, DAG, dl);
11621    SDValue V2 = Extract128BitVector(R, NumElems/2, DAG, dl);
11622
11623    // Recreate the shift amount vectors
11624    SDValue Amt1, Amt2;
11625    if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
11626      // Constant shift amount
11627      SmallVector<SDValue, 4> Amt1Csts;
11628      SmallVector<SDValue, 4> Amt2Csts;
11629      for (unsigned i = 0; i != NumElems/2; ++i)
11630        Amt1Csts.push_back(Amt->getOperand(i));
11631      for (unsigned i = NumElems/2; i != NumElems; ++i)
11632        Amt2Csts.push_back(Amt->getOperand(i));
11633
11634      Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT,
11635                                 &Amt1Csts[0], NumElems/2);
11636      Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT,
11637                                 &Amt2Csts[0], NumElems/2);
11638    } else {
11639      // Variable shift amount
11640      Amt1 = Extract128BitVector(Amt, 0, DAG, dl);
11641      Amt2 = Extract128BitVector(Amt, NumElems/2, DAG, dl);
11642    }
11643
11644    // Issue new vector shifts for the smaller types
11645    V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
11646    V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
11647
11648    // Concatenate the result back
11649    return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
11650  }
11651
11652  return SDValue();
11653}
11654
11655static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
11656  // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
11657  // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
11658  // looks for this combo and may remove the "setcc" instruction if the "setcc"
11659  // has only one use.
11660  SDNode *N = Op.getNode();
11661  SDValue LHS = N->getOperand(0);
11662  SDValue RHS = N->getOperand(1);
11663  unsigned BaseOp = 0;
11664  unsigned Cond = 0;
11665  DebugLoc DL = Op.getDebugLoc();
11666  switch (Op.getOpcode()) {
11667  default: llvm_unreachable("Unknown ovf instruction!");
11668  case ISD::SADDO:
11669    // A subtract of one will be selected as a INC. Note that INC doesn't
11670    // set CF, so we can't do this for UADDO.
11671    if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
11672      if (C->isOne()) {
11673        BaseOp = X86ISD::INC;
11674        Cond = X86::COND_O;
11675        break;
11676      }
11677    BaseOp = X86ISD::ADD;
11678    Cond = X86::COND_O;
11679    break;
11680  case ISD::UADDO:
11681    BaseOp = X86ISD::ADD;
11682    Cond = X86::COND_B;
11683    break;
11684  case ISD::SSUBO:
11685    // A subtract of one will be selected as a DEC. Note that DEC doesn't
11686    // set CF, so we can't do this for USUBO.
11687    if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
11688      if (C->isOne()) {
11689        BaseOp = X86ISD::DEC;
11690        Cond = X86::COND_O;
11691        break;
11692      }
11693    BaseOp = X86ISD::SUB;
11694    Cond = X86::COND_O;
11695    break;
11696  case ISD::USUBO:
11697    BaseOp = X86ISD::SUB;
11698    Cond = X86::COND_B;
11699    break;
11700  case ISD::SMULO:
11701    BaseOp = X86ISD::SMUL;
11702    Cond = X86::COND_O;
11703    break;
11704  case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
11705    SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
11706                                 MVT::i32);
11707    SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
11708
11709    SDValue SetCC =
11710      DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
11711                  DAG.getConstant(X86::COND_O, MVT::i32),
11712                  SDValue(Sum.getNode(), 2));
11713
11714    return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
11715  }
11716  }
11717
11718  // Also sets EFLAGS.
11719  SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
11720  SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
11721
11722  SDValue SetCC =
11723    DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
11724                DAG.getConstant(Cond, MVT::i32),
11725                SDValue(Sum.getNode(), 1));
11726
11727  return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
11728}
11729
11730SDValue X86TargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op,
11731                                                  SelectionDAG &DAG) const {
11732  DebugLoc dl = Op.getDebugLoc();
11733  EVT ExtraVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
11734  EVT VT = Op.getValueType();
11735
11736  if (!Subtarget->hasSSE2() || !VT.isVector())
11737    return SDValue();
11738
11739  unsigned BitsDiff = VT.getScalarType().getSizeInBits() -
11740                      ExtraVT.getScalarType().getSizeInBits();
11741  SDValue ShAmt = DAG.getConstant(BitsDiff, MVT::i32);
11742
11743  switch (VT.getSimpleVT().SimpleTy) {
11744    default: return SDValue();
11745    case MVT::v8i32:
11746    case MVT::v16i16:
11747      if (!Subtarget->hasFp256())
11748        return SDValue();
11749      if (!Subtarget->hasInt256()) {
11750        // needs to be split
11751        unsigned NumElems = VT.getVectorNumElements();
11752
11753        // Extract the LHS vectors
11754        SDValue LHS = Op.getOperand(0);
11755        SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
11756        SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
11757
11758        MVT EltVT = VT.getVectorElementType().getSimpleVT();
11759        EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
11760
11761        EVT ExtraEltVT = ExtraVT.getVectorElementType();
11762        unsigned ExtraNumElems = ExtraVT.getVectorNumElements();
11763        ExtraVT = EVT::getVectorVT(*DAG.getContext(), ExtraEltVT,
11764                                   ExtraNumElems/2);
11765        SDValue Extra = DAG.getValueType(ExtraVT);
11766
11767        LHS1 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, Extra);
11768        LHS2 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, Extra);
11769
11770        return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, LHS1, LHS2);
11771      }
11772      // fall through
11773    case MVT::v4i32:
11774    case MVT::v8i16: {
11775      SDValue Tmp1 = getTargetVShiftNode(X86ISD::VSHLI, dl, VT,
11776                                         Op.getOperand(0), ShAmt, DAG);
11777      return getTargetVShiftNode(X86ISD::VSRAI, dl, VT, Tmp1, ShAmt, DAG);
11778    }
11779  }
11780}
11781
11782static SDValue LowerMEMBARRIER(SDValue Op, const X86Subtarget *Subtarget,
11783                              SelectionDAG &DAG) {
11784  DebugLoc dl = Op.getDebugLoc();
11785
11786  // Go ahead and emit the fence on x86-64 even if we asked for no-sse2.
11787  // There isn't any reason to disable it if the target processor supports it.
11788  if (!Subtarget->hasSSE2() && !Subtarget->is64Bit()) {
11789    SDValue Chain = Op.getOperand(0);
11790    SDValue Zero = DAG.getConstant(0, MVT::i32);
11791    SDValue Ops[] = {
11792      DAG.getRegister(X86::ESP, MVT::i32), // Base
11793      DAG.getTargetConstant(1, MVT::i8),   // Scale
11794      DAG.getRegister(0, MVT::i32),        // Index
11795      DAG.getTargetConstant(0, MVT::i32),  // Disp
11796      DAG.getRegister(0, MVT::i32),        // Segment.
11797      Zero,
11798      Chain
11799    };
11800    SDNode *Res =
11801      DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops,
11802                          array_lengthof(Ops));
11803    return SDValue(Res, 0);
11804  }
11805
11806  unsigned isDev = cast<ConstantSDNode>(Op.getOperand(5))->getZExtValue();
11807  if (!isDev)
11808    return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
11809
11810  unsigned Op1 = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
11811  unsigned Op2 = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
11812  unsigned Op3 = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue();
11813  unsigned Op4 = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
11814
11815  // def : Pat<(membarrier (i8 0), (i8 0), (i8 0), (i8 1), (i8 1)), (SFENCE)>;
11816  if (!Op1 && !Op2 && !Op3 && Op4)
11817    return DAG.getNode(X86ISD::SFENCE, dl, MVT::Other, Op.getOperand(0));
11818
11819  // def : Pat<(membarrier (i8 1), (i8 0), (i8 0), (i8 0), (i8 1)), (LFENCE)>;
11820  if (Op1 && !Op2 && !Op3 && !Op4)
11821    return DAG.getNode(X86ISD::LFENCE, dl, MVT::Other, Op.getOperand(0));
11822
11823  // def : Pat<(membarrier (i8 imm), (i8 imm), (i8 imm), (i8 imm), (i8 1)),
11824  //           (MFENCE)>;
11825  return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
11826}
11827
11828static SDValue LowerATOMIC_FENCE(SDValue Op, const X86Subtarget *Subtarget,
11829                                 SelectionDAG &DAG) {
11830  DebugLoc dl = Op.getDebugLoc();
11831  AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
11832    cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
11833  SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
11834    cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
11835
11836  // The only fence that needs an instruction is a sequentially-consistent
11837  // cross-thread fence.
11838  if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
11839    // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
11840    // no-sse2). There isn't any reason to disable it if the target processor
11841    // supports it.
11842    if (Subtarget->hasSSE2() || Subtarget->is64Bit())
11843      return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
11844
11845    SDValue Chain = Op.getOperand(0);
11846    SDValue Zero = DAG.getConstant(0, MVT::i32);
11847    SDValue Ops[] = {
11848      DAG.getRegister(X86::ESP, MVT::i32), // Base
11849      DAG.getTargetConstant(1, MVT::i8),   // Scale
11850      DAG.getRegister(0, MVT::i32),        // Index
11851      DAG.getTargetConstant(0, MVT::i32),  // Disp
11852      DAG.getRegister(0, MVT::i32),        // Segment.
11853      Zero,
11854      Chain
11855    };
11856    SDNode *Res =
11857      DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops,
11858                         array_lengthof(Ops));
11859    return SDValue(Res, 0);
11860  }
11861
11862  // MEMBARRIER is a compiler barrier; it codegens to a no-op.
11863  return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
11864}
11865
11866static SDValue LowerCMP_SWAP(SDValue Op, const X86Subtarget *Subtarget,
11867                             SelectionDAG &DAG) {
11868  EVT T = Op.getValueType();
11869  DebugLoc DL = Op.getDebugLoc();
11870  unsigned Reg = 0;
11871  unsigned size = 0;
11872  switch(T.getSimpleVT().SimpleTy) {
11873  default: llvm_unreachable("Invalid value type!");
11874  case MVT::i8:  Reg = X86::AL;  size = 1; break;
11875  case MVT::i16: Reg = X86::AX;  size = 2; break;
11876  case MVT::i32: Reg = X86::EAX; size = 4; break;
11877  case MVT::i64:
11878    assert(Subtarget->is64Bit() && "Node not type legal!");
11879    Reg = X86::RAX; size = 8;
11880    break;
11881  }
11882  SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
11883                                    Op.getOperand(2), SDValue());
11884  SDValue Ops[] = { cpIn.getValue(0),
11885                    Op.getOperand(1),
11886                    Op.getOperand(3),
11887                    DAG.getTargetConstant(size, MVT::i8),
11888                    cpIn.getValue(1) };
11889  SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
11890  MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
11891  SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
11892                                           Ops, 5, T, MMO);
11893  SDValue cpOut =
11894    DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
11895  return cpOut;
11896}
11897
11898static SDValue LowerREADCYCLECOUNTER(SDValue Op, const X86Subtarget *Subtarget,
11899                                     SelectionDAG &DAG) {
11900  assert(Subtarget->is64Bit() && "Result not type legalized?");
11901  SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
11902  SDValue TheChain = Op.getOperand(0);
11903  DebugLoc dl = Op.getDebugLoc();
11904  SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
11905  SDValue rax = DAG.getCopyFromReg(rd, dl, X86::RAX, MVT::i64, rd.getValue(1));
11906  SDValue rdx = DAG.getCopyFromReg(rax.getValue(1), dl, X86::RDX, MVT::i64,
11907                                   rax.getValue(2));
11908  SDValue Tmp = DAG.getNode(ISD::SHL, dl, MVT::i64, rdx,
11909                            DAG.getConstant(32, MVT::i8));
11910  SDValue Ops[] = {
11911    DAG.getNode(ISD::OR, dl, MVT::i64, rax, Tmp),
11912    rdx.getValue(1)
11913  };
11914  return DAG.getMergeValues(Ops, 2, dl);
11915}
11916
11917SDValue X86TargetLowering::LowerBITCAST(SDValue Op, SelectionDAG &DAG) const {
11918  EVT SrcVT = Op.getOperand(0).getValueType();
11919  EVT DstVT = Op.getValueType();
11920  assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
11921         Subtarget->hasMMX() && "Unexpected custom BITCAST");
11922  assert((DstVT == MVT::i64 ||
11923          (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
11924         "Unexpected custom BITCAST");
11925  // i64 <=> MMX conversions are Legal.
11926  if (SrcVT==MVT::i64 && DstVT.isVector())
11927    return Op;
11928  if (DstVT==MVT::i64 && SrcVT.isVector())
11929    return Op;
11930  // MMX <=> MMX conversions are Legal.
11931  if (SrcVT.isVector() && DstVT.isVector())
11932    return Op;
11933  // All other conversions need to be expanded.
11934  return SDValue();
11935}
11936
11937static SDValue LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) {
11938  SDNode *Node = Op.getNode();
11939  DebugLoc dl = Node->getDebugLoc();
11940  EVT T = Node->getValueType(0);
11941  SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
11942                              DAG.getConstant(0, T), Node->getOperand(2));
11943  return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
11944                       cast<AtomicSDNode>(Node)->getMemoryVT(),
11945                       Node->getOperand(0),
11946                       Node->getOperand(1), negOp,
11947                       cast<AtomicSDNode>(Node)->getSrcValue(),
11948                       cast<AtomicSDNode>(Node)->getAlignment(),
11949                       cast<AtomicSDNode>(Node)->getOrdering(),
11950                       cast<AtomicSDNode>(Node)->getSynchScope());
11951}
11952
11953static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
11954  SDNode *Node = Op.getNode();
11955  DebugLoc dl = Node->getDebugLoc();
11956  EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
11957
11958  // Convert seq_cst store -> xchg
11959  // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
11960  // FIXME: On 32-bit, store -> fist or movq would be more efficient
11961  //        (The only way to get a 16-byte store is cmpxchg16b)
11962  // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
11963  if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
11964      !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
11965    SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
11966                                 cast<AtomicSDNode>(Node)->getMemoryVT(),
11967                                 Node->getOperand(0),
11968                                 Node->getOperand(1), Node->getOperand(2),
11969                                 cast<AtomicSDNode>(Node)->getMemOperand(),
11970                                 cast<AtomicSDNode>(Node)->getOrdering(),
11971                                 cast<AtomicSDNode>(Node)->getSynchScope());
11972    return Swap.getValue(1);
11973  }
11974  // Other atomic stores have a simple pattern.
11975  return Op;
11976}
11977
11978static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
11979  EVT VT = Op.getNode()->getValueType(0);
11980
11981  // Let legalize expand this if it isn't a legal type yet.
11982  if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
11983    return SDValue();
11984
11985  SDVTList VTs = DAG.getVTList(VT, MVT::i32);
11986
11987  unsigned Opc;
11988  bool ExtraOp = false;
11989  switch (Op.getOpcode()) {
11990  default: llvm_unreachable("Invalid code");
11991  case ISD::ADDC: Opc = X86ISD::ADD; break;
11992  case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
11993  case ISD::SUBC: Opc = X86ISD::SUB; break;
11994  case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
11995  }
11996
11997  if (!ExtraOp)
11998    return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
11999                       Op.getOperand(1));
12000  return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
12001                     Op.getOperand(1), Op.getOperand(2));
12002}
12003
12004/// LowerOperation - Provide custom lowering hooks for some operations.
12005///
12006SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
12007  switch (Op.getOpcode()) {
12008  default: llvm_unreachable("Should not custom lower this!");
12009  case ISD::SIGN_EXTEND_INREG:  return LowerSIGN_EXTEND_INREG(Op,DAG);
12010  case ISD::MEMBARRIER:         return LowerMEMBARRIER(Op, Subtarget, DAG);
12011  case ISD::ATOMIC_FENCE:       return LowerATOMIC_FENCE(Op, Subtarget, DAG);
12012  case ISD::ATOMIC_CMP_SWAP:    return LowerCMP_SWAP(Op, Subtarget, DAG);
12013  case ISD::ATOMIC_LOAD_SUB:    return LowerLOAD_SUB(Op,DAG);
12014  case ISD::ATOMIC_STORE:       return LowerATOMIC_STORE(Op,DAG);
12015  case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
12016  case ISD::CONCAT_VECTORS:     return LowerCONCAT_VECTORS(Op, DAG);
12017  case ISD::VECTOR_SHUFFLE:     return LowerVECTOR_SHUFFLE(Op, DAG);
12018  case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
12019  case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
12020  case ISD::EXTRACT_SUBVECTOR:  return LowerEXTRACT_SUBVECTOR(Op,Subtarget,DAG);
12021  case ISD::INSERT_SUBVECTOR:   return LowerINSERT_SUBVECTOR(Op, Subtarget,DAG);
12022  case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
12023  case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
12024  case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
12025  case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
12026  case ISD::ExternalSymbol:     return LowerExternalSymbol(Op, DAG);
12027  case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
12028  case ISD::SHL_PARTS:
12029  case ISD::SRA_PARTS:
12030  case ISD::SRL_PARTS:          return LowerShiftParts(Op, DAG);
12031  case ISD::SINT_TO_FP:         return LowerSINT_TO_FP(Op, DAG);
12032  case ISD::UINT_TO_FP:         return LowerUINT_TO_FP(Op, DAG);
12033  case ISD::TRUNCATE:           return lowerTRUNCATE(Op, DAG);
12034  case ISD::ZERO_EXTEND:        return LowerZERO_EXTEND(Op, DAG);
12035  case ISD::SIGN_EXTEND:        return LowerSIGN_EXTEND(Op, DAG);
12036  case ISD::ANY_EXTEND:         return LowerANY_EXTEND(Op, DAG);
12037  case ISD::FP_TO_SINT:         return LowerFP_TO_SINT(Op, DAG);
12038  case ISD::FP_TO_UINT:         return LowerFP_TO_UINT(Op, DAG);
12039  case ISD::FP_EXTEND:          return lowerFP_EXTEND(Op, DAG);
12040  case ISD::FABS:               return LowerFABS(Op, DAG);
12041  case ISD::FNEG:               return LowerFNEG(Op, DAG);
12042  case ISD::FCOPYSIGN:          return LowerFCOPYSIGN(Op, DAG);
12043  case ISD::FGETSIGN:           return LowerFGETSIGN(Op, DAG);
12044  case ISD::SETCC:              return LowerSETCC(Op, DAG);
12045  case ISD::SELECT:             return LowerSELECT(Op, DAG);
12046  case ISD::BRCOND:             return LowerBRCOND(Op, DAG);
12047  case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
12048  case ISD::VASTART:            return LowerVASTART(Op, DAG);
12049  case ISD::VAARG:              return LowerVAARG(Op, DAG);
12050  case ISD::VACOPY:             return LowerVACOPY(Op, Subtarget, DAG);
12051  case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
12052  case ISD::INTRINSIC_W_CHAIN:  return LowerINTRINSIC_W_CHAIN(Op, DAG);
12053  case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
12054  case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
12055  case ISD::FRAME_TO_ARGS_OFFSET:
12056                                return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
12057  case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
12058  case ISD::EH_RETURN:          return LowerEH_RETURN(Op, DAG);
12059  case ISD::EH_SJLJ_SETJMP:     return lowerEH_SJLJ_SETJMP(Op, DAG);
12060  case ISD::EH_SJLJ_LONGJMP:    return lowerEH_SJLJ_LONGJMP(Op, DAG);
12061  case ISD::INIT_TRAMPOLINE:    return LowerINIT_TRAMPOLINE(Op, DAG);
12062  case ISD::ADJUST_TRAMPOLINE:  return LowerADJUST_TRAMPOLINE(Op, DAG);
12063  case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
12064  case ISD::CTLZ:               return LowerCTLZ(Op, DAG);
12065  case ISD::CTLZ_ZERO_UNDEF:    return LowerCTLZ_ZERO_UNDEF(Op, DAG);
12066  case ISD::CTTZ:               return LowerCTTZ(Op, DAG);
12067  case ISD::MUL:                return LowerMUL(Op, Subtarget, DAG);
12068  case ISD::SRA:
12069  case ISD::SRL:
12070  case ISD::SHL:                return LowerShift(Op, DAG);
12071  case ISD::SADDO:
12072  case ISD::UADDO:
12073  case ISD::SSUBO:
12074  case ISD::USUBO:
12075  case ISD::SMULO:
12076  case ISD::UMULO:              return LowerXALUO(Op, DAG);
12077  case ISD::READCYCLECOUNTER:   return LowerREADCYCLECOUNTER(Op, Subtarget,DAG);
12078  case ISD::BITCAST:            return LowerBITCAST(Op, DAG);
12079  case ISD::ADDC:
12080  case ISD::ADDE:
12081  case ISD::SUBC:
12082  case ISD::SUBE:               return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
12083  case ISD::ADD:                return LowerADD(Op, DAG);
12084  case ISD::SUB:                return LowerSUB(Op, DAG);
12085  case ISD::SDIV:               return LowerSDIV(Op, DAG);
12086  }
12087}
12088
12089static void ReplaceATOMIC_LOAD(SDNode *Node,
12090                                  SmallVectorImpl<SDValue> &Results,
12091                                  SelectionDAG &DAG) {
12092  DebugLoc dl = Node->getDebugLoc();
12093  EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
12094
12095  // Convert wide load -> cmpxchg8b/cmpxchg16b
12096  // FIXME: On 32-bit, load -> fild or movq would be more efficient
12097  //        (The only way to get a 16-byte load is cmpxchg16b)
12098  // FIXME: 16-byte ATOMIC_CMP_SWAP isn't actually hooked up at the moment.
12099  SDValue Zero = DAG.getConstant(0, VT);
12100  SDValue Swap = DAG.getAtomic(ISD::ATOMIC_CMP_SWAP, dl, VT,
12101                               Node->getOperand(0),
12102                               Node->getOperand(1), Zero, Zero,
12103                               cast<AtomicSDNode>(Node)->getMemOperand(),
12104                               cast<AtomicSDNode>(Node)->getOrdering(),
12105                               cast<AtomicSDNode>(Node)->getSynchScope());
12106  Results.push_back(Swap.getValue(0));
12107  Results.push_back(Swap.getValue(1));
12108}
12109
12110static void
12111ReplaceATOMIC_BINARY_64(SDNode *Node, SmallVectorImpl<SDValue>&Results,
12112                        SelectionDAG &DAG, unsigned NewOp) {
12113  DebugLoc dl = Node->getDebugLoc();
12114  assert (Node->getValueType(0) == MVT::i64 &&
12115          "Only know how to expand i64 atomics");
12116
12117  SDValue Chain = Node->getOperand(0);
12118  SDValue In1 = Node->getOperand(1);
12119  SDValue In2L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
12120                             Node->getOperand(2), DAG.getIntPtrConstant(0));
12121  SDValue In2H = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
12122                             Node->getOperand(2), DAG.getIntPtrConstant(1));
12123  SDValue Ops[] = { Chain, In1, In2L, In2H };
12124  SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
12125  SDValue Result =
12126    DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops, 4, MVT::i64,
12127                            cast<MemSDNode>(Node)->getMemOperand());
12128  SDValue OpsF[] = { Result.getValue(0), Result.getValue(1)};
12129  Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
12130  Results.push_back(Result.getValue(2));
12131}
12132
12133/// ReplaceNodeResults - Replace a node with an illegal result type
12134/// with a new node built out of custom code.
12135void X86TargetLowering::ReplaceNodeResults(SDNode *N,
12136                                           SmallVectorImpl<SDValue>&Results,
12137                                           SelectionDAG &DAG) const {
12138  DebugLoc dl = N->getDebugLoc();
12139  const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12140  switch (N->getOpcode()) {
12141  default:
12142    llvm_unreachable("Do not know how to custom type legalize this operation!");
12143  case ISD::SIGN_EXTEND_INREG:
12144  case ISD::ADDC:
12145  case ISD::ADDE:
12146  case ISD::SUBC:
12147  case ISD::SUBE:
12148    // We don't want to expand or promote these.
12149    return;
12150  case ISD::FP_TO_SINT:
12151  case ISD::FP_TO_UINT: {
12152    bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
12153
12154    if (!IsSigned && !isIntegerTypeFTOL(SDValue(N, 0).getValueType()))
12155      return;
12156
12157    std::pair<SDValue,SDValue> Vals =
12158        FP_TO_INTHelper(SDValue(N, 0), DAG, IsSigned, /*IsReplace=*/ true);
12159    SDValue FIST = Vals.first, StackSlot = Vals.second;
12160    if (FIST.getNode() != 0) {
12161      EVT VT = N->getValueType(0);
12162      // Return a load from the stack slot.
12163      if (StackSlot.getNode() != 0)
12164        Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
12165                                      MachinePointerInfo(),
12166                                      false, false, false, 0));
12167      else
12168        Results.push_back(FIST);
12169    }
12170    return;
12171  }
12172  case ISD::UINT_TO_FP: {
12173    if (N->getOperand(0).getValueType() != MVT::v2i32 &&
12174        N->getValueType(0) != MVT::v2f32)
12175      return;
12176    SDValue ZExtIn = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v2i64,
12177                                 N->getOperand(0));
12178    SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
12179                                     MVT::f64);
12180    SDValue VBias = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2f64, Bias, Bias);
12181    SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64, ZExtIn,
12182                             DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, VBias));
12183    Or = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or);
12184    SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, Or, VBias);
12185    Results.push_back(DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, Sub));
12186    return;
12187  }
12188  case ISD::FP_ROUND: {
12189    if (!TLI.isTypeLegal(N->getOperand(0).getValueType()))
12190        return;
12191    SDValue V = DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, N->getOperand(0));
12192    Results.push_back(V);
12193    return;
12194  }
12195  case ISD::READCYCLECOUNTER: {
12196    SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
12197    SDValue TheChain = N->getOperand(0);
12198    SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
12199    SDValue eax = DAG.getCopyFromReg(rd, dl, X86::EAX, MVT::i32,
12200                                     rd.getValue(1));
12201    SDValue edx = DAG.getCopyFromReg(eax.getValue(1), dl, X86::EDX, MVT::i32,
12202                                     eax.getValue(2));
12203    // Use a buildpair to merge the two 32-bit values into a 64-bit one.
12204    SDValue Ops[] = { eax, edx };
12205    Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Ops, 2));
12206    Results.push_back(edx.getValue(1));
12207    return;
12208  }
12209  case ISD::ATOMIC_CMP_SWAP: {
12210    EVT T = N->getValueType(0);
12211    assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
12212    bool Regs64bit = T == MVT::i128;
12213    EVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
12214    SDValue cpInL, cpInH;
12215    cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
12216                        DAG.getConstant(0, HalfT));
12217    cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
12218                        DAG.getConstant(1, HalfT));
12219    cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
12220                             Regs64bit ? X86::RAX : X86::EAX,
12221                             cpInL, SDValue());
12222    cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
12223                             Regs64bit ? X86::RDX : X86::EDX,
12224                             cpInH, cpInL.getValue(1));
12225    SDValue swapInL, swapInH;
12226    swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
12227                          DAG.getConstant(0, HalfT));
12228    swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
12229                          DAG.getConstant(1, HalfT));
12230    swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
12231                               Regs64bit ? X86::RBX : X86::EBX,
12232                               swapInL, cpInH.getValue(1));
12233    swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
12234                               Regs64bit ? X86::RCX : X86::ECX,
12235                               swapInH, swapInL.getValue(1));
12236    SDValue Ops[] = { swapInH.getValue(0),
12237                      N->getOperand(1),
12238                      swapInH.getValue(1) };
12239    SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
12240    MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
12241    unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
12242                                  X86ISD::LCMPXCHG8_DAG;
12243    SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys,
12244                                             Ops, 3, T, MMO);
12245    SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
12246                                        Regs64bit ? X86::RAX : X86::EAX,
12247                                        HalfT, Result.getValue(1));
12248    SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
12249                                        Regs64bit ? X86::RDX : X86::EDX,
12250                                        HalfT, cpOutL.getValue(2));
12251    SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
12252    Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF, 2));
12253    Results.push_back(cpOutH.getValue(1));
12254    return;
12255  }
12256  case ISD::ATOMIC_LOAD_ADD:
12257  case ISD::ATOMIC_LOAD_AND:
12258  case ISD::ATOMIC_LOAD_NAND:
12259  case ISD::ATOMIC_LOAD_OR:
12260  case ISD::ATOMIC_LOAD_SUB:
12261  case ISD::ATOMIC_LOAD_XOR:
12262  case ISD::ATOMIC_LOAD_MAX:
12263  case ISD::ATOMIC_LOAD_MIN:
12264  case ISD::ATOMIC_LOAD_UMAX:
12265  case ISD::ATOMIC_LOAD_UMIN:
12266  case ISD::ATOMIC_SWAP: {
12267    unsigned Opc;
12268    switch (N->getOpcode()) {
12269    default: llvm_unreachable("Unexpected opcode");
12270    case ISD::ATOMIC_LOAD_ADD:
12271      Opc = X86ISD::ATOMADD64_DAG;
12272      break;
12273    case ISD::ATOMIC_LOAD_AND:
12274      Opc = X86ISD::ATOMAND64_DAG;
12275      break;
12276    case ISD::ATOMIC_LOAD_NAND:
12277      Opc = X86ISD::ATOMNAND64_DAG;
12278      break;
12279    case ISD::ATOMIC_LOAD_OR:
12280      Opc = X86ISD::ATOMOR64_DAG;
12281      break;
12282    case ISD::ATOMIC_LOAD_SUB:
12283      Opc = X86ISD::ATOMSUB64_DAG;
12284      break;
12285    case ISD::ATOMIC_LOAD_XOR:
12286      Opc = X86ISD::ATOMXOR64_DAG;
12287      break;
12288    case ISD::ATOMIC_LOAD_MAX:
12289      Opc = X86ISD::ATOMMAX64_DAG;
12290      break;
12291    case ISD::ATOMIC_LOAD_MIN:
12292      Opc = X86ISD::ATOMMIN64_DAG;
12293      break;
12294    case ISD::ATOMIC_LOAD_UMAX:
12295      Opc = X86ISD::ATOMUMAX64_DAG;
12296      break;
12297    case ISD::ATOMIC_LOAD_UMIN:
12298      Opc = X86ISD::ATOMUMIN64_DAG;
12299      break;
12300    case ISD::ATOMIC_SWAP:
12301      Opc = X86ISD::ATOMSWAP64_DAG;
12302      break;
12303    }
12304    ReplaceATOMIC_BINARY_64(N, Results, DAG, Opc);
12305    return;
12306  }
12307  case ISD::ATOMIC_LOAD:
12308    ReplaceATOMIC_LOAD(N, Results, DAG);
12309  }
12310}
12311
12312const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
12313  switch (Opcode) {
12314  default: return NULL;
12315  case X86ISD::BSF:                return "X86ISD::BSF";
12316  case X86ISD::BSR:                return "X86ISD::BSR";
12317  case X86ISD::SHLD:               return "X86ISD::SHLD";
12318  case X86ISD::SHRD:               return "X86ISD::SHRD";
12319  case X86ISD::FAND:               return "X86ISD::FAND";
12320  case X86ISD::FOR:                return "X86ISD::FOR";
12321  case X86ISD::FXOR:               return "X86ISD::FXOR";
12322  case X86ISD::FSRL:               return "X86ISD::FSRL";
12323  case X86ISD::FILD:               return "X86ISD::FILD";
12324  case X86ISD::FILD_FLAG:          return "X86ISD::FILD_FLAG";
12325  case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
12326  case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
12327  case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
12328  case X86ISD::FLD:                return "X86ISD::FLD";
12329  case X86ISD::FST:                return "X86ISD::FST";
12330  case X86ISD::CALL:               return "X86ISD::CALL";
12331  case X86ISD::RDTSC_DAG:          return "X86ISD::RDTSC_DAG";
12332  case X86ISD::BT:                 return "X86ISD::BT";
12333  case X86ISD::CMP:                return "X86ISD::CMP";
12334  case X86ISD::COMI:               return "X86ISD::COMI";
12335  case X86ISD::UCOMI:              return "X86ISD::UCOMI";
12336  case X86ISD::SETCC:              return "X86ISD::SETCC";
12337  case X86ISD::SETCC_CARRY:        return "X86ISD::SETCC_CARRY";
12338  case X86ISD::FSETCCsd:           return "X86ISD::FSETCCsd";
12339  case X86ISD::FSETCCss:           return "X86ISD::FSETCCss";
12340  case X86ISD::CMOV:               return "X86ISD::CMOV";
12341  case X86ISD::BRCOND:             return "X86ISD::BRCOND";
12342  case X86ISD::RET_FLAG:           return "X86ISD::RET_FLAG";
12343  case X86ISD::REP_STOS:           return "X86ISD::REP_STOS";
12344  case X86ISD::REP_MOVS:           return "X86ISD::REP_MOVS";
12345  case X86ISD::GlobalBaseReg:      return "X86ISD::GlobalBaseReg";
12346  case X86ISD::Wrapper:            return "X86ISD::Wrapper";
12347  case X86ISD::WrapperRIP:         return "X86ISD::WrapperRIP";
12348  case X86ISD::PEXTRB:             return "X86ISD::PEXTRB";
12349  case X86ISD::PEXTRW:             return "X86ISD::PEXTRW";
12350  case X86ISD::INSERTPS:           return "X86ISD::INSERTPS";
12351  case X86ISD::PINSRB:             return "X86ISD::PINSRB";
12352  case X86ISD::PINSRW:             return "X86ISD::PINSRW";
12353  case X86ISD::PSHUFB:             return "X86ISD::PSHUFB";
12354  case X86ISD::ANDNP:              return "X86ISD::ANDNP";
12355  case X86ISD::PSIGN:              return "X86ISD::PSIGN";
12356  case X86ISD::BLENDV:             return "X86ISD::BLENDV";
12357  case X86ISD::BLENDI:             return "X86ISD::BLENDI";
12358  case X86ISD::SUBUS:              return "X86ISD::SUBUS";
12359  case X86ISD::HADD:               return "X86ISD::HADD";
12360  case X86ISD::HSUB:               return "X86ISD::HSUB";
12361  case X86ISD::FHADD:              return "X86ISD::FHADD";
12362  case X86ISD::FHSUB:              return "X86ISD::FHSUB";
12363  case X86ISD::UMAX:               return "X86ISD::UMAX";
12364  case X86ISD::UMIN:               return "X86ISD::UMIN";
12365  case X86ISD::SMAX:               return "X86ISD::SMAX";
12366  case X86ISD::SMIN:               return "X86ISD::SMIN";
12367  case X86ISD::FMAX:               return "X86ISD::FMAX";
12368  case X86ISD::FMIN:               return "X86ISD::FMIN";
12369  case X86ISD::FMAXC:              return "X86ISD::FMAXC";
12370  case X86ISD::FMINC:              return "X86ISD::FMINC";
12371  case X86ISD::FRSQRT:             return "X86ISD::FRSQRT";
12372  case X86ISD::FRCP:               return "X86ISD::FRCP";
12373  case X86ISD::TLSADDR:            return "X86ISD::TLSADDR";
12374  case X86ISD::TLSBASEADDR:        return "X86ISD::TLSBASEADDR";
12375  case X86ISD::TLSCALL:            return "X86ISD::TLSCALL";
12376  case X86ISD::EH_SJLJ_SETJMP:     return "X86ISD::EH_SJLJ_SETJMP";
12377  case X86ISD::EH_SJLJ_LONGJMP:    return "X86ISD::EH_SJLJ_LONGJMP";
12378  case X86ISD::EH_RETURN:          return "X86ISD::EH_RETURN";
12379  case X86ISD::TC_RETURN:          return "X86ISD::TC_RETURN";
12380  case X86ISD::FNSTCW16m:          return "X86ISD::FNSTCW16m";
12381  case X86ISD::FNSTSW16r:          return "X86ISD::FNSTSW16r";
12382  case X86ISD::LCMPXCHG_DAG:       return "X86ISD::LCMPXCHG_DAG";
12383  case X86ISD::LCMPXCHG8_DAG:      return "X86ISD::LCMPXCHG8_DAG";
12384  case X86ISD::ATOMADD64_DAG:      return "X86ISD::ATOMADD64_DAG";
12385  case X86ISD::ATOMSUB64_DAG:      return "X86ISD::ATOMSUB64_DAG";
12386  case X86ISD::ATOMOR64_DAG:       return "X86ISD::ATOMOR64_DAG";
12387  case X86ISD::ATOMXOR64_DAG:      return "X86ISD::ATOMXOR64_DAG";
12388  case X86ISD::ATOMAND64_DAG:      return "X86ISD::ATOMAND64_DAG";
12389  case X86ISD::ATOMNAND64_DAG:     return "X86ISD::ATOMNAND64_DAG";
12390  case X86ISD::VZEXT_MOVL:         return "X86ISD::VZEXT_MOVL";
12391  case X86ISD::VSEXT_MOVL:         return "X86ISD::VSEXT_MOVL";
12392  case X86ISD::VZEXT_LOAD:         return "X86ISD::VZEXT_LOAD";
12393  case X86ISD::VZEXT:              return "X86ISD::VZEXT";
12394  case X86ISD::VSEXT:              return "X86ISD::VSEXT";
12395  case X86ISD::VFPEXT:             return "X86ISD::VFPEXT";
12396  case X86ISD::VFPROUND:           return "X86ISD::VFPROUND";
12397  case X86ISD::VSHLDQ:             return "X86ISD::VSHLDQ";
12398  case X86ISD::VSRLDQ:             return "X86ISD::VSRLDQ";
12399  case X86ISD::VSHL:               return "X86ISD::VSHL";
12400  case X86ISD::VSRL:               return "X86ISD::VSRL";
12401  case X86ISD::VSRA:               return "X86ISD::VSRA";
12402  case X86ISD::VSHLI:              return "X86ISD::VSHLI";
12403  case X86ISD::VSRLI:              return "X86ISD::VSRLI";
12404  case X86ISD::VSRAI:              return "X86ISD::VSRAI";
12405  case X86ISD::CMPP:               return "X86ISD::CMPP";
12406  case X86ISD::PCMPEQ:             return "X86ISD::PCMPEQ";
12407  case X86ISD::PCMPGT:             return "X86ISD::PCMPGT";
12408  case X86ISD::ADD:                return "X86ISD::ADD";
12409  case X86ISD::SUB:                return "X86ISD::SUB";
12410  case X86ISD::ADC:                return "X86ISD::ADC";
12411  case X86ISD::SBB:                return "X86ISD::SBB";
12412  case X86ISD::SMUL:               return "X86ISD::SMUL";
12413  case X86ISD::UMUL:               return "X86ISD::UMUL";
12414  case X86ISD::INC:                return "X86ISD::INC";
12415  case X86ISD::DEC:                return "X86ISD::DEC";
12416  case X86ISD::OR:                 return "X86ISD::OR";
12417  case X86ISD::XOR:                return "X86ISD::XOR";
12418  case X86ISD::AND:                return "X86ISD::AND";
12419  case X86ISD::BLSI:               return "X86ISD::BLSI";
12420  case X86ISD::BLSMSK:             return "X86ISD::BLSMSK";
12421  case X86ISD::BLSR:               return "X86ISD::BLSR";
12422  case X86ISD::MUL_IMM:            return "X86ISD::MUL_IMM";
12423  case X86ISD::PTEST:              return "X86ISD::PTEST";
12424  case X86ISD::TESTP:              return "X86ISD::TESTP";
12425  case X86ISD::PALIGN:             return "X86ISD::PALIGN";
12426  case X86ISD::PSHUFD:             return "X86ISD::PSHUFD";
12427  case X86ISD::PSHUFHW:            return "X86ISD::PSHUFHW";
12428  case X86ISD::PSHUFLW:            return "X86ISD::PSHUFLW";
12429  case X86ISD::SHUFP:              return "X86ISD::SHUFP";
12430  case X86ISD::MOVLHPS:            return "X86ISD::MOVLHPS";
12431  case X86ISD::MOVLHPD:            return "X86ISD::MOVLHPD";
12432  case X86ISD::MOVHLPS:            return "X86ISD::MOVHLPS";
12433  case X86ISD::MOVLPS:             return "X86ISD::MOVLPS";
12434  case X86ISD::MOVLPD:             return "X86ISD::MOVLPD";
12435  case X86ISD::MOVDDUP:            return "X86ISD::MOVDDUP";
12436  case X86ISD::MOVSHDUP:           return "X86ISD::MOVSHDUP";
12437  case X86ISD::MOVSLDUP:           return "X86ISD::MOVSLDUP";
12438  case X86ISD::MOVSD:              return "X86ISD::MOVSD";
12439  case X86ISD::MOVSS:              return "X86ISD::MOVSS";
12440  case X86ISD::UNPCKL:             return "X86ISD::UNPCKL";
12441  case X86ISD::UNPCKH:             return "X86ISD::UNPCKH";
12442  case X86ISD::VBROADCAST:         return "X86ISD::VBROADCAST";
12443  case X86ISD::VPERMILP:           return "X86ISD::VPERMILP";
12444  case X86ISD::VPERM2X128:         return "X86ISD::VPERM2X128";
12445  case X86ISD::VPERMV:             return "X86ISD::VPERMV";
12446  case X86ISD::VPERMI:             return "X86ISD::VPERMI";
12447  case X86ISD::PMULUDQ:            return "X86ISD::PMULUDQ";
12448  case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
12449  case X86ISD::VAARG_64:           return "X86ISD::VAARG_64";
12450  case X86ISD::WIN_ALLOCA:         return "X86ISD::WIN_ALLOCA";
12451  case X86ISD::MEMBARRIER:         return "X86ISD::MEMBARRIER";
12452  case X86ISD::SEG_ALLOCA:         return "X86ISD::SEG_ALLOCA";
12453  case X86ISD::WIN_FTOL:           return "X86ISD::WIN_FTOL";
12454  case X86ISD::SAHF:               return "X86ISD::SAHF";
12455  case X86ISD::RDRAND:             return "X86ISD::RDRAND";
12456  case X86ISD::FMADD:              return "X86ISD::FMADD";
12457  case X86ISD::FMSUB:              return "X86ISD::FMSUB";
12458  case X86ISD::FNMADD:             return "X86ISD::FNMADD";
12459  case X86ISD::FNMSUB:             return "X86ISD::FNMSUB";
12460  case X86ISD::FMADDSUB:           return "X86ISD::FMADDSUB";
12461  case X86ISD::FMSUBADD:           return "X86ISD::FMSUBADD";
12462  case X86ISD::PCMPESTRI:          return "X86ISD::PCMPESTRI";
12463  case X86ISD::PCMPISTRI:          return "X86ISD::PCMPISTRI";
12464  }
12465}
12466
12467// isLegalAddressingMode - Return true if the addressing mode represented
12468// by AM is legal for this target, for a load/store of the specified type.
12469bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
12470                                              Type *Ty) const {
12471  // X86 supports extremely general addressing modes.
12472  CodeModel::Model M = getTargetMachine().getCodeModel();
12473  Reloc::Model R = getTargetMachine().getRelocationModel();
12474
12475  // X86 allows a sign-extended 32-bit immediate field as a displacement.
12476  if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != NULL))
12477    return false;
12478
12479  if (AM.BaseGV) {
12480    unsigned GVFlags =
12481      Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
12482
12483    // If a reference to this global requires an extra load, we can't fold it.
12484    if (isGlobalStubReference(GVFlags))
12485      return false;
12486
12487    // If BaseGV requires a register for the PIC base, we cannot also have a
12488    // BaseReg specified.
12489    if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
12490      return false;
12491
12492    // If lower 4G is not available, then we must use rip-relative addressing.
12493    if ((M != CodeModel::Small || R != Reloc::Static) &&
12494        Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
12495      return false;
12496  }
12497
12498  switch (AM.Scale) {
12499  case 0:
12500  case 1:
12501  case 2:
12502  case 4:
12503  case 8:
12504    // These scales always work.
12505    break;
12506  case 3:
12507  case 5:
12508  case 9:
12509    // These scales are formed with basereg+scalereg.  Only accept if there is
12510    // no basereg yet.
12511    if (AM.HasBaseReg)
12512      return false;
12513    break;
12514  default:  // Other stuff never works.
12515    return false;
12516  }
12517
12518  return true;
12519}
12520
12521bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
12522  if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
12523    return false;
12524  unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
12525  unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
12526  return NumBits1 > NumBits2;
12527}
12528
12529bool X86TargetLowering::isLegalICmpImmediate(int64_t Imm) const {
12530  return isInt<32>(Imm);
12531}
12532
12533bool X86TargetLowering::isLegalAddImmediate(int64_t Imm) const {
12534  // Can also use sub to handle negated immediates.
12535  return isInt<32>(Imm);
12536}
12537
12538bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
12539  if (!VT1.isInteger() || !VT2.isInteger())
12540    return false;
12541  unsigned NumBits1 = VT1.getSizeInBits();
12542  unsigned NumBits2 = VT2.getSizeInBits();
12543  return NumBits1 > NumBits2;
12544}
12545
12546bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
12547  // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
12548  return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
12549}
12550
12551bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
12552  // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
12553  return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
12554}
12555
12556bool X86TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
12557  EVT VT1 = Val.getValueType();
12558  if (isZExtFree(VT1, VT2))
12559    return true;
12560
12561  if (Val.getOpcode() != ISD::LOAD)
12562    return false;
12563
12564  if (!VT1.isSimple() || !VT1.isInteger() ||
12565      !VT2.isSimple() || !VT2.isInteger())
12566    return false;
12567
12568  switch (VT1.getSimpleVT().SimpleTy) {
12569  default: break;
12570  case MVT::i8:
12571  case MVT::i16:
12572  case MVT::i32:
12573    // X86 has 8, 16, and 32-bit zero-extending loads.
12574    return true;
12575  }
12576
12577  return false;
12578}
12579
12580bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
12581  // i16 instructions are longer (0x66 prefix) and potentially slower.
12582  return !(VT1 == MVT::i32 && VT2 == MVT::i16);
12583}
12584
12585/// isShuffleMaskLegal - Targets can use this to indicate that they only
12586/// support *some* VECTOR_SHUFFLE operations, those with specific masks.
12587/// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
12588/// are assumed to be legal.
12589bool
12590X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
12591                                      EVT VT) const {
12592  // Very little shuffling can be done for 64-bit vectors right now.
12593  if (VT.getSizeInBits() == 64)
12594    return false;
12595
12596  // FIXME: pshufb, blends, shifts.
12597  return (VT.getVectorNumElements() == 2 ||
12598          ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
12599          isMOVLMask(M, VT) ||
12600          isSHUFPMask(M, VT, Subtarget->hasFp256()) ||
12601          isPSHUFDMask(M, VT) ||
12602          isPSHUFHWMask(M, VT, Subtarget->hasInt256()) ||
12603          isPSHUFLWMask(M, VT, Subtarget->hasInt256()) ||
12604          isPALIGNRMask(M, VT, Subtarget) ||
12605          isUNPCKLMask(M, VT, Subtarget->hasInt256()) ||
12606          isUNPCKHMask(M, VT, Subtarget->hasInt256()) ||
12607          isUNPCKL_v_undef_Mask(M, VT, Subtarget->hasInt256()) ||
12608          isUNPCKH_v_undef_Mask(M, VT, Subtarget->hasInt256()));
12609}
12610
12611bool
12612X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
12613                                          EVT VT) const {
12614  unsigned NumElts = VT.getVectorNumElements();
12615  // FIXME: This collection of masks seems suspect.
12616  if (NumElts == 2)
12617    return true;
12618  if (NumElts == 4 && VT.is128BitVector()) {
12619    return (isMOVLMask(Mask, VT)  ||
12620            isCommutedMOVLMask(Mask, VT, true) ||
12621            isSHUFPMask(Mask, VT, Subtarget->hasFp256()) ||
12622            isSHUFPMask(Mask, VT, Subtarget->hasFp256(), /* Commuted */ true));
12623  }
12624  return false;
12625}
12626
12627//===----------------------------------------------------------------------===//
12628//                           X86 Scheduler Hooks
12629//===----------------------------------------------------------------------===//
12630
12631/// Utility function to emit xbegin specifying the start of an RTM region.
12632static MachineBasicBlock *EmitXBegin(MachineInstr *MI, MachineBasicBlock *MBB,
12633                                     const TargetInstrInfo *TII) {
12634  DebugLoc DL = MI->getDebugLoc();
12635
12636  const BasicBlock *BB = MBB->getBasicBlock();
12637  MachineFunction::iterator I = MBB;
12638  ++I;
12639
12640  // For the v = xbegin(), we generate
12641  //
12642  // thisMBB:
12643  //  xbegin sinkMBB
12644  //
12645  // mainMBB:
12646  //  eax = -1
12647  //
12648  // sinkMBB:
12649  //  v = eax
12650
12651  MachineBasicBlock *thisMBB = MBB;
12652  MachineFunction *MF = MBB->getParent();
12653  MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
12654  MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
12655  MF->insert(I, mainMBB);
12656  MF->insert(I, sinkMBB);
12657
12658  // Transfer the remainder of BB and its successor edges to sinkMBB.
12659  sinkMBB->splice(sinkMBB->begin(), MBB,
12660                  llvm::next(MachineBasicBlock::iterator(MI)), MBB->end());
12661  sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
12662
12663  // thisMBB:
12664  //  xbegin sinkMBB
12665  //  # fallthrough to mainMBB
12666  //  # abortion to sinkMBB
12667  BuildMI(thisMBB, DL, TII->get(X86::XBEGIN_4)).addMBB(sinkMBB);
12668  thisMBB->addSuccessor(mainMBB);
12669  thisMBB->addSuccessor(sinkMBB);
12670
12671  // mainMBB:
12672  //  EAX = -1
12673  BuildMI(mainMBB, DL, TII->get(X86::MOV32ri), X86::EAX).addImm(-1);
12674  mainMBB->addSuccessor(sinkMBB);
12675
12676  // sinkMBB:
12677  // EAX is live into the sinkMBB
12678  sinkMBB->addLiveIn(X86::EAX);
12679  BuildMI(*sinkMBB, sinkMBB->begin(), DL,
12680          TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
12681    .addReg(X86::EAX);
12682
12683  MI->eraseFromParent();
12684  return sinkMBB;
12685}
12686
12687// Get CMPXCHG opcode for the specified data type.
12688static unsigned getCmpXChgOpcode(EVT VT) {
12689  switch (VT.getSimpleVT().SimpleTy) {
12690  case MVT::i8:  return X86::LCMPXCHG8;
12691  case MVT::i16: return X86::LCMPXCHG16;
12692  case MVT::i32: return X86::LCMPXCHG32;
12693  case MVT::i64: return X86::LCMPXCHG64;
12694  default:
12695    break;
12696  }
12697  llvm_unreachable("Invalid operand size!");
12698}
12699
12700// Get LOAD opcode for the specified data type.
12701static unsigned getLoadOpcode(EVT VT) {
12702  switch (VT.getSimpleVT().SimpleTy) {
12703  case MVT::i8:  return X86::MOV8rm;
12704  case MVT::i16: return X86::MOV16rm;
12705  case MVT::i32: return X86::MOV32rm;
12706  case MVT::i64: return X86::MOV64rm;
12707  default:
12708    break;
12709  }
12710  llvm_unreachable("Invalid operand size!");
12711}
12712
12713// Get opcode of the non-atomic one from the specified atomic instruction.
12714static unsigned getNonAtomicOpcode(unsigned Opc) {
12715  switch (Opc) {
12716  case X86::ATOMAND8:  return X86::AND8rr;
12717  case X86::ATOMAND16: return X86::AND16rr;
12718  case X86::ATOMAND32: return X86::AND32rr;
12719  case X86::ATOMAND64: return X86::AND64rr;
12720  case X86::ATOMOR8:   return X86::OR8rr;
12721  case X86::ATOMOR16:  return X86::OR16rr;
12722  case X86::ATOMOR32:  return X86::OR32rr;
12723  case X86::ATOMOR64:  return X86::OR64rr;
12724  case X86::ATOMXOR8:  return X86::XOR8rr;
12725  case X86::ATOMXOR16: return X86::XOR16rr;
12726  case X86::ATOMXOR32: return X86::XOR32rr;
12727  case X86::ATOMXOR64: return X86::XOR64rr;
12728  }
12729  llvm_unreachable("Unhandled atomic-load-op opcode!");
12730}
12731
12732// Get opcode of the non-atomic one from the specified atomic instruction with
12733// extra opcode.
12734static unsigned getNonAtomicOpcodeWithExtraOpc(unsigned Opc,
12735                                               unsigned &ExtraOpc) {
12736  switch (Opc) {
12737  case X86::ATOMNAND8:  ExtraOpc = X86::NOT8r;   return X86::AND8rr;
12738  case X86::ATOMNAND16: ExtraOpc = X86::NOT16r;  return X86::AND16rr;
12739  case X86::ATOMNAND32: ExtraOpc = X86::NOT32r;  return X86::AND32rr;
12740  case X86::ATOMNAND64: ExtraOpc = X86::NOT64r;  return X86::AND64rr;
12741  case X86::ATOMMAX8:   ExtraOpc = X86::CMP8rr;  return X86::CMOVL32rr;
12742  case X86::ATOMMAX16:  ExtraOpc = X86::CMP16rr; return X86::CMOVL16rr;
12743  case X86::ATOMMAX32:  ExtraOpc = X86::CMP32rr; return X86::CMOVL32rr;
12744  case X86::ATOMMAX64:  ExtraOpc = X86::CMP64rr; return X86::CMOVL64rr;
12745  case X86::ATOMMIN8:   ExtraOpc = X86::CMP8rr;  return X86::CMOVG32rr;
12746  case X86::ATOMMIN16:  ExtraOpc = X86::CMP16rr; return X86::CMOVG16rr;
12747  case X86::ATOMMIN32:  ExtraOpc = X86::CMP32rr; return X86::CMOVG32rr;
12748  case X86::ATOMMIN64:  ExtraOpc = X86::CMP64rr; return X86::CMOVG64rr;
12749  case X86::ATOMUMAX8:  ExtraOpc = X86::CMP8rr;  return X86::CMOVB32rr;
12750  case X86::ATOMUMAX16: ExtraOpc = X86::CMP16rr; return X86::CMOVB16rr;
12751  case X86::ATOMUMAX32: ExtraOpc = X86::CMP32rr; return X86::CMOVB32rr;
12752  case X86::ATOMUMAX64: ExtraOpc = X86::CMP64rr; return X86::CMOVB64rr;
12753  case X86::ATOMUMIN8:  ExtraOpc = X86::CMP8rr;  return X86::CMOVA32rr;
12754  case X86::ATOMUMIN16: ExtraOpc = X86::CMP16rr; return X86::CMOVA16rr;
12755  case X86::ATOMUMIN32: ExtraOpc = X86::CMP32rr; return X86::CMOVA32rr;
12756  case X86::ATOMUMIN64: ExtraOpc = X86::CMP64rr; return X86::CMOVA64rr;
12757  }
12758  llvm_unreachable("Unhandled atomic-load-op opcode!");
12759}
12760
12761// Get opcode of the non-atomic one from the specified atomic instruction for
12762// 64-bit data type on 32-bit target.
12763static unsigned getNonAtomic6432Opcode(unsigned Opc, unsigned &HiOpc) {
12764  switch (Opc) {
12765  case X86::ATOMAND6432:  HiOpc = X86::AND32rr; return X86::AND32rr;
12766  case X86::ATOMOR6432:   HiOpc = X86::OR32rr;  return X86::OR32rr;
12767  case X86::ATOMXOR6432:  HiOpc = X86::XOR32rr; return X86::XOR32rr;
12768  case X86::ATOMADD6432:  HiOpc = X86::ADC32rr; return X86::ADD32rr;
12769  case X86::ATOMSUB6432:  HiOpc = X86::SBB32rr; return X86::SUB32rr;
12770  case X86::ATOMSWAP6432: HiOpc = X86::MOV32rr; return X86::MOV32rr;
12771  case X86::ATOMMAX6432:  HiOpc = X86::SETLr;   return X86::SETLr;
12772  case X86::ATOMMIN6432:  HiOpc = X86::SETGr;   return X86::SETGr;
12773  case X86::ATOMUMAX6432: HiOpc = X86::SETBr;   return X86::SETBr;
12774  case X86::ATOMUMIN6432: HiOpc = X86::SETAr;   return X86::SETAr;
12775  }
12776  llvm_unreachable("Unhandled atomic-load-op opcode!");
12777}
12778
12779// Get opcode of the non-atomic one from the specified atomic instruction for
12780// 64-bit data type on 32-bit target with extra opcode.
12781static unsigned getNonAtomic6432OpcodeWithExtraOpc(unsigned Opc,
12782                                                   unsigned &HiOpc,
12783                                                   unsigned &ExtraOpc) {
12784  switch (Opc) {
12785  case X86::ATOMNAND6432:
12786    ExtraOpc = X86::NOT32r;
12787    HiOpc = X86::AND32rr;
12788    return X86::AND32rr;
12789  }
12790  llvm_unreachable("Unhandled atomic-load-op opcode!");
12791}
12792
12793// Get pseudo CMOV opcode from the specified data type.
12794static unsigned getPseudoCMOVOpc(EVT VT) {
12795  switch (VT.getSimpleVT().SimpleTy) {
12796  case MVT::i8:  return X86::CMOV_GR8;
12797  case MVT::i16: return X86::CMOV_GR16;
12798  case MVT::i32: return X86::CMOV_GR32;
12799  default:
12800    break;
12801  }
12802  llvm_unreachable("Unknown CMOV opcode!");
12803}
12804
12805// EmitAtomicLoadArith - emit the code sequence for pseudo atomic instructions.
12806// They will be translated into a spin-loop or compare-exchange loop from
12807//
12808//    ...
12809//    dst = atomic-fetch-op MI.addr, MI.val
12810//    ...
12811//
12812// to
12813//
12814//    ...
12815//    EAX = LOAD MI.addr
12816// loop:
12817//    t1 = OP MI.val, EAX
12818//    LCMPXCHG [MI.addr], t1, [EAX is implicitly used & defined]
12819//    JNE loop
12820// sink:
12821//    dst = EAX
12822//    ...
12823MachineBasicBlock *
12824X86TargetLowering::EmitAtomicLoadArith(MachineInstr *MI,
12825                                       MachineBasicBlock *MBB) const {
12826  const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12827  DebugLoc DL = MI->getDebugLoc();
12828
12829  MachineFunction *MF = MBB->getParent();
12830  MachineRegisterInfo &MRI = MF->getRegInfo();
12831
12832  const BasicBlock *BB = MBB->getBasicBlock();
12833  MachineFunction::iterator I = MBB;
12834  ++I;
12835
12836  assert(MI->getNumOperands() <= X86::AddrNumOperands + 2 &&
12837         "Unexpected number of operands");
12838
12839  assert(MI->hasOneMemOperand() &&
12840         "Expected atomic-load-op to have one memoperand");
12841
12842  // Memory Reference
12843  MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
12844  MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
12845
12846  unsigned DstReg, SrcReg;
12847  unsigned MemOpndSlot;
12848
12849  unsigned CurOp = 0;
12850
12851  DstReg = MI->getOperand(CurOp++).getReg();
12852  MemOpndSlot = CurOp;
12853  CurOp += X86::AddrNumOperands;
12854  SrcReg = MI->getOperand(CurOp++).getReg();
12855
12856  const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
12857  MVT::SimpleValueType VT = *RC->vt_begin();
12858  unsigned AccPhyReg = getX86SubSuperRegister(X86::EAX, VT);
12859
12860  unsigned LCMPXCHGOpc = getCmpXChgOpcode(VT);
12861  unsigned LOADOpc = getLoadOpcode(VT);
12862
12863  // For the atomic load-arith operator, we generate
12864  //
12865  //  thisMBB:
12866  //    EAX = LOAD [MI.addr]
12867  //  mainMBB:
12868  //    t1 = OP MI.val, EAX
12869  //    LCMPXCHG [MI.addr], t1, [EAX is implicitly used & defined]
12870  //    JNE mainMBB
12871  //  sinkMBB:
12872
12873  MachineBasicBlock *thisMBB = MBB;
12874  MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
12875  MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
12876  MF->insert(I, mainMBB);
12877  MF->insert(I, sinkMBB);
12878
12879  MachineInstrBuilder MIB;
12880
12881  // Transfer the remainder of BB and its successor edges to sinkMBB.
12882  sinkMBB->splice(sinkMBB->begin(), MBB,
12883                  llvm::next(MachineBasicBlock::iterator(MI)), MBB->end());
12884  sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
12885
12886  // thisMBB:
12887  MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), AccPhyReg);
12888  for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
12889    MIB.addOperand(MI->getOperand(MemOpndSlot + i));
12890  MIB.setMemRefs(MMOBegin, MMOEnd);
12891
12892  thisMBB->addSuccessor(mainMBB);
12893
12894  // mainMBB:
12895  MachineBasicBlock *origMainMBB = mainMBB;
12896  mainMBB->addLiveIn(AccPhyReg);
12897
12898  // Copy AccPhyReg as it is used more than once.
12899  unsigned AccReg = MRI.createVirtualRegister(RC);
12900  BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), AccReg)
12901    .addReg(AccPhyReg);
12902
12903  unsigned t1 = MRI.createVirtualRegister(RC);
12904  unsigned Opc = MI->getOpcode();
12905  switch (Opc) {
12906  default:
12907    llvm_unreachable("Unhandled atomic-load-op opcode!");
12908  case X86::ATOMAND8:
12909  case X86::ATOMAND16:
12910  case X86::ATOMAND32:
12911  case X86::ATOMAND64:
12912  case X86::ATOMOR8:
12913  case X86::ATOMOR16:
12914  case X86::ATOMOR32:
12915  case X86::ATOMOR64:
12916  case X86::ATOMXOR8:
12917  case X86::ATOMXOR16:
12918  case X86::ATOMXOR32:
12919  case X86::ATOMXOR64: {
12920    unsigned ARITHOpc = getNonAtomicOpcode(Opc);
12921    BuildMI(mainMBB, DL, TII->get(ARITHOpc), t1).addReg(SrcReg)
12922      .addReg(AccReg);
12923    break;
12924  }
12925  case X86::ATOMNAND8:
12926  case X86::ATOMNAND16:
12927  case X86::ATOMNAND32:
12928  case X86::ATOMNAND64: {
12929    unsigned t2 = MRI.createVirtualRegister(RC);
12930    unsigned NOTOpc;
12931    unsigned ANDOpc = getNonAtomicOpcodeWithExtraOpc(Opc, NOTOpc);
12932    BuildMI(mainMBB, DL, TII->get(ANDOpc), t2).addReg(SrcReg)
12933      .addReg(AccReg);
12934    BuildMI(mainMBB, DL, TII->get(NOTOpc), t1).addReg(t2);
12935    break;
12936  }
12937  case X86::ATOMMAX8:
12938  case X86::ATOMMAX16:
12939  case X86::ATOMMAX32:
12940  case X86::ATOMMAX64:
12941  case X86::ATOMMIN8:
12942  case X86::ATOMMIN16:
12943  case X86::ATOMMIN32:
12944  case X86::ATOMMIN64:
12945  case X86::ATOMUMAX8:
12946  case X86::ATOMUMAX16:
12947  case X86::ATOMUMAX32:
12948  case X86::ATOMUMAX64:
12949  case X86::ATOMUMIN8:
12950  case X86::ATOMUMIN16:
12951  case X86::ATOMUMIN32:
12952  case X86::ATOMUMIN64: {
12953    unsigned CMPOpc;
12954    unsigned CMOVOpc = getNonAtomicOpcodeWithExtraOpc(Opc, CMPOpc);
12955
12956    BuildMI(mainMBB, DL, TII->get(CMPOpc))
12957      .addReg(SrcReg)
12958      .addReg(AccReg);
12959
12960    if (Subtarget->hasCMov()) {
12961      if (VT != MVT::i8) {
12962        // Native support
12963        BuildMI(mainMBB, DL, TII->get(CMOVOpc), t1)
12964          .addReg(SrcReg)
12965          .addReg(AccReg);
12966      } else {
12967        // Promote i8 to i32 to use CMOV32
12968        const TargetRegisterClass *RC32 = getRegClassFor(MVT::i32);
12969        unsigned SrcReg32 = MRI.createVirtualRegister(RC32);
12970        unsigned AccReg32 = MRI.createVirtualRegister(RC32);
12971        unsigned t2 = MRI.createVirtualRegister(RC32);
12972
12973        unsigned Undef = MRI.createVirtualRegister(RC32);
12974        BuildMI(mainMBB, DL, TII->get(TargetOpcode::IMPLICIT_DEF), Undef);
12975
12976        BuildMI(mainMBB, DL, TII->get(TargetOpcode::INSERT_SUBREG), SrcReg32)
12977          .addReg(Undef)
12978          .addReg(SrcReg)
12979          .addImm(X86::sub_8bit);
12980        BuildMI(mainMBB, DL, TII->get(TargetOpcode::INSERT_SUBREG), AccReg32)
12981          .addReg(Undef)
12982          .addReg(AccReg)
12983          .addImm(X86::sub_8bit);
12984
12985        BuildMI(mainMBB, DL, TII->get(CMOVOpc), t2)
12986          .addReg(SrcReg32)
12987          .addReg(AccReg32);
12988
12989        BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t1)
12990          .addReg(t2, 0, X86::sub_8bit);
12991      }
12992    } else {
12993      // Use pseudo select and lower them.
12994      assert((VT == MVT::i8 || VT == MVT::i16 || VT == MVT::i32) &&
12995             "Invalid atomic-load-op transformation!");
12996      unsigned SelOpc = getPseudoCMOVOpc(VT);
12997      X86::CondCode CC = X86::getCondFromCMovOpc(CMOVOpc);
12998      assert(CC != X86::COND_INVALID && "Invalid atomic-load-op transformation!");
12999      MIB = BuildMI(mainMBB, DL, TII->get(SelOpc), t1)
13000              .addReg(SrcReg).addReg(AccReg)
13001              .addImm(CC);
13002      mainMBB = EmitLoweredSelect(MIB, mainMBB);
13003    }
13004    break;
13005  }
13006  }
13007
13008  // Copy AccPhyReg back from virtual register.
13009  BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), AccPhyReg)
13010    .addReg(AccReg);
13011
13012  MIB = BuildMI(mainMBB, DL, TII->get(LCMPXCHGOpc));
13013  for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
13014    MIB.addOperand(MI->getOperand(MemOpndSlot + i));
13015  MIB.addReg(t1);
13016  MIB.setMemRefs(MMOBegin, MMOEnd);
13017
13018  BuildMI(mainMBB, DL, TII->get(X86::JNE_4)).addMBB(origMainMBB);
13019
13020  mainMBB->addSuccessor(origMainMBB);
13021  mainMBB->addSuccessor(sinkMBB);
13022
13023  // sinkMBB:
13024  sinkMBB->addLiveIn(AccPhyReg);
13025
13026  BuildMI(*sinkMBB, sinkMBB->begin(), DL,
13027          TII->get(TargetOpcode::COPY), DstReg)
13028    .addReg(AccPhyReg);
13029
13030  MI->eraseFromParent();
13031  return sinkMBB;
13032}
13033
13034// EmitAtomicLoadArith6432 - emit the code sequence for pseudo atomic
13035// instructions. They will be translated into a spin-loop or compare-exchange
13036// loop from
13037//
13038//    ...
13039//    dst = atomic-fetch-op MI.addr, MI.val
13040//    ...
13041//
13042// to
13043//
13044//    ...
13045//    EAX = LOAD [MI.addr + 0]
13046//    EDX = LOAD [MI.addr + 4]
13047// loop:
13048//    EBX = OP MI.val.lo, EAX
13049//    ECX = OP MI.val.hi, EDX
13050//    LCMPXCHG8B [MI.addr], [ECX:EBX & EDX:EAX are implicitly used and EDX:EAX is implicitly defined]
13051//    JNE loop
13052// sink:
13053//    dst = EDX:EAX
13054//    ...
13055MachineBasicBlock *
13056X86TargetLowering::EmitAtomicLoadArith6432(MachineInstr *MI,
13057                                           MachineBasicBlock *MBB) const {
13058  const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
13059  DebugLoc DL = MI->getDebugLoc();
13060
13061  MachineFunction *MF = MBB->getParent();
13062  MachineRegisterInfo &MRI = MF->getRegInfo();
13063
13064  const BasicBlock *BB = MBB->getBasicBlock();
13065  MachineFunction::iterator I = MBB;
13066  ++I;
13067
13068  assert(MI->getNumOperands() <= X86::AddrNumOperands + 4 &&
13069         "Unexpected number of operands");
13070
13071  assert(MI->hasOneMemOperand() &&
13072         "Expected atomic-load-op32 to have one memoperand");
13073
13074  // Memory Reference
13075  MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
13076  MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
13077
13078  unsigned DstLoReg, DstHiReg;
13079  unsigned SrcLoReg, SrcHiReg;
13080  unsigned MemOpndSlot;
13081
13082  unsigned CurOp = 0;
13083
13084  DstLoReg = MI->getOperand(CurOp++).getReg();
13085  DstHiReg = MI->getOperand(CurOp++).getReg();
13086  MemOpndSlot = CurOp;
13087  CurOp += X86::AddrNumOperands;
13088  SrcLoReg = MI->getOperand(CurOp++).getReg();
13089  SrcHiReg = MI->getOperand(CurOp++).getReg();
13090
13091  const TargetRegisterClass *RC = &X86::GR32RegClass;
13092  const TargetRegisterClass *RC8 = &X86::GR8RegClass;
13093
13094  unsigned LCMPXCHGOpc = X86::LCMPXCHG8B;
13095  unsigned LOADOpc = X86::MOV32rm;
13096
13097  // For the atomic load-arith operator, we generate
13098  //
13099  //  thisMBB:
13100  //    EAX = LOAD [MI.addr + 0]
13101  //    EDX = LOAD [MI.addr + 4]
13102  //  mainMBB:
13103  //    EBX = OP MI.vallo, EAX
13104  //    ECX = OP MI.valhi, EDX
13105  //    LCMPXCHG8B [MI.addr], [ECX:EBX & EDX:EAX are implicitly used and EDX:EAX is implicitly defined]
13106  //    JNE mainMBB
13107  //  sinkMBB:
13108
13109  MachineBasicBlock *thisMBB = MBB;
13110  MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
13111  MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
13112  MF->insert(I, mainMBB);
13113  MF->insert(I, sinkMBB);
13114
13115  MachineInstrBuilder MIB;
13116
13117  // Transfer the remainder of BB and its successor edges to sinkMBB.
13118  sinkMBB->splice(sinkMBB->begin(), MBB,
13119                  llvm::next(MachineBasicBlock::iterator(MI)), MBB->end());
13120  sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
13121
13122  // thisMBB:
13123  // Lo
13124  MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), X86::EAX);
13125  for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
13126    MIB.addOperand(MI->getOperand(MemOpndSlot + i));
13127  MIB.setMemRefs(MMOBegin, MMOEnd);
13128  // Hi
13129  MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), X86::EDX);
13130  for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
13131    if (i == X86::AddrDisp)
13132      MIB.addDisp(MI->getOperand(MemOpndSlot + i), 4); // 4 == sizeof(i32)
13133    else
13134      MIB.addOperand(MI->getOperand(MemOpndSlot + i));
13135  }
13136  MIB.setMemRefs(MMOBegin, MMOEnd);
13137
13138  thisMBB->addSuccessor(mainMBB);
13139
13140  // mainMBB:
13141  MachineBasicBlock *origMainMBB = mainMBB;
13142  mainMBB->addLiveIn(X86::EAX);
13143  mainMBB->addLiveIn(X86::EDX);
13144
13145  // Copy EDX:EAX as they are used more than once.
13146  unsigned LoReg = MRI.createVirtualRegister(RC);
13147  unsigned HiReg = MRI.createVirtualRegister(RC);
13148  BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), LoReg).addReg(X86::EAX);
13149  BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), HiReg).addReg(X86::EDX);
13150
13151  unsigned t1L = MRI.createVirtualRegister(RC);
13152  unsigned t1H = MRI.createVirtualRegister(RC);
13153
13154  unsigned Opc = MI->getOpcode();
13155  switch (Opc) {
13156  default:
13157    llvm_unreachable("Unhandled atomic-load-op6432 opcode!");
13158  case X86::ATOMAND6432:
13159  case X86::ATOMOR6432:
13160  case X86::ATOMXOR6432:
13161  case X86::ATOMADD6432:
13162  case X86::ATOMSUB6432: {
13163    unsigned HiOpc;
13164    unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
13165    BuildMI(mainMBB, DL, TII->get(LoOpc), t1L).addReg(LoReg).addReg(SrcLoReg);
13166    BuildMI(mainMBB, DL, TII->get(HiOpc), t1H).addReg(HiReg).addReg(SrcHiReg);
13167    break;
13168  }
13169  case X86::ATOMNAND6432: {
13170    unsigned HiOpc, NOTOpc;
13171    unsigned LoOpc = getNonAtomic6432OpcodeWithExtraOpc(Opc, HiOpc, NOTOpc);
13172    unsigned t2L = MRI.createVirtualRegister(RC);
13173    unsigned t2H = MRI.createVirtualRegister(RC);
13174    BuildMI(mainMBB, DL, TII->get(LoOpc), t2L).addReg(SrcLoReg).addReg(LoReg);
13175    BuildMI(mainMBB, DL, TII->get(HiOpc), t2H).addReg(SrcHiReg).addReg(HiReg);
13176    BuildMI(mainMBB, DL, TII->get(NOTOpc), t1L).addReg(t2L);
13177    BuildMI(mainMBB, DL, TII->get(NOTOpc), t1H).addReg(t2H);
13178    break;
13179  }
13180  case X86::ATOMMAX6432:
13181  case X86::ATOMMIN6432:
13182  case X86::ATOMUMAX6432:
13183  case X86::ATOMUMIN6432: {
13184    unsigned HiOpc;
13185    unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
13186    unsigned cL = MRI.createVirtualRegister(RC8);
13187    unsigned cH = MRI.createVirtualRegister(RC8);
13188    unsigned cL32 = MRI.createVirtualRegister(RC);
13189    unsigned cH32 = MRI.createVirtualRegister(RC);
13190    unsigned cc = MRI.createVirtualRegister(RC);
13191    // cl := cmp src_lo, lo
13192    BuildMI(mainMBB, DL, TII->get(X86::CMP32rr))
13193      .addReg(SrcLoReg).addReg(LoReg);
13194    BuildMI(mainMBB, DL, TII->get(LoOpc), cL);
13195    BuildMI(mainMBB, DL, TII->get(X86::MOVZX32rr8), cL32).addReg(cL);
13196    // ch := cmp src_hi, hi
13197    BuildMI(mainMBB, DL, TII->get(X86::CMP32rr))
13198      .addReg(SrcHiReg).addReg(HiReg);
13199    BuildMI(mainMBB, DL, TII->get(HiOpc), cH);
13200    BuildMI(mainMBB, DL, TII->get(X86::MOVZX32rr8), cH32).addReg(cH);
13201    // cc := if (src_hi == hi) ? cl : ch;
13202    if (Subtarget->hasCMov()) {
13203      BuildMI(mainMBB, DL, TII->get(X86::CMOVE32rr), cc)
13204        .addReg(cH32).addReg(cL32);
13205    } else {
13206      MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), cc)
13207              .addReg(cH32).addReg(cL32)
13208              .addImm(X86::COND_E);
13209      mainMBB = EmitLoweredSelect(MIB, mainMBB);
13210    }
13211    BuildMI(mainMBB, DL, TII->get(X86::TEST32rr)).addReg(cc).addReg(cc);
13212    if (Subtarget->hasCMov()) {
13213      BuildMI(mainMBB, DL, TII->get(X86::CMOVNE32rr), t1L)
13214        .addReg(SrcLoReg).addReg(LoReg);
13215      BuildMI(mainMBB, DL, TII->get(X86::CMOVNE32rr), t1H)
13216        .addReg(SrcHiReg).addReg(HiReg);
13217    } else {
13218      MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), t1L)
13219              .addReg(SrcLoReg).addReg(LoReg)
13220              .addImm(X86::COND_NE);
13221      mainMBB = EmitLoweredSelect(MIB, mainMBB);
13222      MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), t1H)
13223              .addReg(SrcHiReg).addReg(HiReg)
13224              .addImm(X86::COND_NE);
13225      mainMBB = EmitLoweredSelect(MIB, mainMBB);
13226    }
13227    break;
13228  }
13229  case X86::ATOMSWAP6432: {
13230    unsigned HiOpc;
13231    unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
13232    BuildMI(mainMBB, DL, TII->get(LoOpc), t1L).addReg(SrcLoReg);
13233    BuildMI(mainMBB, DL, TII->get(HiOpc), t1H).addReg(SrcHiReg);
13234    break;
13235  }
13236  }
13237
13238  // Copy EDX:EAX back from HiReg:LoReg
13239  BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EAX).addReg(LoReg);
13240  BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EDX).addReg(HiReg);
13241  // Copy ECX:EBX from t1H:t1L
13242  BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EBX).addReg(t1L);
13243  BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::ECX).addReg(t1H);
13244
13245  MIB = BuildMI(mainMBB, DL, TII->get(LCMPXCHGOpc));
13246  for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
13247    MIB.addOperand(MI->getOperand(MemOpndSlot + i));
13248  MIB.setMemRefs(MMOBegin, MMOEnd);
13249
13250  BuildMI(mainMBB, DL, TII->get(X86::JNE_4)).addMBB(origMainMBB);
13251
13252  mainMBB->addSuccessor(origMainMBB);
13253  mainMBB->addSuccessor(sinkMBB);
13254
13255  // sinkMBB:
13256  sinkMBB->addLiveIn(X86::EAX);
13257  sinkMBB->addLiveIn(X86::EDX);
13258
13259  BuildMI(*sinkMBB, sinkMBB->begin(), DL,
13260          TII->get(TargetOpcode::COPY), DstLoReg)
13261    .addReg(X86::EAX);
13262  BuildMI(*sinkMBB, sinkMBB->begin(), DL,
13263          TII->get(TargetOpcode::COPY), DstHiReg)
13264    .addReg(X86::EDX);
13265
13266  MI->eraseFromParent();
13267  return sinkMBB;
13268}
13269
13270// FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
13271// or XMM0_V32I8 in AVX all of this code can be replaced with that
13272// in the .td file.
13273static MachineBasicBlock *EmitPCMPSTRM(MachineInstr *MI, MachineBasicBlock *BB,
13274                                       const TargetInstrInfo *TII) {
13275  unsigned Opc;
13276  switch (MI->getOpcode()) {
13277  default: llvm_unreachable("illegal opcode!");
13278  case X86::PCMPISTRM128REG:  Opc = X86::PCMPISTRM128rr;  break;
13279  case X86::VPCMPISTRM128REG: Opc = X86::VPCMPISTRM128rr; break;
13280  case X86::PCMPISTRM128MEM:  Opc = X86::PCMPISTRM128rm;  break;
13281  case X86::VPCMPISTRM128MEM: Opc = X86::VPCMPISTRM128rm; break;
13282  case X86::PCMPESTRM128REG:  Opc = X86::PCMPESTRM128rr;  break;
13283  case X86::VPCMPESTRM128REG: Opc = X86::VPCMPESTRM128rr; break;
13284  case X86::PCMPESTRM128MEM:  Opc = X86::PCMPESTRM128rm;  break;
13285  case X86::VPCMPESTRM128MEM: Opc = X86::VPCMPESTRM128rm; break;
13286  }
13287
13288  DebugLoc dl = MI->getDebugLoc();
13289  MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
13290
13291  unsigned NumArgs = MI->getNumOperands();
13292  for (unsigned i = 1; i < NumArgs; ++i) {
13293    MachineOperand &Op = MI->getOperand(i);
13294    if (!(Op.isReg() && Op.isImplicit()))
13295      MIB.addOperand(Op);
13296  }
13297  if (MI->hasOneMemOperand())
13298    MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
13299
13300  BuildMI(*BB, MI, dl,
13301    TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
13302    .addReg(X86::XMM0);
13303
13304  MI->eraseFromParent();
13305  return BB;
13306}
13307
13308// FIXME: Custom handling because TableGen doesn't support multiple implicit
13309// defs in an instruction pattern
13310static MachineBasicBlock *EmitPCMPSTRI(MachineInstr *MI, MachineBasicBlock *BB,
13311                                       const TargetInstrInfo *TII) {
13312  unsigned Opc;
13313  switch (MI->getOpcode()) {
13314  default: llvm_unreachable("illegal opcode!");
13315  case X86::PCMPISTRIREG:  Opc = X86::PCMPISTRIrr;  break;
13316  case X86::VPCMPISTRIREG: Opc = X86::VPCMPISTRIrr; break;
13317  case X86::PCMPISTRIMEM:  Opc = X86::PCMPISTRIrm;  break;
13318  case X86::VPCMPISTRIMEM: Opc = X86::VPCMPISTRIrm; break;
13319  case X86::PCMPESTRIREG:  Opc = X86::PCMPESTRIrr;  break;
13320  case X86::VPCMPESTRIREG: Opc = X86::VPCMPESTRIrr; break;
13321  case X86::PCMPESTRIMEM:  Opc = X86::PCMPESTRIrm;  break;
13322  case X86::VPCMPESTRIMEM: Opc = X86::VPCMPESTRIrm; break;
13323  }
13324
13325  DebugLoc dl = MI->getDebugLoc();
13326  MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
13327
13328  unsigned NumArgs = MI->getNumOperands(); // remove the results
13329  for (unsigned i = 1; i < NumArgs; ++i) {
13330    MachineOperand &Op = MI->getOperand(i);
13331    if (!(Op.isReg() && Op.isImplicit()))
13332      MIB.addOperand(Op);
13333  }
13334  if (MI->hasOneMemOperand())
13335    MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
13336
13337  BuildMI(*BB, MI, dl,
13338    TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
13339    .addReg(X86::ECX);
13340
13341  MI->eraseFromParent();
13342  return BB;
13343}
13344
13345static MachineBasicBlock * EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB,
13346                                       const TargetInstrInfo *TII,
13347                                       const X86Subtarget* Subtarget) {
13348  DebugLoc dl = MI->getDebugLoc();
13349
13350  // Address into RAX/EAX, other two args into ECX, EDX.
13351  unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
13352  unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
13353  MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
13354  for (int i = 0; i < X86::AddrNumOperands; ++i)
13355    MIB.addOperand(MI->getOperand(i));
13356
13357  unsigned ValOps = X86::AddrNumOperands;
13358  BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
13359    .addReg(MI->getOperand(ValOps).getReg());
13360  BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
13361    .addReg(MI->getOperand(ValOps+1).getReg());
13362
13363  // The instruction doesn't actually take any operands though.
13364  BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
13365
13366  MI->eraseFromParent(); // The pseudo is gone now.
13367  return BB;
13368}
13369
13370MachineBasicBlock *
13371X86TargetLowering::EmitVAARG64WithCustomInserter(
13372                   MachineInstr *MI,
13373                   MachineBasicBlock *MBB) const {
13374  // Emit va_arg instruction on X86-64.
13375
13376  // Operands to this pseudo-instruction:
13377  // 0  ) Output        : destination address (reg)
13378  // 1-5) Input         : va_list address (addr, i64mem)
13379  // 6  ) ArgSize       : Size (in bytes) of vararg type
13380  // 7  ) ArgMode       : 0=overflow only, 1=use gp_offset, 2=use fp_offset
13381  // 8  ) Align         : Alignment of type
13382  // 9  ) EFLAGS (implicit-def)
13383
13384  assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
13385  assert(X86::AddrNumOperands == 5 && "VAARG_64 assumes 5 address operands");
13386
13387  unsigned DestReg = MI->getOperand(0).getReg();
13388  MachineOperand &Base = MI->getOperand(1);
13389  MachineOperand &Scale = MI->getOperand(2);
13390  MachineOperand &Index = MI->getOperand(3);
13391  MachineOperand &Disp = MI->getOperand(4);
13392  MachineOperand &Segment = MI->getOperand(5);
13393  unsigned ArgSize = MI->getOperand(6).getImm();
13394  unsigned ArgMode = MI->getOperand(7).getImm();
13395  unsigned Align = MI->getOperand(8).getImm();
13396
13397  // Memory Reference
13398  assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
13399  MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
13400  MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
13401
13402  // Machine Information
13403  const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
13404  MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
13405  const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
13406  const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
13407  DebugLoc DL = MI->getDebugLoc();
13408
13409  // struct va_list {
13410  //   i32   gp_offset
13411  //   i32   fp_offset
13412  //   i64   overflow_area (address)
13413  //   i64   reg_save_area (address)
13414  // }
13415  // sizeof(va_list) = 24
13416  // alignment(va_list) = 8
13417
13418  unsigned TotalNumIntRegs = 6;
13419  unsigned TotalNumXMMRegs = 8;
13420  bool UseGPOffset = (ArgMode == 1);
13421  bool UseFPOffset = (ArgMode == 2);
13422  unsigned MaxOffset = TotalNumIntRegs * 8 +
13423                       (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
13424
13425  /* Align ArgSize to a multiple of 8 */
13426  unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
13427  bool NeedsAlign = (Align > 8);
13428
13429  MachineBasicBlock *thisMBB = MBB;
13430  MachineBasicBlock *overflowMBB;
13431  MachineBasicBlock *offsetMBB;
13432  MachineBasicBlock *endMBB;
13433
13434  unsigned OffsetDestReg = 0;    // Argument address computed by offsetMBB
13435  unsigned OverflowDestReg = 0;  // Argument address computed by overflowMBB
13436  unsigned OffsetReg = 0;
13437
13438  if (!UseGPOffset && !UseFPOffset) {
13439    // If we only pull from the overflow region, we don't create a branch.
13440    // We don't need to alter control flow.
13441    OffsetDestReg = 0; // unused
13442    OverflowDestReg = DestReg;
13443
13444    offsetMBB = NULL;
13445    overflowMBB = thisMBB;
13446    endMBB = thisMBB;
13447  } else {
13448    // First emit code to check if gp_offset (or fp_offset) is below the bound.
13449    // If so, pull the argument from reg_save_area. (branch to offsetMBB)
13450    // If not, pull from overflow_area. (branch to overflowMBB)
13451    //
13452    //       thisMBB
13453    //         |     .
13454    //         |        .
13455    //     offsetMBB   overflowMBB
13456    //         |        .
13457    //         |     .
13458    //        endMBB
13459
13460    // Registers for the PHI in endMBB
13461    OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
13462    OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
13463
13464    const BasicBlock *LLVM_BB = MBB->getBasicBlock();
13465    MachineFunction *MF = MBB->getParent();
13466    overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
13467    offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
13468    endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
13469
13470    MachineFunction::iterator MBBIter = MBB;
13471    ++MBBIter;
13472
13473    // Insert the new basic blocks
13474    MF->insert(MBBIter, offsetMBB);
13475    MF->insert(MBBIter, overflowMBB);
13476    MF->insert(MBBIter, endMBB);
13477
13478    // Transfer the remainder of MBB and its successor edges to endMBB.
13479    endMBB->splice(endMBB->begin(), thisMBB,
13480                    llvm::next(MachineBasicBlock::iterator(MI)),
13481                    thisMBB->end());
13482    endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
13483
13484    // Make offsetMBB and overflowMBB successors of thisMBB
13485    thisMBB->addSuccessor(offsetMBB);
13486    thisMBB->addSuccessor(overflowMBB);
13487
13488    // endMBB is a successor of both offsetMBB and overflowMBB
13489    offsetMBB->addSuccessor(endMBB);
13490    overflowMBB->addSuccessor(endMBB);
13491
13492    // Load the offset value into a register
13493    OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
13494    BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
13495      .addOperand(Base)
13496      .addOperand(Scale)
13497      .addOperand(Index)
13498      .addDisp(Disp, UseFPOffset ? 4 : 0)
13499      .addOperand(Segment)
13500      .setMemRefs(MMOBegin, MMOEnd);
13501
13502    // Check if there is enough room left to pull this argument.
13503    BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
13504      .addReg(OffsetReg)
13505      .addImm(MaxOffset + 8 - ArgSizeA8);
13506
13507    // Branch to "overflowMBB" if offset >= max
13508    // Fall through to "offsetMBB" otherwise
13509    BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
13510      .addMBB(overflowMBB);
13511  }
13512
13513  // In offsetMBB, emit code to use the reg_save_area.
13514  if (offsetMBB) {
13515    assert(OffsetReg != 0);
13516
13517    // Read the reg_save_area address.
13518    unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
13519    BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
13520      .addOperand(Base)
13521      .addOperand(Scale)
13522      .addOperand(Index)
13523      .addDisp(Disp, 16)
13524      .addOperand(Segment)
13525      .setMemRefs(MMOBegin, MMOEnd);
13526
13527    // Zero-extend the offset
13528    unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
13529      BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
13530        .addImm(0)
13531        .addReg(OffsetReg)
13532        .addImm(X86::sub_32bit);
13533
13534    // Add the offset to the reg_save_area to get the final address.
13535    BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
13536      .addReg(OffsetReg64)
13537      .addReg(RegSaveReg);
13538
13539    // Compute the offset for the next argument
13540    unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
13541    BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
13542      .addReg(OffsetReg)
13543      .addImm(UseFPOffset ? 16 : 8);
13544
13545    // Store it back into the va_list.
13546    BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
13547      .addOperand(Base)
13548      .addOperand(Scale)
13549      .addOperand(Index)
13550      .addDisp(Disp, UseFPOffset ? 4 : 0)
13551      .addOperand(Segment)
13552      .addReg(NextOffsetReg)
13553      .setMemRefs(MMOBegin, MMOEnd);
13554
13555    // Jump to endMBB
13556    BuildMI(offsetMBB, DL, TII->get(X86::JMP_4))
13557      .addMBB(endMBB);
13558  }
13559
13560  //
13561  // Emit code to use overflow area
13562  //
13563
13564  // Load the overflow_area address into a register.
13565  unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
13566  BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
13567    .addOperand(Base)
13568    .addOperand(Scale)
13569    .addOperand(Index)
13570    .addDisp(Disp, 8)
13571    .addOperand(Segment)
13572    .setMemRefs(MMOBegin, MMOEnd);
13573
13574  // If we need to align it, do so. Otherwise, just copy the address
13575  // to OverflowDestReg.
13576  if (NeedsAlign) {
13577    // Align the overflow address
13578    assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
13579    unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
13580
13581    // aligned_addr = (addr + (align-1)) & ~(align-1)
13582    BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
13583      .addReg(OverflowAddrReg)
13584      .addImm(Align-1);
13585
13586    BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
13587      .addReg(TmpReg)
13588      .addImm(~(uint64_t)(Align-1));
13589  } else {
13590    BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
13591      .addReg(OverflowAddrReg);
13592  }
13593
13594  // Compute the next overflow address after this argument.
13595  // (the overflow address should be kept 8-byte aligned)
13596  unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
13597  BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
13598    .addReg(OverflowDestReg)
13599    .addImm(ArgSizeA8);
13600
13601  // Store the new overflow address.
13602  BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
13603    .addOperand(Base)
13604    .addOperand(Scale)
13605    .addOperand(Index)
13606    .addDisp(Disp, 8)
13607    .addOperand(Segment)
13608    .addReg(NextAddrReg)
13609    .setMemRefs(MMOBegin, MMOEnd);
13610
13611  // If we branched, emit the PHI to the front of endMBB.
13612  if (offsetMBB) {
13613    BuildMI(*endMBB, endMBB->begin(), DL,
13614            TII->get(X86::PHI), DestReg)
13615      .addReg(OffsetDestReg).addMBB(offsetMBB)
13616      .addReg(OverflowDestReg).addMBB(overflowMBB);
13617  }
13618
13619  // Erase the pseudo instruction
13620  MI->eraseFromParent();
13621
13622  return endMBB;
13623}
13624
13625MachineBasicBlock *
13626X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
13627                                                 MachineInstr *MI,
13628                                                 MachineBasicBlock *MBB) const {
13629  // Emit code to save XMM registers to the stack. The ABI says that the
13630  // number of registers to save is given in %al, so it's theoretically
13631  // possible to do an indirect jump trick to avoid saving all of them,
13632  // however this code takes a simpler approach and just executes all
13633  // of the stores if %al is non-zero. It's less code, and it's probably
13634  // easier on the hardware branch predictor, and stores aren't all that
13635  // expensive anyway.
13636
13637  // Create the new basic blocks. One block contains all the XMM stores,
13638  // and one block is the final destination regardless of whether any
13639  // stores were performed.
13640  const BasicBlock *LLVM_BB = MBB->getBasicBlock();
13641  MachineFunction *F = MBB->getParent();
13642  MachineFunction::iterator MBBIter = MBB;
13643  ++MBBIter;
13644  MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
13645  MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
13646  F->insert(MBBIter, XMMSaveMBB);
13647  F->insert(MBBIter, EndMBB);
13648
13649  // Transfer the remainder of MBB and its successor edges to EndMBB.
13650  EndMBB->splice(EndMBB->begin(), MBB,
13651                 llvm::next(MachineBasicBlock::iterator(MI)),
13652                 MBB->end());
13653  EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
13654
13655  // The original block will now fall through to the XMM save block.
13656  MBB->addSuccessor(XMMSaveMBB);
13657  // The XMMSaveMBB will fall through to the end block.
13658  XMMSaveMBB->addSuccessor(EndMBB);
13659
13660  // Now add the instructions.
13661  const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
13662  DebugLoc DL = MI->getDebugLoc();
13663
13664  unsigned CountReg = MI->getOperand(0).getReg();
13665  int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
13666  int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
13667
13668  if (!Subtarget->isTargetWin64()) {
13669    // If %al is 0, branch around the XMM save block.
13670    BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
13671    BuildMI(MBB, DL, TII->get(X86::JE_4)).addMBB(EndMBB);
13672    MBB->addSuccessor(EndMBB);
13673  }
13674
13675  unsigned MOVOpc = Subtarget->hasFp256() ? X86::VMOVAPSmr : X86::MOVAPSmr;
13676  // In the XMM save block, save all the XMM argument registers.
13677  for (int i = 3, e = MI->getNumOperands(); i != e; ++i) {
13678    int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
13679    MachineMemOperand *MMO =
13680      F->getMachineMemOperand(
13681          MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
13682        MachineMemOperand::MOStore,
13683        /*Size=*/16, /*Align=*/16);
13684    BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
13685      .addFrameIndex(RegSaveFrameIndex)
13686      .addImm(/*Scale=*/1)
13687      .addReg(/*IndexReg=*/0)
13688      .addImm(/*Disp=*/Offset)
13689      .addReg(/*Segment=*/0)
13690      .addReg(MI->getOperand(i).getReg())
13691      .addMemOperand(MMO);
13692  }
13693
13694  MI->eraseFromParent();   // The pseudo instruction is gone now.
13695
13696  return EndMBB;
13697}
13698
13699// The EFLAGS operand of SelectItr might be missing a kill marker
13700// because there were multiple uses of EFLAGS, and ISel didn't know
13701// which to mark. Figure out whether SelectItr should have had a
13702// kill marker, and set it if it should. Returns the correct kill
13703// marker value.
13704static bool checkAndUpdateEFLAGSKill(MachineBasicBlock::iterator SelectItr,
13705                                     MachineBasicBlock* BB,
13706                                     const TargetRegisterInfo* TRI) {
13707  // Scan forward through BB for a use/def of EFLAGS.
13708  MachineBasicBlock::iterator miI(llvm::next(SelectItr));
13709  for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
13710    const MachineInstr& mi = *miI;
13711    if (mi.readsRegister(X86::EFLAGS))
13712      return false;
13713    if (mi.definesRegister(X86::EFLAGS))
13714      break; // Should have kill-flag - update below.
13715  }
13716
13717  // If we hit the end of the block, check whether EFLAGS is live into a
13718  // successor.
13719  if (miI == BB->end()) {
13720    for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
13721                                          sEnd = BB->succ_end();
13722         sItr != sEnd; ++sItr) {
13723      MachineBasicBlock* succ = *sItr;
13724      if (succ->isLiveIn(X86::EFLAGS))
13725        return false;
13726    }
13727  }
13728
13729  // We found a def, or hit the end of the basic block and EFLAGS wasn't live
13730  // out. SelectMI should have a kill flag on EFLAGS.
13731  SelectItr->addRegisterKilled(X86::EFLAGS, TRI);
13732  return true;
13733}
13734
13735MachineBasicBlock *
13736X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
13737                                     MachineBasicBlock *BB) const {
13738  const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
13739  DebugLoc DL = MI->getDebugLoc();
13740
13741  // To "insert" a SELECT_CC instruction, we actually have to insert the
13742  // diamond control-flow pattern.  The incoming instruction knows the
13743  // destination vreg to set, the condition code register to branch on, the
13744  // true/false values to select between, and a branch opcode to use.
13745  const BasicBlock *LLVM_BB = BB->getBasicBlock();
13746  MachineFunction::iterator It = BB;
13747  ++It;
13748
13749  //  thisMBB:
13750  //  ...
13751  //   TrueVal = ...
13752  //   cmpTY ccX, r1, r2
13753  //   bCC copy1MBB
13754  //   fallthrough --> copy0MBB
13755  MachineBasicBlock *thisMBB = BB;
13756  MachineFunction *F = BB->getParent();
13757  MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
13758  MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
13759  F->insert(It, copy0MBB);
13760  F->insert(It, sinkMBB);
13761
13762  // If the EFLAGS register isn't dead in the terminator, then claim that it's
13763  // live into the sink and copy blocks.
13764  const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
13765  if (!MI->killsRegister(X86::EFLAGS) &&
13766      !checkAndUpdateEFLAGSKill(MI, BB, TRI)) {
13767    copy0MBB->addLiveIn(X86::EFLAGS);
13768    sinkMBB->addLiveIn(X86::EFLAGS);
13769  }
13770
13771  // Transfer the remainder of BB and its successor edges to sinkMBB.
13772  sinkMBB->splice(sinkMBB->begin(), BB,
13773                  llvm::next(MachineBasicBlock::iterator(MI)),
13774                  BB->end());
13775  sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
13776
13777  // Add the true and fallthrough blocks as its successors.
13778  BB->addSuccessor(copy0MBB);
13779  BB->addSuccessor(sinkMBB);
13780
13781  // Create the conditional branch instruction.
13782  unsigned Opc =
13783    X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
13784  BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
13785
13786  //  copy0MBB:
13787  //   %FalseValue = ...
13788  //   # fallthrough to sinkMBB
13789  copy0MBB->addSuccessor(sinkMBB);
13790
13791  //  sinkMBB:
13792  //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
13793  //  ...
13794  BuildMI(*sinkMBB, sinkMBB->begin(), DL,
13795          TII->get(X86::PHI), MI->getOperand(0).getReg())
13796    .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
13797    .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
13798
13799  MI->eraseFromParent();   // The pseudo instruction is gone now.
13800  return sinkMBB;
13801}
13802
13803MachineBasicBlock *
13804X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI, MachineBasicBlock *BB,
13805                                        bool Is64Bit) const {
13806  const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
13807  DebugLoc DL = MI->getDebugLoc();
13808  MachineFunction *MF = BB->getParent();
13809  const BasicBlock *LLVM_BB = BB->getBasicBlock();
13810
13811  assert(getTargetMachine().Options.EnableSegmentedStacks);
13812
13813  unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
13814  unsigned TlsOffset = Is64Bit ? 0x70 : 0x30;
13815
13816  // BB:
13817  //  ... [Till the alloca]
13818  // If stacklet is not large enough, jump to mallocMBB
13819  //
13820  // bumpMBB:
13821  //  Allocate by subtracting from RSP
13822  //  Jump to continueMBB
13823  //
13824  // mallocMBB:
13825  //  Allocate by call to runtime
13826  //
13827  // continueMBB:
13828  //  ...
13829  //  [rest of original BB]
13830  //
13831
13832  MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
13833  MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
13834  MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
13835
13836  MachineRegisterInfo &MRI = MF->getRegInfo();
13837  const TargetRegisterClass *AddrRegClass =
13838    getRegClassFor(Is64Bit ? MVT::i64:MVT::i32);
13839
13840  unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
13841    bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
13842    tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
13843    SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
13844    sizeVReg = MI->getOperand(1).getReg(),
13845    physSPReg = Is64Bit ? X86::RSP : X86::ESP;
13846
13847  MachineFunction::iterator MBBIter = BB;
13848  ++MBBIter;
13849
13850  MF->insert(MBBIter, bumpMBB);
13851  MF->insert(MBBIter, mallocMBB);
13852  MF->insert(MBBIter, continueMBB);
13853
13854  continueMBB->splice(continueMBB->begin(), BB, llvm::next
13855                      (MachineBasicBlock::iterator(MI)), BB->end());
13856  continueMBB->transferSuccessorsAndUpdatePHIs(BB);
13857
13858  // Add code to the main basic block to check if the stack limit has been hit,
13859  // and if so, jump to mallocMBB otherwise to bumpMBB.
13860  BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
13861  BuildMI(BB, DL, TII->get(Is64Bit ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
13862    .addReg(tmpSPVReg).addReg(sizeVReg);
13863  BuildMI(BB, DL, TII->get(Is64Bit ? X86::CMP64mr:X86::CMP32mr))
13864    .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg)
13865    .addReg(SPLimitVReg);
13866  BuildMI(BB, DL, TII->get(X86::JG_4)).addMBB(mallocMBB);
13867
13868  // bumpMBB simply decreases the stack pointer, since we know the current
13869  // stacklet has enough space.
13870  BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
13871    .addReg(SPLimitVReg);
13872  BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
13873    .addReg(SPLimitVReg);
13874  BuildMI(bumpMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
13875
13876  // Calls into a routine in libgcc to allocate more space from the heap.
13877  const uint32_t *RegMask =
13878    getTargetMachine().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
13879  if (Is64Bit) {
13880    BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
13881      .addReg(sizeVReg);
13882    BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
13883      .addExternalSymbol("__morestack_allocate_stack_space")
13884      .addRegMask(RegMask)
13885      .addReg(X86::RDI, RegState::Implicit)
13886      .addReg(X86::RAX, RegState::ImplicitDefine);
13887  } else {
13888    BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
13889      .addImm(12);
13890    BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
13891    BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
13892      .addExternalSymbol("__morestack_allocate_stack_space")
13893      .addRegMask(RegMask)
13894      .addReg(X86::EAX, RegState::ImplicitDefine);
13895  }
13896
13897  if (!Is64Bit)
13898    BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
13899      .addImm(16);
13900
13901  BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
13902    .addReg(Is64Bit ? X86::RAX : X86::EAX);
13903  BuildMI(mallocMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
13904
13905  // Set up the CFG correctly.
13906  BB->addSuccessor(bumpMBB);
13907  BB->addSuccessor(mallocMBB);
13908  mallocMBB->addSuccessor(continueMBB);
13909  bumpMBB->addSuccessor(continueMBB);
13910
13911  // Take care of the PHI nodes.
13912  BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
13913          MI->getOperand(0).getReg())
13914    .addReg(mallocPtrVReg).addMBB(mallocMBB)
13915    .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
13916
13917  // Delete the original pseudo instruction.
13918  MI->eraseFromParent();
13919
13920  // And we're done.
13921  return continueMBB;
13922}
13923
13924MachineBasicBlock *
13925X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
13926                                          MachineBasicBlock *BB) const {
13927  const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
13928  DebugLoc DL = MI->getDebugLoc();
13929
13930  assert(!Subtarget->isTargetEnvMacho());
13931
13932  // The lowering is pretty easy: we're just emitting the call to _alloca.  The
13933  // non-trivial part is impdef of ESP.
13934
13935  if (Subtarget->isTargetWin64()) {
13936    if (Subtarget->isTargetCygMing()) {
13937      // ___chkstk(Mingw64):
13938      // Clobbers R10, R11, RAX and EFLAGS.
13939      // Updates RSP.
13940      BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
13941        .addExternalSymbol("___chkstk")
13942        .addReg(X86::RAX, RegState::Implicit)
13943        .addReg(X86::RSP, RegState::Implicit)
13944        .addReg(X86::RAX, RegState::Define | RegState::Implicit)
13945        .addReg(X86::RSP, RegState::Define | RegState::Implicit)
13946        .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
13947    } else {
13948      // __chkstk(MSVCRT): does not update stack pointer.
13949      // Clobbers R10, R11 and EFLAGS.
13950      // FIXME: RAX(allocated size) might be reused and not killed.
13951      BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
13952        .addExternalSymbol("__chkstk")
13953        .addReg(X86::RAX, RegState::Implicit)
13954        .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
13955      // RAX has the offset to subtracted from RSP.
13956      BuildMI(*BB, MI, DL, TII->get(X86::SUB64rr), X86::RSP)
13957        .addReg(X86::RSP)
13958        .addReg(X86::RAX);
13959    }
13960  } else {
13961    const char *StackProbeSymbol =
13962      Subtarget->isTargetWindows() ? "_chkstk" : "_alloca";
13963
13964    BuildMI(*BB, MI, DL, TII->get(X86::CALLpcrel32))
13965      .addExternalSymbol(StackProbeSymbol)
13966      .addReg(X86::EAX, RegState::Implicit)
13967      .addReg(X86::ESP, RegState::Implicit)
13968      .addReg(X86::EAX, RegState::Define | RegState::Implicit)
13969      .addReg(X86::ESP, RegState::Define | RegState::Implicit)
13970      .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
13971  }
13972
13973  MI->eraseFromParent();   // The pseudo instruction is gone now.
13974  return BB;
13975}
13976
13977MachineBasicBlock *
13978X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
13979                                      MachineBasicBlock *BB) const {
13980  // This is pretty easy.  We're taking the value that we received from
13981  // our load from the relocation, sticking it in either RDI (x86-64)
13982  // or EAX and doing an indirect call.  The return value will then
13983  // be in the normal return register.
13984  const X86InstrInfo *TII
13985    = static_cast<const X86InstrInfo*>(getTargetMachine().getInstrInfo());
13986  DebugLoc DL = MI->getDebugLoc();
13987  MachineFunction *F = BB->getParent();
13988
13989  assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
13990  assert(MI->getOperand(3).isGlobal() && "This should be a global");
13991
13992  // Get a register mask for the lowered call.
13993  // FIXME: The 32-bit calls have non-standard calling conventions. Use a
13994  // proper register mask.
13995  const uint32_t *RegMask =
13996    getTargetMachine().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
13997  if (Subtarget->is64Bit()) {
13998    MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
13999                                      TII->get(X86::MOV64rm), X86::RDI)
14000    .addReg(X86::RIP)
14001    .addImm(0).addReg(0)
14002    .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
14003                      MI->getOperand(3).getTargetFlags())
14004    .addReg(0);
14005    MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
14006    addDirectMem(MIB, X86::RDI);
14007    MIB.addReg(X86::RAX, RegState::ImplicitDefine).addRegMask(RegMask);
14008  } else if (getTargetMachine().getRelocationModel() != Reloc::PIC_) {
14009    MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
14010                                      TII->get(X86::MOV32rm), X86::EAX)
14011    .addReg(0)
14012    .addImm(0).addReg(0)
14013    .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
14014                      MI->getOperand(3).getTargetFlags())
14015    .addReg(0);
14016    MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
14017    addDirectMem(MIB, X86::EAX);
14018    MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
14019  } else {
14020    MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
14021                                      TII->get(X86::MOV32rm), X86::EAX)
14022    .addReg(TII->getGlobalBaseReg(F))
14023    .addImm(0).addReg(0)
14024    .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
14025                      MI->getOperand(3).getTargetFlags())
14026    .addReg(0);
14027    MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
14028    addDirectMem(MIB, X86::EAX);
14029    MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
14030  }
14031
14032  MI->eraseFromParent(); // The pseudo instruction is gone now.
14033  return BB;
14034}
14035
14036MachineBasicBlock *
14037X86TargetLowering::emitEHSjLjSetJmp(MachineInstr *MI,
14038                                    MachineBasicBlock *MBB) const {
14039  DebugLoc DL = MI->getDebugLoc();
14040  const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
14041
14042  MachineFunction *MF = MBB->getParent();
14043  MachineRegisterInfo &MRI = MF->getRegInfo();
14044
14045  const BasicBlock *BB = MBB->getBasicBlock();
14046  MachineFunction::iterator I = MBB;
14047  ++I;
14048
14049  // Memory Reference
14050  MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
14051  MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
14052
14053  unsigned DstReg;
14054  unsigned MemOpndSlot = 0;
14055
14056  unsigned CurOp = 0;
14057
14058  DstReg = MI->getOperand(CurOp++).getReg();
14059  const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
14060  assert(RC->hasType(MVT::i32) && "Invalid destination!");
14061  unsigned mainDstReg = MRI.createVirtualRegister(RC);
14062  unsigned restoreDstReg = MRI.createVirtualRegister(RC);
14063
14064  MemOpndSlot = CurOp;
14065
14066  MVT PVT = getPointerTy();
14067  assert((PVT == MVT::i64 || PVT == MVT::i32) &&
14068         "Invalid Pointer Size!");
14069
14070  // For v = setjmp(buf), we generate
14071  //
14072  // thisMBB:
14073  //  buf[LabelOffset] = restoreMBB
14074  //  SjLjSetup restoreMBB
14075  //
14076  // mainMBB:
14077  //  v_main = 0
14078  //
14079  // sinkMBB:
14080  //  v = phi(main, restore)
14081  //
14082  // restoreMBB:
14083  //  v_restore = 1
14084
14085  MachineBasicBlock *thisMBB = MBB;
14086  MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
14087  MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
14088  MachineBasicBlock *restoreMBB = MF->CreateMachineBasicBlock(BB);
14089  MF->insert(I, mainMBB);
14090  MF->insert(I, sinkMBB);
14091  MF->push_back(restoreMBB);
14092
14093  MachineInstrBuilder MIB;
14094
14095  // Transfer the remainder of BB and its successor edges to sinkMBB.
14096  sinkMBB->splice(sinkMBB->begin(), MBB,
14097                  llvm::next(MachineBasicBlock::iterator(MI)), MBB->end());
14098  sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
14099
14100  // thisMBB:
14101  unsigned PtrStoreOpc = 0;
14102  unsigned LabelReg = 0;
14103  const int64_t LabelOffset = 1 * PVT.getStoreSize();
14104  Reloc::Model RM = getTargetMachine().getRelocationModel();
14105  bool UseImmLabel = (getTargetMachine().getCodeModel() == CodeModel::Small) &&
14106                     (RM == Reloc::Static || RM == Reloc::DynamicNoPIC);
14107
14108  // Prepare IP either in reg or imm.
14109  if (!UseImmLabel) {
14110    PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mr : X86::MOV32mr;
14111    const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
14112    LabelReg = MRI.createVirtualRegister(PtrRC);
14113    if (Subtarget->is64Bit()) {
14114      MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA64r), LabelReg)
14115              .addReg(X86::RIP)
14116              .addImm(0)
14117              .addReg(0)
14118              .addMBB(restoreMBB)
14119              .addReg(0);
14120    } else {
14121      const X86InstrInfo *XII = static_cast<const X86InstrInfo*>(TII);
14122      MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA32r), LabelReg)
14123              .addReg(XII->getGlobalBaseReg(MF))
14124              .addImm(0)
14125              .addReg(0)
14126              .addMBB(restoreMBB, Subtarget->ClassifyBlockAddressReference())
14127              .addReg(0);
14128    }
14129  } else
14130    PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mi32 : X86::MOV32mi;
14131  // Store IP
14132  MIB = BuildMI(*thisMBB, MI, DL, TII->get(PtrStoreOpc));
14133  for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
14134    if (i == X86::AddrDisp)
14135      MIB.addDisp(MI->getOperand(MemOpndSlot + i), LabelOffset);
14136    else
14137      MIB.addOperand(MI->getOperand(MemOpndSlot + i));
14138  }
14139  if (!UseImmLabel)
14140    MIB.addReg(LabelReg);
14141  else
14142    MIB.addMBB(restoreMBB);
14143  MIB.setMemRefs(MMOBegin, MMOEnd);
14144  // Setup
14145  MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::EH_SjLj_Setup))
14146          .addMBB(restoreMBB);
14147  MIB.addRegMask(RegInfo->getNoPreservedMask());
14148  thisMBB->addSuccessor(mainMBB);
14149  thisMBB->addSuccessor(restoreMBB);
14150
14151  // mainMBB:
14152  //  EAX = 0
14153  BuildMI(mainMBB, DL, TII->get(X86::MOV32r0), mainDstReg);
14154  mainMBB->addSuccessor(sinkMBB);
14155
14156  // sinkMBB:
14157  BuildMI(*sinkMBB, sinkMBB->begin(), DL,
14158          TII->get(X86::PHI), DstReg)
14159    .addReg(mainDstReg).addMBB(mainMBB)
14160    .addReg(restoreDstReg).addMBB(restoreMBB);
14161
14162  // restoreMBB:
14163  BuildMI(restoreMBB, DL, TII->get(X86::MOV32ri), restoreDstReg).addImm(1);
14164  BuildMI(restoreMBB, DL, TII->get(X86::JMP_4)).addMBB(sinkMBB);
14165  restoreMBB->addSuccessor(sinkMBB);
14166
14167  MI->eraseFromParent();
14168  return sinkMBB;
14169}
14170
14171MachineBasicBlock *
14172X86TargetLowering::emitEHSjLjLongJmp(MachineInstr *MI,
14173                                     MachineBasicBlock *MBB) const {
14174  DebugLoc DL = MI->getDebugLoc();
14175  const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
14176
14177  MachineFunction *MF = MBB->getParent();
14178  MachineRegisterInfo &MRI = MF->getRegInfo();
14179
14180  // Memory Reference
14181  MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
14182  MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
14183
14184  MVT PVT = getPointerTy();
14185  assert((PVT == MVT::i64 || PVT == MVT::i32) &&
14186         "Invalid Pointer Size!");
14187
14188  const TargetRegisterClass *RC =
14189    (PVT == MVT::i64) ? &X86::GR64RegClass : &X86::GR32RegClass;
14190  unsigned Tmp = MRI.createVirtualRegister(RC);
14191  // Since FP is only updated here but NOT referenced, it's treated as GPR.
14192  unsigned FP = (PVT == MVT::i64) ? X86::RBP : X86::EBP;
14193  unsigned SP = RegInfo->getStackRegister();
14194
14195  MachineInstrBuilder MIB;
14196
14197  const int64_t LabelOffset = 1 * PVT.getStoreSize();
14198  const int64_t SPOffset = 2 * PVT.getStoreSize();
14199
14200  unsigned PtrLoadOpc = (PVT == MVT::i64) ? X86::MOV64rm : X86::MOV32rm;
14201  unsigned IJmpOpc = (PVT == MVT::i64) ? X86::JMP64r : X86::JMP32r;
14202
14203  // Reload FP
14204  MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), FP);
14205  for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
14206    MIB.addOperand(MI->getOperand(i));
14207  MIB.setMemRefs(MMOBegin, MMOEnd);
14208  // Reload IP
14209  MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), Tmp);
14210  for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
14211    if (i == X86::AddrDisp)
14212      MIB.addDisp(MI->getOperand(i), LabelOffset);
14213    else
14214      MIB.addOperand(MI->getOperand(i));
14215  }
14216  MIB.setMemRefs(MMOBegin, MMOEnd);
14217  // Reload SP
14218  MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), SP);
14219  for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
14220    if (i == X86::AddrDisp)
14221      MIB.addDisp(MI->getOperand(i), SPOffset);
14222    else
14223      MIB.addOperand(MI->getOperand(i));
14224  }
14225  MIB.setMemRefs(MMOBegin, MMOEnd);
14226  // Jump
14227  BuildMI(*MBB, MI, DL, TII->get(IJmpOpc)).addReg(Tmp);
14228
14229  MI->eraseFromParent();
14230  return MBB;
14231}
14232
14233MachineBasicBlock *
14234X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
14235                                               MachineBasicBlock *BB) const {
14236  switch (MI->getOpcode()) {
14237  default: llvm_unreachable("Unexpected instr type to insert");
14238  case X86::TAILJMPd64:
14239  case X86::TAILJMPr64:
14240  case X86::TAILJMPm64:
14241    llvm_unreachable("TAILJMP64 would not be touched here.");
14242  case X86::TCRETURNdi64:
14243  case X86::TCRETURNri64:
14244  case X86::TCRETURNmi64:
14245    return BB;
14246  case X86::WIN_ALLOCA:
14247    return EmitLoweredWinAlloca(MI, BB);
14248  case X86::SEG_ALLOCA_32:
14249    return EmitLoweredSegAlloca(MI, BB, false);
14250  case X86::SEG_ALLOCA_64:
14251    return EmitLoweredSegAlloca(MI, BB, true);
14252  case X86::TLSCall_32:
14253  case X86::TLSCall_64:
14254    return EmitLoweredTLSCall(MI, BB);
14255  case X86::CMOV_GR8:
14256  case X86::CMOV_FR32:
14257  case X86::CMOV_FR64:
14258  case X86::CMOV_V4F32:
14259  case X86::CMOV_V2F64:
14260  case X86::CMOV_V2I64:
14261  case X86::CMOV_V8F32:
14262  case X86::CMOV_V4F64:
14263  case X86::CMOV_V4I64:
14264  case X86::CMOV_GR16:
14265  case X86::CMOV_GR32:
14266  case X86::CMOV_RFP32:
14267  case X86::CMOV_RFP64:
14268  case X86::CMOV_RFP80:
14269    return EmitLoweredSelect(MI, BB);
14270
14271  case X86::FP32_TO_INT16_IN_MEM:
14272  case X86::FP32_TO_INT32_IN_MEM:
14273  case X86::FP32_TO_INT64_IN_MEM:
14274  case X86::FP64_TO_INT16_IN_MEM:
14275  case X86::FP64_TO_INT32_IN_MEM:
14276  case X86::FP64_TO_INT64_IN_MEM:
14277  case X86::FP80_TO_INT16_IN_MEM:
14278  case X86::FP80_TO_INT32_IN_MEM:
14279  case X86::FP80_TO_INT64_IN_MEM: {
14280    const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
14281    DebugLoc DL = MI->getDebugLoc();
14282
14283    // Change the floating point control register to use "round towards zero"
14284    // mode when truncating to an integer value.
14285    MachineFunction *F = BB->getParent();
14286    int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
14287    addFrameReference(BuildMI(*BB, MI, DL,
14288                              TII->get(X86::FNSTCW16m)), CWFrameIdx);
14289
14290    // Load the old value of the high byte of the control word...
14291    unsigned OldCW =
14292      F->getRegInfo().createVirtualRegister(&X86::GR16RegClass);
14293    addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
14294                      CWFrameIdx);
14295
14296    // Set the high part to be round to zero...
14297    addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
14298      .addImm(0xC7F);
14299
14300    // Reload the modified control word now...
14301    addFrameReference(BuildMI(*BB, MI, DL,
14302                              TII->get(X86::FLDCW16m)), CWFrameIdx);
14303
14304    // Restore the memory image of control word to original value
14305    addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
14306      .addReg(OldCW);
14307
14308    // Get the X86 opcode to use.
14309    unsigned Opc;
14310    switch (MI->getOpcode()) {
14311    default: llvm_unreachable("illegal opcode!");
14312    case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
14313    case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
14314    case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
14315    case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
14316    case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
14317    case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
14318    case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
14319    case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
14320    case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
14321    }
14322
14323    X86AddressMode AM;
14324    MachineOperand &Op = MI->getOperand(0);
14325    if (Op.isReg()) {
14326      AM.BaseType = X86AddressMode::RegBase;
14327      AM.Base.Reg = Op.getReg();
14328    } else {
14329      AM.BaseType = X86AddressMode::FrameIndexBase;
14330      AM.Base.FrameIndex = Op.getIndex();
14331    }
14332    Op = MI->getOperand(1);
14333    if (Op.isImm())
14334      AM.Scale = Op.getImm();
14335    Op = MI->getOperand(2);
14336    if (Op.isImm())
14337      AM.IndexReg = Op.getImm();
14338    Op = MI->getOperand(3);
14339    if (Op.isGlobal()) {
14340      AM.GV = Op.getGlobal();
14341    } else {
14342      AM.Disp = Op.getImm();
14343    }
14344    addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
14345                      .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
14346
14347    // Reload the original control word now.
14348    addFrameReference(BuildMI(*BB, MI, DL,
14349                              TII->get(X86::FLDCW16m)), CWFrameIdx);
14350
14351    MI->eraseFromParent();   // The pseudo instruction is gone now.
14352    return BB;
14353  }
14354    // String/text processing lowering.
14355  case X86::PCMPISTRM128REG:
14356  case X86::VPCMPISTRM128REG:
14357  case X86::PCMPISTRM128MEM:
14358  case X86::VPCMPISTRM128MEM:
14359  case X86::PCMPESTRM128REG:
14360  case X86::VPCMPESTRM128REG:
14361  case X86::PCMPESTRM128MEM:
14362  case X86::VPCMPESTRM128MEM:
14363    assert(Subtarget->hasSSE42() &&
14364           "Target must have SSE4.2 or AVX features enabled");
14365    return EmitPCMPSTRM(MI, BB, getTargetMachine().getInstrInfo());
14366
14367  // String/text processing lowering.
14368  case X86::PCMPISTRIREG:
14369  case X86::VPCMPISTRIREG:
14370  case X86::PCMPISTRIMEM:
14371  case X86::VPCMPISTRIMEM:
14372  case X86::PCMPESTRIREG:
14373  case X86::VPCMPESTRIREG:
14374  case X86::PCMPESTRIMEM:
14375  case X86::VPCMPESTRIMEM:
14376    assert(Subtarget->hasSSE42() &&
14377           "Target must have SSE4.2 or AVX features enabled");
14378    return EmitPCMPSTRI(MI, BB, getTargetMachine().getInstrInfo());
14379
14380  // Thread synchronization.
14381  case X86::MONITOR:
14382    return EmitMonitor(MI, BB, getTargetMachine().getInstrInfo(), Subtarget);
14383
14384  // xbegin
14385  case X86::XBEGIN:
14386    return EmitXBegin(MI, BB, getTargetMachine().getInstrInfo());
14387
14388  // Atomic Lowering.
14389  case X86::ATOMAND8:
14390  case X86::ATOMAND16:
14391  case X86::ATOMAND32:
14392  case X86::ATOMAND64:
14393    // Fall through
14394  case X86::ATOMOR8:
14395  case X86::ATOMOR16:
14396  case X86::ATOMOR32:
14397  case X86::ATOMOR64:
14398    // Fall through
14399  case X86::ATOMXOR16:
14400  case X86::ATOMXOR8:
14401  case X86::ATOMXOR32:
14402  case X86::ATOMXOR64:
14403    // Fall through
14404  case X86::ATOMNAND8:
14405  case X86::ATOMNAND16:
14406  case X86::ATOMNAND32:
14407  case X86::ATOMNAND64:
14408    // Fall through
14409  case X86::ATOMMAX8:
14410  case X86::ATOMMAX16:
14411  case X86::ATOMMAX32:
14412  case X86::ATOMMAX64:
14413    // Fall through
14414  case X86::ATOMMIN8:
14415  case X86::ATOMMIN16:
14416  case X86::ATOMMIN32:
14417  case X86::ATOMMIN64:
14418    // Fall through
14419  case X86::ATOMUMAX8:
14420  case X86::ATOMUMAX16:
14421  case X86::ATOMUMAX32:
14422  case X86::ATOMUMAX64:
14423    // Fall through
14424  case X86::ATOMUMIN8:
14425  case X86::ATOMUMIN16:
14426  case X86::ATOMUMIN32:
14427  case X86::ATOMUMIN64:
14428    return EmitAtomicLoadArith(MI, BB);
14429
14430  // This group does 64-bit operations on a 32-bit host.
14431  case X86::ATOMAND6432:
14432  case X86::ATOMOR6432:
14433  case X86::ATOMXOR6432:
14434  case X86::ATOMNAND6432:
14435  case X86::ATOMADD6432:
14436  case X86::ATOMSUB6432:
14437  case X86::ATOMMAX6432:
14438  case X86::ATOMMIN6432:
14439  case X86::ATOMUMAX6432:
14440  case X86::ATOMUMIN6432:
14441  case X86::ATOMSWAP6432:
14442    return EmitAtomicLoadArith6432(MI, BB);
14443
14444  case X86::VASTART_SAVE_XMM_REGS:
14445    return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
14446
14447  case X86::VAARG_64:
14448    return EmitVAARG64WithCustomInserter(MI, BB);
14449
14450  case X86::EH_SjLj_SetJmp32:
14451  case X86::EH_SjLj_SetJmp64:
14452    return emitEHSjLjSetJmp(MI, BB);
14453
14454  case X86::EH_SjLj_LongJmp32:
14455  case X86::EH_SjLj_LongJmp64:
14456    return emitEHSjLjLongJmp(MI, BB);
14457  }
14458}
14459
14460//===----------------------------------------------------------------------===//
14461//                           X86 Optimization Hooks
14462//===----------------------------------------------------------------------===//
14463
14464void X86TargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
14465                                                       APInt &KnownZero,
14466                                                       APInt &KnownOne,
14467                                                       const SelectionDAG &DAG,
14468                                                       unsigned Depth) const {
14469  unsigned BitWidth = KnownZero.getBitWidth();
14470  unsigned Opc = Op.getOpcode();
14471  assert((Opc >= ISD::BUILTIN_OP_END ||
14472          Opc == ISD::INTRINSIC_WO_CHAIN ||
14473          Opc == ISD::INTRINSIC_W_CHAIN ||
14474          Opc == ISD::INTRINSIC_VOID) &&
14475         "Should use MaskedValueIsZero if you don't know whether Op"
14476         " is a target node!");
14477
14478  KnownZero = KnownOne = APInt(BitWidth, 0);   // Don't know anything.
14479  switch (Opc) {
14480  default: break;
14481  case X86ISD::ADD:
14482  case X86ISD::SUB:
14483  case X86ISD::ADC:
14484  case X86ISD::SBB:
14485  case X86ISD::SMUL:
14486  case X86ISD::UMUL:
14487  case X86ISD::INC:
14488  case X86ISD::DEC:
14489  case X86ISD::OR:
14490  case X86ISD::XOR:
14491  case X86ISD::AND:
14492    // These nodes' second result is a boolean.
14493    if (Op.getResNo() == 0)
14494      break;
14495    // Fallthrough
14496  case X86ISD::SETCC:
14497    KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
14498    break;
14499  case ISD::INTRINSIC_WO_CHAIN: {
14500    unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
14501    unsigned NumLoBits = 0;
14502    switch (IntId) {
14503    default: break;
14504    case Intrinsic::x86_sse_movmsk_ps:
14505    case Intrinsic::x86_avx_movmsk_ps_256:
14506    case Intrinsic::x86_sse2_movmsk_pd:
14507    case Intrinsic::x86_avx_movmsk_pd_256:
14508    case Intrinsic::x86_mmx_pmovmskb:
14509    case Intrinsic::x86_sse2_pmovmskb_128:
14510    case Intrinsic::x86_avx2_pmovmskb: {
14511      // High bits of movmskp{s|d}, pmovmskb are known zero.
14512      switch (IntId) {
14513        default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
14514        case Intrinsic::x86_sse_movmsk_ps:      NumLoBits = 4; break;
14515        case Intrinsic::x86_avx_movmsk_ps_256:  NumLoBits = 8; break;
14516        case Intrinsic::x86_sse2_movmsk_pd:     NumLoBits = 2; break;
14517        case Intrinsic::x86_avx_movmsk_pd_256:  NumLoBits = 4; break;
14518        case Intrinsic::x86_mmx_pmovmskb:       NumLoBits = 8; break;
14519        case Intrinsic::x86_sse2_pmovmskb_128:  NumLoBits = 16; break;
14520        case Intrinsic::x86_avx2_pmovmskb:      NumLoBits = 32; break;
14521      }
14522      KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - NumLoBits);
14523      break;
14524    }
14525    }
14526    break;
14527  }
14528  }
14529}
14530
14531unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(SDValue Op,
14532                                                         unsigned Depth) const {
14533  // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
14534  if (Op.getOpcode() == X86ISD::SETCC_CARRY)
14535    return Op.getValueType().getScalarType().getSizeInBits();
14536
14537  // Fallback case.
14538  return 1;
14539}
14540
14541/// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
14542/// node is a GlobalAddress + offset.
14543bool X86TargetLowering::isGAPlusOffset(SDNode *N,
14544                                       const GlobalValue* &GA,
14545                                       int64_t &Offset) const {
14546  if (N->getOpcode() == X86ISD::Wrapper) {
14547    if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
14548      GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
14549      Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
14550      return true;
14551    }
14552  }
14553  return TargetLowering::isGAPlusOffset(N, GA, Offset);
14554}
14555
14556/// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the
14557/// same as extracting the high 128-bit part of 256-bit vector and then
14558/// inserting the result into the low part of a new 256-bit vector
14559static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) {
14560  EVT VT = SVOp->getValueType(0);
14561  unsigned NumElems = VT.getVectorNumElements();
14562
14563  // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
14564  for (unsigned i = 0, j = NumElems/2; i != NumElems/2; ++i, ++j)
14565    if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
14566        SVOp->getMaskElt(j) >= 0)
14567      return false;
14568
14569  return true;
14570}
14571
14572/// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the
14573/// same as extracting the low 128-bit part of 256-bit vector and then
14574/// inserting the result into the high part of a new 256-bit vector
14575static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) {
14576  EVT VT = SVOp->getValueType(0);
14577  unsigned NumElems = VT.getVectorNumElements();
14578
14579  // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
14580  for (unsigned i = NumElems/2, j = 0; i != NumElems; ++i, ++j)
14581    if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
14582        SVOp->getMaskElt(j) >= 0)
14583      return false;
14584
14585  return true;
14586}
14587
14588/// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
14589static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
14590                                        TargetLowering::DAGCombinerInfo &DCI,
14591                                        const X86Subtarget* Subtarget) {
14592  DebugLoc dl = N->getDebugLoc();
14593  ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
14594  SDValue V1 = SVOp->getOperand(0);
14595  SDValue V2 = SVOp->getOperand(1);
14596  EVT VT = SVOp->getValueType(0);
14597  unsigned NumElems = VT.getVectorNumElements();
14598
14599  if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
14600      V2.getOpcode() == ISD::CONCAT_VECTORS) {
14601    //
14602    //                   0,0,0,...
14603    //                      |
14604    //    V      UNDEF    BUILD_VECTOR    UNDEF
14605    //     \      /           \           /
14606    //  CONCAT_VECTOR         CONCAT_VECTOR
14607    //         \                  /
14608    //          \                /
14609    //          RESULT: V + zero extended
14610    //
14611    if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
14612        V2.getOperand(1).getOpcode() != ISD::UNDEF ||
14613        V1.getOperand(1).getOpcode() != ISD::UNDEF)
14614      return SDValue();
14615
14616    if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
14617      return SDValue();
14618
14619    // To match the shuffle mask, the first half of the mask should
14620    // be exactly the first vector, and all the rest a splat with the
14621    // first element of the second one.
14622    for (unsigned i = 0; i != NumElems/2; ++i)
14623      if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
14624          !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
14625        return SDValue();
14626
14627    // If V1 is coming from a vector load then just fold to a VZEXT_LOAD.
14628    if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(V1.getOperand(0))) {
14629      if (Ld->hasNUsesOfValue(1, 0)) {
14630        SDVTList Tys = DAG.getVTList(MVT::v4i64, MVT::Other);
14631        SDValue Ops[] = { Ld->getChain(), Ld->getBasePtr() };
14632        SDValue ResNode =
14633          DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops, 2,
14634                                  Ld->getMemoryVT(),
14635                                  Ld->getPointerInfo(),
14636                                  Ld->getAlignment(),
14637                                  false/*isVolatile*/, true/*ReadMem*/,
14638                                  false/*WriteMem*/);
14639
14640        // Make sure the newly-created LOAD is in the same position as Ld in
14641        // terms of dependency. We create a TokenFactor for Ld and ResNode,
14642        // and update uses of Ld's output chain to use the TokenFactor.
14643        if (Ld->hasAnyUseOfValue(1)) {
14644          SDValue NewChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
14645                             SDValue(Ld, 1), SDValue(ResNode.getNode(), 1));
14646          DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), NewChain);
14647          DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(Ld, 1),
14648                                 SDValue(ResNode.getNode(), 1));
14649        }
14650
14651        return DAG.getNode(ISD::BITCAST, dl, VT, ResNode);
14652      }
14653    }
14654
14655    // Emit a zeroed vector and insert the desired subvector on its
14656    // first half.
14657    SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
14658    SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0), 0, DAG, dl);
14659    return DCI.CombineTo(N, InsV);
14660  }
14661
14662  //===--------------------------------------------------------------------===//
14663  // Combine some shuffles into subvector extracts and inserts:
14664  //
14665
14666  // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
14667  if (isShuffleHigh128VectorInsertLow(SVOp)) {
14668    SDValue V = Extract128BitVector(V1, NumElems/2, DAG, dl);
14669    SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, 0, DAG, dl);
14670    return DCI.CombineTo(N, InsV);
14671  }
14672
14673  // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
14674  if (isShuffleLow128VectorInsertHigh(SVOp)) {
14675    SDValue V = Extract128BitVector(V1, 0, DAG, dl);
14676    SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, NumElems/2, DAG, dl);
14677    return DCI.CombineTo(N, InsV);
14678  }
14679
14680  return SDValue();
14681}
14682
14683/// PerformShuffleCombine - Performs several different shuffle combines.
14684static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
14685                                     TargetLowering::DAGCombinerInfo &DCI,
14686                                     const X86Subtarget *Subtarget) {
14687  DebugLoc dl = N->getDebugLoc();
14688  EVT VT = N->getValueType(0);
14689
14690  // Don't create instructions with illegal types after legalize types has run.
14691  const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14692  if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
14693    return SDValue();
14694
14695  // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
14696  if (Subtarget->hasFp256() && VT.is256BitVector() &&
14697      N->getOpcode() == ISD::VECTOR_SHUFFLE)
14698    return PerformShuffleCombine256(N, DAG, DCI, Subtarget);
14699
14700  // Only handle 128 wide vector from here on.
14701  if (!VT.is128BitVector())
14702    return SDValue();
14703
14704  // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
14705  // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
14706  // consecutive, non-overlapping, and in the right order.
14707  SmallVector<SDValue, 16> Elts;
14708  for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
14709    Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
14710
14711  return EltsFromConsecutiveLoads(VT, Elts, dl, DAG);
14712}
14713
14714/// PerformTruncateCombine - Converts truncate operation to
14715/// a sequence of vector shuffle operations.
14716/// It is possible when we truncate 256-bit vector to 128-bit vector
14717static SDValue PerformTruncateCombine(SDNode *N, SelectionDAG &DAG,
14718                                      TargetLowering::DAGCombinerInfo &DCI,
14719                                      const X86Subtarget *Subtarget)  {
14720  return SDValue();
14721}
14722
14723/// XFormVExtractWithShuffleIntoLoad - Check if a vector extract from a target
14724/// specific shuffle of a load can be folded into a single element load.
14725/// Similar handling for VECTOR_SHUFFLE is performed by DAGCombiner, but
14726/// shuffles have been customed lowered so we need to handle those here.
14727static SDValue XFormVExtractWithShuffleIntoLoad(SDNode *N, SelectionDAG &DAG,
14728                                         TargetLowering::DAGCombinerInfo &DCI) {
14729  if (DCI.isBeforeLegalizeOps())
14730    return SDValue();
14731
14732  SDValue InVec = N->getOperand(0);
14733  SDValue EltNo = N->getOperand(1);
14734
14735  if (!isa<ConstantSDNode>(EltNo))
14736    return SDValue();
14737
14738  EVT VT = InVec.getValueType();
14739
14740  bool HasShuffleIntoBitcast = false;
14741  if (InVec.getOpcode() == ISD::BITCAST) {
14742    // Don't duplicate a load with other uses.
14743    if (!InVec.hasOneUse())
14744      return SDValue();
14745    EVT BCVT = InVec.getOperand(0).getValueType();
14746    if (BCVT.getVectorNumElements() != VT.getVectorNumElements())
14747      return SDValue();
14748    InVec = InVec.getOperand(0);
14749    HasShuffleIntoBitcast = true;
14750  }
14751
14752  if (!isTargetShuffle(InVec.getOpcode()))
14753    return SDValue();
14754
14755  // Don't duplicate a load with other uses.
14756  if (!InVec.hasOneUse())
14757    return SDValue();
14758
14759  SmallVector<int, 16> ShuffleMask;
14760  bool UnaryShuffle;
14761  if (!getTargetShuffleMask(InVec.getNode(), VT.getSimpleVT(), ShuffleMask,
14762                            UnaryShuffle))
14763    return SDValue();
14764
14765  // Select the input vector, guarding against out of range extract vector.
14766  unsigned NumElems = VT.getVectorNumElements();
14767  int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
14768  int Idx = (Elt > (int)NumElems) ? -1 : ShuffleMask[Elt];
14769  SDValue LdNode = (Idx < (int)NumElems) ? InVec.getOperand(0)
14770                                         : InVec.getOperand(1);
14771
14772  // If inputs to shuffle are the same for both ops, then allow 2 uses
14773  unsigned AllowedUses = InVec.getOperand(0) == InVec.getOperand(1) ? 2 : 1;
14774
14775  if (LdNode.getOpcode() == ISD::BITCAST) {
14776    // Don't duplicate a load with other uses.
14777    if (!LdNode.getNode()->hasNUsesOfValue(AllowedUses, 0))
14778      return SDValue();
14779
14780    AllowedUses = 1; // only allow 1 load use if we have a bitcast
14781    LdNode = LdNode.getOperand(0);
14782  }
14783
14784  if (!ISD::isNormalLoad(LdNode.getNode()))
14785    return SDValue();
14786
14787  LoadSDNode *LN0 = cast<LoadSDNode>(LdNode);
14788
14789  if (!LN0 ||!LN0->hasNUsesOfValue(AllowedUses, 0) || LN0->isVolatile())
14790    return SDValue();
14791
14792  if (HasShuffleIntoBitcast) {
14793    // If there's a bitcast before the shuffle, check if the load type and
14794    // alignment is valid.
14795    unsigned Align = LN0->getAlignment();
14796    const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14797    unsigned NewAlign = TLI.getDataLayout()->
14798      getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
14799
14800    if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VT))
14801      return SDValue();
14802  }
14803
14804  // All checks match so transform back to vector_shuffle so that DAG combiner
14805  // can finish the job
14806  DebugLoc dl = N->getDebugLoc();
14807
14808  // Create shuffle node taking into account the case that its a unary shuffle
14809  SDValue Shuffle = (UnaryShuffle) ? DAG.getUNDEF(VT) : InVec.getOperand(1);
14810  Shuffle = DAG.getVectorShuffle(InVec.getValueType(), dl,
14811                                 InVec.getOperand(0), Shuffle,
14812                                 &ShuffleMask[0]);
14813  Shuffle = DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
14814  return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0), Shuffle,
14815                     EltNo);
14816}
14817
14818/// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
14819/// generation and convert it from being a bunch of shuffles and extracts
14820/// to a simple store and scalar loads to extract the elements.
14821static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
14822                                         TargetLowering::DAGCombinerInfo &DCI) {
14823  SDValue NewOp = XFormVExtractWithShuffleIntoLoad(N, DAG, DCI);
14824  if (NewOp.getNode())
14825    return NewOp;
14826
14827  SDValue InputVector = N->getOperand(0);
14828  // Detect whether we are trying to convert from mmx to i32 and the bitcast
14829  // from mmx to v2i32 has a single usage.
14830  if (InputVector.getNode()->getOpcode() == llvm::ISD::BITCAST &&
14831      InputVector.getNode()->getOperand(0).getValueType() == MVT::x86mmx &&
14832      InputVector.hasOneUse() && N->getValueType(0) == MVT::i32)
14833    return DAG.getNode(X86ISD::MMX_MOVD2W, InputVector.getDebugLoc(),
14834                       N->getValueType(0),
14835                       InputVector.getNode()->getOperand(0));
14836
14837  // Only operate on vectors of 4 elements, where the alternative shuffling
14838  // gets to be more expensive.
14839  if (InputVector.getValueType() != MVT::v4i32)
14840    return SDValue();
14841
14842  // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
14843  // single use which is a sign-extend or zero-extend, and all elements are
14844  // used.
14845  SmallVector<SDNode *, 4> Uses;
14846  unsigned ExtractedElements = 0;
14847  for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
14848       UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
14849    if (UI.getUse().getResNo() != InputVector.getResNo())
14850      return SDValue();
14851
14852    SDNode *Extract = *UI;
14853    if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
14854      return SDValue();
14855
14856    if (Extract->getValueType(0) != MVT::i32)
14857      return SDValue();
14858    if (!Extract->hasOneUse())
14859      return SDValue();
14860    if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
14861        Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
14862      return SDValue();
14863    if (!isa<ConstantSDNode>(Extract->getOperand(1)))
14864      return SDValue();
14865
14866    // Record which element was extracted.
14867    ExtractedElements |=
14868      1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
14869
14870    Uses.push_back(Extract);
14871  }
14872
14873  // If not all the elements were used, this may not be worthwhile.
14874  if (ExtractedElements != 15)
14875    return SDValue();
14876
14877  // Ok, we've now decided to do the transformation.
14878  DebugLoc dl = InputVector.getDebugLoc();
14879
14880  // Store the value to a temporary stack slot.
14881  SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
14882  SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
14883                            MachinePointerInfo(), false, false, 0);
14884
14885  // Replace each use (extract) with a load of the appropriate element.
14886  for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
14887       UE = Uses.end(); UI != UE; ++UI) {
14888    SDNode *Extract = *UI;
14889
14890    // cOMpute the element's address.
14891    SDValue Idx = Extract->getOperand(1);
14892    unsigned EltSize =
14893        InputVector.getValueType().getVectorElementType().getSizeInBits()/8;
14894    uint64_t Offset = EltSize * cast<ConstantSDNode>(Idx)->getZExtValue();
14895    const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14896    SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy());
14897
14898    SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(),
14899                                     StackPtr, OffsetVal);
14900
14901    // Load the scalar.
14902    SDValue LoadScalar = DAG.getLoad(Extract->getValueType(0), dl, Ch,
14903                                     ScalarAddr, MachinePointerInfo(),
14904                                     false, false, false, 0);
14905
14906    // Replace the exact with the load.
14907    DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), LoadScalar);
14908  }
14909
14910  // The replacement was made in place; don't return anything.
14911  return SDValue();
14912}
14913
14914/// \brief Matches a VSELECT onto min/max or return 0 if the node doesn't match.
14915static unsigned matchIntegerMINMAX(SDValue Cond, EVT VT, SDValue LHS,
14916                                   SDValue RHS, SelectionDAG &DAG,
14917                                   const X86Subtarget *Subtarget) {
14918  if (!VT.isVector())
14919    return 0;
14920
14921  switch (VT.getSimpleVT().SimpleTy) {
14922  default: return 0;
14923  case MVT::v32i8:
14924  case MVT::v16i16:
14925  case MVT::v8i32:
14926    if (!Subtarget->hasAVX2())
14927      return 0;
14928  case MVT::v16i8:
14929  case MVT::v8i16:
14930  case MVT::v4i32:
14931    if (!Subtarget->hasSSE2())
14932      return 0;
14933  }
14934
14935  // SSE2 has only a small subset of the operations.
14936  bool hasUnsigned = Subtarget->hasSSE41() ||
14937                     (Subtarget->hasSSE2() && VT == MVT::v16i8);
14938  bool hasSigned = Subtarget->hasSSE41() ||
14939                   (Subtarget->hasSSE2() && VT == MVT::v8i16);
14940
14941  ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
14942
14943  // Check for x CC y ? x : y.
14944  if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
14945      DAG.isEqualTo(RHS, Cond.getOperand(1))) {
14946    switch (CC) {
14947    default: break;
14948    case ISD::SETULT:
14949    case ISD::SETULE:
14950      return hasUnsigned ? X86ISD::UMIN : 0;
14951    case ISD::SETUGT:
14952    case ISD::SETUGE:
14953      return hasUnsigned ? X86ISD::UMAX : 0;
14954    case ISD::SETLT:
14955    case ISD::SETLE:
14956      return hasSigned ? X86ISD::SMIN : 0;
14957    case ISD::SETGT:
14958    case ISD::SETGE:
14959      return hasSigned ? X86ISD::SMAX : 0;
14960    }
14961  // Check for x CC y ? y : x -- a min/max with reversed arms.
14962  } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
14963             DAG.isEqualTo(RHS, Cond.getOperand(0))) {
14964    switch (CC) {
14965    default: break;
14966    case ISD::SETULT:
14967    case ISD::SETULE:
14968      return hasUnsigned ? X86ISD::UMAX : 0;
14969    case ISD::SETUGT:
14970    case ISD::SETUGE:
14971      return hasUnsigned ? X86ISD::UMIN : 0;
14972    case ISD::SETLT:
14973    case ISD::SETLE:
14974      return hasSigned ? X86ISD::SMAX : 0;
14975    case ISD::SETGT:
14976    case ISD::SETGE:
14977      return hasSigned ? X86ISD::SMIN : 0;
14978    }
14979  }
14980
14981  return 0;
14982}
14983
14984/// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
14985/// nodes.
14986static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
14987                                    TargetLowering::DAGCombinerInfo &DCI,
14988                                    const X86Subtarget *Subtarget) {
14989  DebugLoc DL = N->getDebugLoc();
14990  SDValue Cond = N->getOperand(0);
14991  // Get the LHS/RHS of the select.
14992  SDValue LHS = N->getOperand(1);
14993  SDValue RHS = N->getOperand(2);
14994  EVT VT = LHS.getValueType();
14995
14996  // If we have SSE[12] support, try to form min/max nodes. SSE min/max
14997  // instructions match the semantics of the common C idiom x<y?x:y but not
14998  // x<=y?x:y, because of how they handle negative zero (which can be
14999  // ignored in unsafe-math mode).
15000  if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
15001      VT != MVT::f80 && DAG.getTargetLoweringInfo().isTypeLegal(VT) &&
15002      (Subtarget->hasSSE2() ||
15003       (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
15004    ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
15005
15006    unsigned Opcode = 0;
15007    // Check for x CC y ? x : y.
15008    if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
15009        DAG.isEqualTo(RHS, Cond.getOperand(1))) {
15010      switch (CC) {
15011      default: break;
15012      case ISD::SETULT:
15013        // Converting this to a min would handle NaNs incorrectly, and swapping
15014        // the operands would cause it to handle comparisons between positive
15015        // and negative zero incorrectly.
15016        if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
15017          if (!DAG.getTarget().Options.UnsafeFPMath &&
15018              !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
15019            break;
15020          std::swap(LHS, RHS);
15021        }
15022        Opcode = X86ISD::FMIN;
15023        break;
15024      case ISD::SETOLE:
15025        // Converting this to a min would handle comparisons between positive
15026        // and negative zero incorrectly.
15027        if (!DAG.getTarget().Options.UnsafeFPMath &&
15028            !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
15029          break;
15030        Opcode = X86ISD::FMIN;
15031        break;
15032      case ISD::SETULE:
15033        // Converting this to a min would handle both negative zeros and NaNs
15034        // incorrectly, but we can swap the operands to fix both.
15035        std::swap(LHS, RHS);
15036      case ISD::SETOLT:
15037      case ISD::SETLT:
15038      case ISD::SETLE:
15039        Opcode = X86ISD::FMIN;
15040        break;
15041
15042      case ISD::SETOGE:
15043        // Converting this to a max would handle comparisons between positive
15044        // and negative zero incorrectly.
15045        if (!DAG.getTarget().Options.UnsafeFPMath &&
15046            !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
15047          break;
15048        Opcode = X86ISD::FMAX;
15049        break;
15050      case ISD::SETUGT:
15051        // Converting this to a max would handle NaNs incorrectly, and swapping
15052        // the operands would cause it to handle comparisons between positive
15053        // and negative zero incorrectly.
15054        if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
15055          if (!DAG.getTarget().Options.UnsafeFPMath &&
15056              !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
15057            break;
15058          std::swap(LHS, RHS);
15059        }
15060        Opcode = X86ISD::FMAX;
15061        break;
15062      case ISD::SETUGE:
15063        // Converting this to a max would handle both negative zeros and NaNs
15064        // incorrectly, but we can swap the operands to fix both.
15065        std::swap(LHS, RHS);
15066      case ISD::SETOGT:
15067      case ISD::SETGT:
15068      case ISD::SETGE:
15069        Opcode = X86ISD::FMAX;
15070        break;
15071      }
15072    // Check for x CC y ? y : x -- a min/max with reversed arms.
15073    } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
15074               DAG.isEqualTo(RHS, Cond.getOperand(0))) {
15075      switch (CC) {
15076      default: break;
15077      case ISD::SETOGE:
15078        // Converting this to a min would handle comparisons between positive
15079        // and negative zero incorrectly, and swapping the operands would
15080        // cause it to handle NaNs incorrectly.
15081        if (!DAG.getTarget().Options.UnsafeFPMath &&
15082            !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
15083          if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
15084            break;
15085          std::swap(LHS, RHS);
15086        }
15087        Opcode = X86ISD::FMIN;
15088        break;
15089      case ISD::SETUGT:
15090        // Converting this to a min would handle NaNs incorrectly.
15091        if (!DAG.getTarget().Options.UnsafeFPMath &&
15092            (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
15093          break;
15094        Opcode = X86ISD::FMIN;
15095        break;
15096      case ISD::SETUGE:
15097        // Converting this to a min would handle both negative zeros and NaNs
15098        // incorrectly, but we can swap the operands to fix both.
15099        std::swap(LHS, RHS);
15100      case ISD::SETOGT:
15101      case ISD::SETGT:
15102      case ISD::SETGE:
15103        Opcode = X86ISD::FMIN;
15104        break;
15105
15106      case ISD::SETULT:
15107        // Converting this to a max would handle NaNs incorrectly.
15108        if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
15109          break;
15110        Opcode = X86ISD::FMAX;
15111        break;
15112      case ISD::SETOLE:
15113        // Converting this to a max would handle comparisons between positive
15114        // and negative zero incorrectly, and swapping the operands would
15115        // cause it to handle NaNs incorrectly.
15116        if (!DAG.getTarget().Options.UnsafeFPMath &&
15117            !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
15118          if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
15119            break;
15120          std::swap(LHS, RHS);
15121        }
15122        Opcode = X86ISD::FMAX;
15123        break;
15124      case ISD::SETULE:
15125        // Converting this to a max would handle both negative zeros and NaNs
15126        // incorrectly, but we can swap the operands to fix both.
15127        std::swap(LHS, RHS);
15128      case ISD::SETOLT:
15129      case ISD::SETLT:
15130      case ISD::SETLE:
15131        Opcode = X86ISD::FMAX;
15132        break;
15133      }
15134    }
15135
15136    if (Opcode)
15137      return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
15138  }
15139
15140  // If this is a select between two integer constants, try to do some
15141  // optimizations.
15142  if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
15143    if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
15144      // Don't do this for crazy integer types.
15145      if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
15146        // If this is efficiently invertible, canonicalize the LHSC/RHSC values
15147        // so that TrueC (the true value) is larger than FalseC.
15148        bool NeedsCondInvert = false;
15149
15150        if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
15151            // Efficiently invertible.
15152            (Cond.getOpcode() == ISD::SETCC ||  // setcc -> invertible.
15153             (Cond.getOpcode() == ISD::XOR &&   // xor(X, C) -> invertible.
15154              isa<ConstantSDNode>(Cond.getOperand(1))))) {
15155          NeedsCondInvert = true;
15156          std::swap(TrueC, FalseC);
15157        }
15158
15159        // Optimize C ? 8 : 0 -> zext(C) << 3.  Likewise for any pow2/0.
15160        if (FalseC->getAPIntValue() == 0 &&
15161            TrueC->getAPIntValue().isPowerOf2()) {
15162          if (NeedsCondInvert) // Invert the condition if needed.
15163            Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
15164                               DAG.getConstant(1, Cond.getValueType()));
15165
15166          // Zero extend the condition if needed.
15167          Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
15168
15169          unsigned ShAmt = TrueC->getAPIntValue().logBase2();
15170          return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
15171                             DAG.getConstant(ShAmt, MVT::i8));
15172        }
15173
15174        // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
15175        if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
15176          if (NeedsCondInvert) // Invert the condition if needed.
15177            Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
15178                               DAG.getConstant(1, Cond.getValueType()));
15179
15180          // Zero extend the condition if needed.
15181          Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
15182                             FalseC->getValueType(0), Cond);
15183          return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
15184                             SDValue(FalseC, 0));
15185        }
15186
15187        // Optimize cases that will turn into an LEA instruction.  This requires
15188        // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
15189        if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
15190          uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
15191          if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
15192
15193          bool isFastMultiplier = false;
15194          if (Diff < 10) {
15195            switch ((unsigned char)Diff) {
15196              default: break;
15197              case 1:  // result = add base, cond
15198              case 2:  // result = lea base(    , cond*2)
15199              case 3:  // result = lea base(cond, cond*2)
15200              case 4:  // result = lea base(    , cond*4)
15201              case 5:  // result = lea base(cond, cond*4)
15202              case 8:  // result = lea base(    , cond*8)
15203              case 9:  // result = lea base(cond, cond*8)
15204                isFastMultiplier = true;
15205                break;
15206            }
15207          }
15208
15209          if (isFastMultiplier) {
15210            APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
15211            if (NeedsCondInvert) // Invert the condition if needed.
15212              Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
15213                                 DAG.getConstant(1, Cond.getValueType()));
15214
15215            // Zero extend the condition if needed.
15216            Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
15217                               Cond);
15218            // Scale the condition by the difference.
15219            if (Diff != 1)
15220              Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
15221                                 DAG.getConstant(Diff, Cond.getValueType()));
15222
15223            // Add the base if non-zero.
15224            if (FalseC->getAPIntValue() != 0)
15225              Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
15226                                 SDValue(FalseC, 0));
15227            return Cond;
15228          }
15229        }
15230      }
15231  }
15232
15233  // Canonicalize max and min:
15234  // (x > y) ? x : y -> (x >= y) ? x : y
15235  // (x < y) ? x : y -> (x <= y) ? x : y
15236  // This allows use of COND_S / COND_NS (see TranslateX86CC) which eliminates
15237  // the need for an extra compare
15238  // against zero. e.g.
15239  // (x - y) > 0 : (x - y) ? 0 -> (x - y) >= 0 : (x - y) ? 0
15240  // subl   %esi, %edi
15241  // testl  %edi, %edi
15242  // movl   $0, %eax
15243  // cmovgl %edi, %eax
15244  // =>
15245  // xorl   %eax, %eax
15246  // subl   %esi, $edi
15247  // cmovsl %eax, %edi
15248  if (N->getOpcode() == ISD::SELECT && Cond.getOpcode() == ISD::SETCC &&
15249      DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
15250      DAG.isEqualTo(RHS, Cond.getOperand(1))) {
15251    ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
15252    switch (CC) {
15253    default: break;
15254    case ISD::SETLT:
15255    case ISD::SETGT: {
15256      ISD::CondCode NewCC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGE;
15257      Cond = DAG.getSetCC(Cond.getDebugLoc(), Cond.getValueType(),
15258                          Cond.getOperand(0), Cond.getOperand(1), NewCC);
15259      return DAG.getNode(ISD::SELECT, DL, VT, Cond, LHS, RHS);
15260    }
15261    }
15262  }
15263
15264  // Match VSELECTs into subs with unsigned saturation.
15265  if (!DCI.isBeforeLegalize() &&
15266      N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
15267      // psubus is available in SSE2 and AVX2 for i8 and i16 vectors.
15268      ((Subtarget->hasSSE2() && (VT == MVT::v16i8 || VT == MVT::v8i16)) ||
15269       (Subtarget->hasAVX2() && (VT == MVT::v32i8 || VT == MVT::v16i16)))) {
15270    ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
15271
15272    // Check if one of the arms of the VSELECT is a zero vector. If it's on the
15273    // left side invert the predicate to simplify logic below.
15274    SDValue Other;
15275    if (ISD::isBuildVectorAllZeros(LHS.getNode())) {
15276      Other = RHS;
15277      CC = ISD::getSetCCInverse(CC, true);
15278    } else if (ISD::isBuildVectorAllZeros(RHS.getNode())) {
15279      Other = LHS;
15280    }
15281
15282    if (Other.getNode() && Other->getNumOperands() == 2 &&
15283        DAG.isEqualTo(Other->getOperand(0), Cond.getOperand(0))) {
15284      SDValue OpLHS = Other->getOperand(0), OpRHS = Other->getOperand(1);
15285      SDValue CondRHS = Cond->getOperand(1);
15286
15287      // Look for a general sub with unsigned saturation first.
15288      // x >= y ? x-y : 0 --> subus x, y
15289      // x >  y ? x-y : 0 --> subus x, y
15290      if ((CC == ISD::SETUGE || CC == ISD::SETUGT) &&
15291          Other->getOpcode() == ISD::SUB && DAG.isEqualTo(OpRHS, CondRHS))
15292        return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
15293
15294      // If the RHS is a constant we have to reverse the const canonicalization.
15295      // x > C-1 ? x+-C : 0 --> subus x, C
15296      if (CC == ISD::SETUGT && Other->getOpcode() == ISD::ADD &&
15297          isSplatVector(CondRHS.getNode()) && isSplatVector(OpRHS.getNode())) {
15298        APInt A = cast<ConstantSDNode>(OpRHS.getOperand(0))->getAPIntValue();
15299        if (CondRHS.getConstantOperandVal(0) == -A-1) {
15300          SmallVector<SDValue, 32> V(VT.getVectorNumElements(),
15301                                     DAG.getConstant(-A, VT.getScalarType()));
15302          return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS,
15303                             DAG.getNode(ISD::BUILD_VECTOR, DL, VT,
15304                                         V.data(), V.size()));
15305        }
15306      }
15307
15308      // Another special case: If C was a sign bit, the sub has been
15309      // canonicalized into a xor.
15310      // FIXME: Would it be better to use ComputeMaskedBits to determine whether
15311      //        it's safe to decanonicalize the xor?
15312      // x s< 0 ? x^C : 0 --> subus x, C
15313      if (CC == ISD::SETLT && Other->getOpcode() == ISD::XOR &&
15314          ISD::isBuildVectorAllZeros(CondRHS.getNode()) &&
15315          isSplatVector(OpRHS.getNode())) {
15316        APInt A = cast<ConstantSDNode>(OpRHS.getOperand(0))->getAPIntValue();
15317        if (A.isSignBit())
15318          return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
15319      }
15320    }
15321  }
15322
15323  // Try to match a min/max vector operation.
15324  if (!DCI.isBeforeLegalize() &&
15325      N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC)
15326    if (unsigned Op = matchIntegerMINMAX(Cond, VT, LHS, RHS, DAG, Subtarget))
15327      return DAG.getNode(Op, DL, N->getValueType(0), LHS, RHS);
15328
15329  // If we know that this node is legal then we know that it is going to be
15330  // matched by one of the SSE/AVX BLEND instructions. These instructions only
15331  // depend on the highest bit in each word. Try to use SimplifyDemandedBits
15332  // to simplify previous instructions.
15333  const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15334  if (N->getOpcode() == ISD::VSELECT && DCI.isBeforeLegalizeOps() &&
15335      !DCI.isBeforeLegalize() && TLI.isOperationLegal(ISD::VSELECT, VT)) {
15336    unsigned BitWidth = Cond.getValueType().getScalarType().getSizeInBits();
15337
15338    // Don't optimize vector selects that map to mask-registers.
15339    if (BitWidth == 1)
15340      return SDValue();
15341
15342    assert(BitWidth >= 8 && BitWidth <= 64 && "Invalid mask size");
15343    APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 1);
15344
15345    APInt KnownZero, KnownOne;
15346    TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
15347                                          DCI.isBeforeLegalizeOps());
15348    if (TLO.ShrinkDemandedConstant(Cond, DemandedMask) ||
15349        TLI.SimplifyDemandedBits(Cond, DemandedMask, KnownZero, KnownOne, TLO))
15350      DCI.CommitTargetLoweringOpt(TLO);
15351  }
15352
15353  return SDValue();
15354}
15355
15356// Check whether a boolean test is testing a boolean value generated by
15357// X86ISD::SETCC. If so, return the operand of that SETCC and proper condition
15358// code.
15359//
15360// Simplify the following patterns:
15361// (Op (CMP (SETCC Cond EFLAGS) 1) EQ) or
15362// (Op (CMP (SETCC Cond EFLAGS) 0) NEQ)
15363// to (Op EFLAGS Cond)
15364//
15365// (Op (CMP (SETCC Cond EFLAGS) 0) EQ) or
15366// (Op (CMP (SETCC Cond EFLAGS) 1) NEQ)
15367// to (Op EFLAGS !Cond)
15368//
15369// where Op could be BRCOND or CMOV.
15370//
15371static SDValue checkBoolTestSetCCCombine(SDValue Cmp, X86::CondCode &CC) {
15372  // Quit if not CMP and SUB with its value result used.
15373  if (Cmp.getOpcode() != X86ISD::CMP &&
15374      (Cmp.getOpcode() != X86ISD::SUB || Cmp.getNode()->hasAnyUseOfValue(0)))
15375      return SDValue();
15376
15377  // Quit if not used as a boolean value.
15378  if (CC != X86::COND_E && CC != X86::COND_NE)
15379    return SDValue();
15380
15381  // Check CMP operands. One of them should be 0 or 1 and the other should be
15382  // an SetCC or extended from it.
15383  SDValue Op1 = Cmp.getOperand(0);
15384  SDValue Op2 = Cmp.getOperand(1);
15385
15386  SDValue SetCC;
15387  const ConstantSDNode* C = 0;
15388  bool needOppositeCond = (CC == X86::COND_E);
15389
15390  if ((C = dyn_cast<ConstantSDNode>(Op1)))
15391    SetCC = Op2;
15392  else if ((C = dyn_cast<ConstantSDNode>(Op2)))
15393    SetCC = Op1;
15394  else // Quit if all operands are not constants.
15395    return SDValue();
15396
15397  if (C->getZExtValue() == 1)
15398    needOppositeCond = !needOppositeCond;
15399  else if (C->getZExtValue() != 0)
15400    // Quit if the constant is neither 0 or 1.
15401    return SDValue();
15402
15403  // Skip 'zext' node.
15404  if (SetCC.getOpcode() == ISD::ZERO_EXTEND)
15405    SetCC = SetCC.getOperand(0);
15406
15407  switch (SetCC.getOpcode()) {
15408  case X86ISD::SETCC:
15409    // Set the condition code or opposite one if necessary.
15410    CC = X86::CondCode(SetCC.getConstantOperandVal(0));
15411    if (needOppositeCond)
15412      CC = X86::GetOppositeBranchCondition(CC);
15413    return SetCC.getOperand(1);
15414  case X86ISD::CMOV: {
15415    // Check whether false/true value has canonical one, i.e. 0 or 1.
15416    ConstantSDNode *FVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(0));
15417    ConstantSDNode *TVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(1));
15418    // Quit if true value is not a constant.
15419    if (!TVal)
15420      return SDValue();
15421    // Quit if false value is not a constant.
15422    if (!FVal) {
15423      // A special case for rdrand, where 0 is set if false cond is found.
15424      SDValue Op = SetCC.getOperand(0);
15425      if (Op.getOpcode() != X86ISD::RDRAND)
15426        return SDValue();
15427    }
15428    // Quit if false value is not the constant 0 or 1.
15429    bool FValIsFalse = true;
15430    if (FVal && FVal->getZExtValue() != 0) {
15431      if (FVal->getZExtValue() != 1)
15432        return SDValue();
15433      // If FVal is 1, opposite cond is needed.
15434      needOppositeCond = !needOppositeCond;
15435      FValIsFalse = false;
15436    }
15437    // Quit if TVal is not the constant opposite of FVal.
15438    if (FValIsFalse && TVal->getZExtValue() != 1)
15439      return SDValue();
15440    if (!FValIsFalse && TVal->getZExtValue() != 0)
15441      return SDValue();
15442    CC = X86::CondCode(SetCC.getConstantOperandVal(2));
15443    if (needOppositeCond)
15444      CC = X86::GetOppositeBranchCondition(CC);
15445    return SetCC.getOperand(3);
15446  }
15447  }
15448
15449  return SDValue();
15450}
15451
15452/// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
15453static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
15454                                  TargetLowering::DAGCombinerInfo &DCI,
15455                                  const X86Subtarget *Subtarget) {
15456  DebugLoc DL = N->getDebugLoc();
15457
15458  // If the flag operand isn't dead, don't touch this CMOV.
15459  if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
15460    return SDValue();
15461
15462  SDValue FalseOp = N->getOperand(0);
15463  SDValue TrueOp = N->getOperand(1);
15464  X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
15465  SDValue Cond = N->getOperand(3);
15466
15467  if (CC == X86::COND_E || CC == X86::COND_NE) {
15468    switch (Cond.getOpcode()) {
15469    default: break;
15470    case X86ISD::BSR:
15471    case X86ISD::BSF:
15472      // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
15473      if (DAG.isKnownNeverZero(Cond.getOperand(0)))
15474        return (CC == X86::COND_E) ? FalseOp : TrueOp;
15475    }
15476  }
15477
15478  SDValue Flags;
15479
15480  Flags = checkBoolTestSetCCCombine(Cond, CC);
15481  if (Flags.getNode() &&
15482      // Extra check as FCMOV only supports a subset of X86 cond.
15483      (FalseOp.getValueType() != MVT::f80 || hasFPCMov(CC))) {
15484    SDValue Ops[] = { FalseOp, TrueOp,
15485                      DAG.getConstant(CC, MVT::i8), Flags };
15486    return DAG.getNode(X86ISD::CMOV, DL, N->getVTList(),
15487                       Ops, array_lengthof(Ops));
15488  }
15489
15490  // If this is a select between two integer constants, try to do some
15491  // optimizations.  Note that the operands are ordered the opposite of SELECT
15492  // operands.
15493  if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
15494    if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
15495      // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
15496      // larger than FalseC (the false value).
15497      if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
15498        CC = X86::GetOppositeBranchCondition(CC);
15499        std::swap(TrueC, FalseC);
15500        std::swap(TrueOp, FalseOp);
15501      }
15502
15503      // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3.  Likewise for any pow2/0.
15504      // This is efficient for any integer data type (including i8/i16) and
15505      // shift amount.
15506      if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
15507        Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
15508                           DAG.getConstant(CC, MVT::i8), Cond);
15509
15510        // Zero extend the condition if needed.
15511        Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
15512
15513        unsigned ShAmt = TrueC->getAPIntValue().logBase2();
15514        Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
15515                           DAG.getConstant(ShAmt, MVT::i8));
15516        if (N->getNumValues() == 2)  // Dead flag value?
15517          return DCI.CombineTo(N, Cond, SDValue());
15518        return Cond;
15519      }
15520
15521      // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.  This is efficient
15522      // for any integer data type, including i8/i16.
15523      if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
15524        Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
15525                           DAG.getConstant(CC, MVT::i8), Cond);
15526
15527        // Zero extend the condition if needed.
15528        Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
15529                           FalseC->getValueType(0), Cond);
15530        Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
15531                           SDValue(FalseC, 0));
15532
15533        if (N->getNumValues() == 2)  // Dead flag value?
15534          return DCI.CombineTo(N, Cond, SDValue());
15535        return Cond;
15536      }
15537
15538      // Optimize cases that will turn into an LEA instruction.  This requires
15539      // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
15540      if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
15541        uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
15542        if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
15543
15544        bool isFastMultiplier = false;
15545        if (Diff < 10) {
15546          switch ((unsigned char)Diff) {
15547          default: break;
15548          case 1:  // result = add base, cond
15549          case 2:  // result = lea base(    , cond*2)
15550          case 3:  // result = lea base(cond, cond*2)
15551          case 4:  // result = lea base(    , cond*4)
15552          case 5:  // result = lea base(cond, cond*4)
15553          case 8:  // result = lea base(    , cond*8)
15554          case 9:  // result = lea base(cond, cond*8)
15555            isFastMultiplier = true;
15556            break;
15557          }
15558        }
15559
15560        if (isFastMultiplier) {
15561          APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
15562          Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
15563                             DAG.getConstant(CC, MVT::i8), Cond);
15564          // Zero extend the condition if needed.
15565          Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
15566                             Cond);
15567          // Scale the condition by the difference.
15568          if (Diff != 1)
15569            Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
15570                               DAG.getConstant(Diff, Cond.getValueType()));
15571
15572          // Add the base if non-zero.
15573          if (FalseC->getAPIntValue() != 0)
15574            Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
15575                               SDValue(FalseC, 0));
15576          if (N->getNumValues() == 2)  // Dead flag value?
15577            return DCI.CombineTo(N, Cond, SDValue());
15578          return Cond;
15579        }
15580      }
15581    }
15582  }
15583
15584  // Handle these cases:
15585  //   (select (x != c), e, c) -> select (x != c), e, x),
15586  //   (select (x == c), c, e) -> select (x == c), x, e)
15587  // where the c is an integer constant, and the "select" is the combination
15588  // of CMOV and CMP.
15589  //
15590  // The rationale for this change is that the conditional-move from a constant
15591  // needs two instructions, however, conditional-move from a register needs
15592  // only one instruction.
15593  //
15594  // CAVEAT: By replacing a constant with a symbolic value, it may obscure
15595  //  some instruction-combining opportunities. This opt needs to be
15596  //  postponed as late as possible.
15597  //
15598  if (!DCI.isBeforeLegalize() && !DCI.isBeforeLegalizeOps()) {
15599    // the DCI.xxxx conditions are provided to postpone the optimization as
15600    // late as possible.
15601
15602    ConstantSDNode *CmpAgainst = 0;
15603    if ((Cond.getOpcode() == X86ISD::CMP || Cond.getOpcode() == X86ISD::SUB) &&
15604        (CmpAgainst = dyn_cast<ConstantSDNode>(Cond.getOperand(1))) &&
15605        dyn_cast<ConstantSDNode>(Cond.getOperand(0)) == 0) {
15606
15607      if (CC == X86::COND_NE &&
15608          CmpAgainst == dyn_cast<ConstantSDNode>(FalseOp)) {
15609        CC = X86::GetOppositeBranchCondition(CC);
15610        std::swap(TrueOp, FalseOp);
15611      }
15612
15613      if (CC == X86::COND_E &&
15614          CmpAgainst == dyn_cast<ConstantSDNode>(TrueOp)) {
15615        SDValue Ops[] = { FalseOp, Cond.getOperand(0),
15616                          DAG.getConstant(CC, MVT::i8), Cond };
15617        return DAG.getNode(X86ISD::CMOV, DL, N->getVTList (), Ops,
15618                           array_lengthof(Ops));
15619      }
15620    }
15621  }
15622
15623  return SDValue();
15624}
15625
15626/// PerformMulCombine - Optimize a single multiply with constant into two
15627/// in order to implement it with two cheaper instructions, e.g.
15628/// LEA + SHL, LEA + LEA.
15629static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
15630                                 TargetLowering::DAGCombinerInfo &DCI) {
15631  if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
15632    return SDValue();
15633
15634  EVT VT = N->getValueType(0);
15635  if (VT != MVT::i64)
15636    return SDValue();
15637
15638  ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
15639  if (!C)
15640    return SDValue();
15641  uint64_t MulAmt = C->getZExtValue();
15642  if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
15643    return SDValue();
15644
15645  uint64_t MulAmt1 = 0;
15646  uint64_t MulAmt2 = 0;
15647  if ((MulAmt % 9) == 0) {
15648    MulAmt1 = 9;
15649    MulAmt2 = MulAmt / 9;
15650  } else if ((MulAmt % 5) == 0) {
15651    MulAmt1 = 5;
15652    MulAmt2 = MulAmt / 5;
15653  } else if ((MulAmt % 3) == 0) {
15654    MulAmt1 = 3;
15655    MulAmt2 = MulAmt / 3;
15656  }
15657  if (MulAmt2 &&
15658      (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
15659    DebugLoc DL = N->getDebugLoc();
15660
15661    if (isPowerOf2_64(MulAmt2) &&
15662        !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
15663      // If second multiplifer is pow2, issue it first. We want the multiply by
15664      // 3, 5, or 9 to be folded into the addressing mode unless the lone use
15665      // is an add.
15666      std::swap(MulAmt1, MulAmt2);
15667
15668    SDValue NewMul;
15669    if (isPowerOf2_64(MulAmt1))
15670      NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
15671                           DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
15672    else
15673      NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
15674                           DAG.getConstant(MulAmt1, VT));
15675
15676    if (isPowerOf2_64(MulAmt2))
15677      NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
15678                           DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
15679    else
15680      NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
15681                           DAG.getConstant(MulAmt2, VT));
15682
15683    // Do not add new nodes to DAG combiner worklist.
15684    DCI.CombineTo(N, NewMul, false);
15685  }
15686  return SDValue();
15687}
15688
15689static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
15690  SDValue N0 = N->getOperand(0);
15691  SDValue N1 = N->getOperand(1);
15692  ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
15693  EVT VT = N0.getValueType();
15694
15695  // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
15696  // since the result of setcc_c is all zero's or all ones.
15697  if (VT.isInteger() && !VT.isVector() &&
15698      N1C && N0.getOpcode() == ISD::AND &&
15699      N0.getOperand(1).getOpcode() == ISD::Constant) {
15700    SDValue N00 = N0.getOperand(0);
15701    if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
15702        ((N00.getOpcode() == ISD::ANY_EXTEND ||
15703          N00.getOpcode() == ISD::ZERO_EXTEND) &&
15704         N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
15705      APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
15706      APInt ShAmt = N1C->getAPIntValue();
15707      Mask = Mask.shl(ShAmt);
15708      if (Mask != 0)
15709        return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
15710                           N00, DAG.getConstant(Mask, VT));
15711    }
15712  }
15713
15714  // Hardware support for vector shifts is sparse which makes us scalarize the
15715  // vector operations in many cases. Also, on sandybridge ADD is faster than
15716  // shl.
15717  // (shl V, 1) -> add V,V
15718  if (isSplatVector(N1.getNode())) {
15719    assert(N0.getValueType().isVector() && "Invalid vector shift type");
15720    ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1->getOperand(0));
15721    // We shift all of the values by one. In many cases we do not have
15722    // hardware support for this operation. This is better expressed as an ADD
15723    // of two values.
15724    if (N1C && (1 == N1C->getZExtValue())) {
15725      return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, N0, N0);
15726    }
15727  }
15728
15729  return SDValue();
15730}
15731
15732/// PerformShiftCombine - Transforms vector shift nodes to use vector shifts
15733///                       when possible.
15734static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
15735                                   TargetLowering::DAGCombinerInfo &DCI,
15736                                   const X86Subtarget *Subtarget) {
15737  EVT VT = N->getValueType(0);
15738  if (N->getOpcode() == ISD::SHL) {
15739    SDValue V = PerformSHLCombine(N, DAG);
15740    if (V.getNode()) return V;
15741  }
15742
15743  // On X86 with SSE2 support, we can transform this to a vector shift if
15744  // all elements are shifted by the same amount.  We can't do this in legalize
15745  // because the a constant vector is typically transformed to a constant pool
15746  // so we have no knowledge of the shift amount.
15747  if (!Subtarget->hasSSE2())
15748    return SDValue();
15749
15750  if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16 &&
15751      (!Subtarget->hasInt256() ||
15752       (VT != MVT::v4i64 && VT != MVT::v8i32 && VT != MVT::v16i16)))
15753    return SDValue();
15754
15755  SDValue ShAmtOp = N->getOperand(1);
15756  EVT EltVT = VT.getVectorElementType();
15757  DebugLoc DL = N->getDebugLoc();
15758  SDValue BaseShAmt = SDValue();
15759  if (ShAmtOp.getOpcode() == ISD::BUILD_VECTOR) {
15760    unsigned NumElts = VT.getVectorNumElements();
15761    unsigned i = 0;
15762    for (; i != NumElts; ++i) {
15763      SDValue Arg = ShAmtOp.getOperand(i);
15764      if (Arg.getOpcode() == ISD::UNDEF) continue;
15765      BaseShAmt = Arg;
15766      break;
15767    }
15768    // Handle the case where the build_vector is all undef
15769    // FIXME: Should DAG allow this?
15770    if (i == NumElts)
15771      return SDValue();
15772
15773    for (; i != NumElts; ++i) {
15774      SDValue Arg = ShAmtOp.getOperand(i);
15775      if (Arg.getOpcode() == ISD::UNDEF) continue;
15776      if (Arg != BaseShAmt) {
15777        return SDValue();
15778      }
15779    }
15780  } else if (ShAmtOp.getOpcode() == ISD::VECTOR_SHUFFLE &&
15781             cast<ShuffleVectorSDNode>(ShAmtOp)->isSplat()) {
15782    SDValue InVec = ShAmtOp.getOperand(0);
15783    if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
15784      unsigned NumElts = InVec.getValueType().getVectorNumElements();
15785      unsigned i = 0;
15786      for (; i != NumElts; ++i) {
15787        SDValue Arg = InVec.getOperand(i);
15788        if (Arg.getOpcode() == ISD::UNDEF) continue;
15789        BaseShAmt = Arg;
15790        break;
15791      }
15792    } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
15793       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
15794         unsigned SplatIdx= cast<ShuffleVectorSDNode>(ShAmtOp)->getSplatIndex();
15795         if (C->getZExtValue() == SplatIdx)
15796           BaseShAmt = InVec.getOperand(1);
15797       }
15798    }
15799    if (BaseShAmt.getNode() == 0) {
15800      // Don't create instructions with illegal types after legalize
15801      // types has run.
15802      if (!DAG.getTargetLoweringInfo().isTypeLegal(EltVT) &&
15803          !DCI.isBeforeLegalize())
15804        return SDValue();
15805
15806      BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, ShAmtOp,
15807                              DAG.getIntPtrConstant(0));
15808    }
15809  } else
15810    return SDValue();
15811
15812  // The shift amount is an i32.
15813  if (EltVT.bitsGT(MVT::i32))
15814    BaseShAmt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, BaseShAmt);
15815  else if (EltVT.bitsLT(MVT::i32))
15816    BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, BaseShAmt);
15817
15818  // The shift amount is identical so we can do a vector shift.
15819  SDValue  ValOp = N->getOperand(0);
15820  switch (N->getOpcode()) {
15821  default:
15822    llvm_unreachable("Unknown shift opcode!");
15823  case ISD::SHL:
15824    switch (VT.getSimpleVT().SimpleTy) {
15825    default: return SDValue();
15826    case MVT::v2i64:
15827    case MVT::v4i32:
15828    case MVT::v8i16:
15829    case MVT::v4i64:
15830    case MVT::v8i32:
15831    case MVT::v16i16:
15832      return getTargetVShiftNode(X86ISD::VSHLI, DL, VT, ValOp, BaseShAmt, DAG);
15833    }
15834  case ISD::SRA:
15835    switch (VT.getSimpleVT().SimpleTy) {
15836    default: return SDValue();
15837    case MVT::v4i32:
15838    case MVT::v8i16:
15839    case MVT::v8i32:
15840    case MVT::v16i16:
15841      return getTargetVShiftNode(X86ISD::VSRAI, DL, VT, ValOp, BaseShAmt, DAG);
15842    }
15843  case ISD::SRL:
15844    switch (VT.getSimpleVT().SimpleTy) {
15845    default: return SDValue();
15846    case MVT::v2i64:
15847    case MVT::v4i32:
15848    case MVT::v8i16:
15849    case MVT::v4i64:
15850    case MVT::v8i32:
15851    case MVT::v16i16:
15852      return getTargetVShiftNode(X86ISD::VSRLI, DL, VT, ValOp, BaseShAmt, DAG);
15853    }
15854  }
15855}
15856
15857// CMPEQCombine - Recognize the distinctive  (AND (setcc ...) (setcc ..))
15858// where both setccs reference the same FP CMP, and rewrite for CMPEQSS
15859// and friends.  Likewise for OR -> CMPNEQSS.
15860static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
15861                            TargetLowering::DAGCombinerInfo &DCI,
15862                            const X86Subtarget *Subtarget) {
15863  unsigned opcode;
15864
15865  // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
15866  // we're requiring SSE2 for both.
15867  if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
15868    SDValue N0 = N->getOperand(0);
15869    SDValue N1 = N->getOperand(1);
15870    SDValue CMP0 = N0->getOperand(1);
15871    SDValue CMP1 = N1->getOperand(1);
15872    DebugLoc DL = N->getDebugLoc();
15873
15874    // The SETCCs should both refer to the same CMP.
15875    if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
15876      return SDValue();
15877
15878    SDValue CMP00 = CMP0->getOperand(0);
15879    SDValue CMP01 = CMP0->getOperand(1);
15880    EVT     VT    = CMP00.getValueType();
15881
15882    if (VT == MVT::f32 || VT == MVT::f64) {
15883      bool ExpectingFlags = false;
15884      // Check for any users that want flags:
15885      for (SDNode::use_iterator UI = N->use_begin(),
15886             UE = N->use_end();
15887           !ExpectingFlags && UI != UE; ++UI)
15888        switch (UI->getOpcode()) {
15889        default:
15890        case ISD::BR_CC:
15891        case ISD::BRCOND:
15892        case ISD::SELECT:
15893          ExpectingFlags = true;
15894          break;
15895        case ISD::CopyToReg:
15896        case ISD::SIGN_EXTEND:
15897        case ISD::ZERO_EXTEND:
15898        case ISD::ANY_EXTEND:
15899          break;
15900        }
15901
15902      if (!ExpectingFlags) {
15903        enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
15904        enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
15905
15906        if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
15907          X86::CondCode tmp = cc0;
15908          cc0 = cc1;
15909          cc1 = tmp;
15910        }
15911
15912        if ((cc0 == X86::COND_E  && cc1 == X86::COND_NP) ||
15913            (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
15914          bool is64BitFP = (CMP00.getValueType() == MVT::f64);
15915          X86ISD::NodeType NTOperator = is64BitFP ?
15916            X86ISD::FSETCCsd : X86ISD::FSETCCss;
15917          // FIXME: need symbolic constants for these magic numbers.
15918          // See X86ATTInstPrinter.cpp:printSSECC().
15919          unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
15920          SDValue OnesOrZeroesF = DAG.getNode(NTOperator, DL, MVT::f32, CMP00, CMP01,
15921                                              DAG.getConstant(x86cc, MVT::i8));
15922          SDValue OnesOrZeroesI = DAG.getNode(ISD::BITCAST, DL, MVT::i32,
15923                                              OnesOrZeroesF);
15924          SDValue ANDed = DAG.getNode(ISD::AND, DL, MVT::i32, OnesOrZeroesI,
15925                                      DAG.getConstant(1, MVT::i32));
15926          SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8, ANDed);
15927          return OneBitOfTruth;
15928        }
15929      }
15930    }
15931  }
15932  return SDValue();
15933}
15934
15935/// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
15936/// so it can be folded inside ANDNP.
15937static bool CanFoldXORWithAllOnes(const SDNode *N) {
15938  EVT VT = N->getValueType(0);
15939
15940  // Match direct AllOnes for 128 and 256-bit vectors
15941  if (ISD::isBuildVectorAllOnes(N))
15942    return true;
15943
15944  // Look through a bit convert.
15945  if (N->getOpcode() == ISD::BITCAST)
15946    N = N->getOperand(0).getNode();
15947
15948  // Sometimes the operand may come from a insert_subvector building a 256-bit
15949  // allones vector
15950  if (VT.is256BitVector() &&
15951      N->getOpcode() == ISD::INSERT_SUBVECTOR) {
15952    SDValue V1 = N->getOperand(0);
15953    SDValue V2 = N->getOperand(1);
15954
15955    if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
15956        V1.getOperand(0).getOpcode() == ISD::UNDEF &&
15957        ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
15958        ISD::isBuildVectorAllOnes(V2.getNode()))
15959      return true;
15960  }
15961
15962  return false;
15963}
15964
15965// On AVX/AVX2 the type v8i1 is legalized to v8i16, which is an XMM sized
15966// register. In most cases we actually compare or select YMM-sized registers
15967// and mixing the two types creates horrible code. This method optimizes
15968// some of the transition sequences.
15969static SDValue WidenMaskArithmetic(SDNode *N, SelectionDAG &DAG,
15970                                 TargetLowering::DAGCombinerInfo &DCI,
15971                                 const X86Subtarget *Subtarget) {
15972  EVT VT = N->getValueType(0);
15973  if (VT.getSizeInBits() != 256)
15974    return SDValue();
15975
15976  assert((N->getOpcode() == ISD::ANY_EXTEND ||
15977          N->getOpcode() == ISD::ZERO_EXTEND ||
15978          N->getOpcode() == ISD::SIGN_EXTEND) && "Invalid Node");
15979
15980  SDValue Narrow = N->getOperand(0);
15981  EVT NarrowVT = Narrow->getValueType(0);
15982  if (NarrowVT.getSizeInBits() != 128)
15983    return SDValue();
15984
15985  if (Narrow->getOpcode() != ISD::XOR &&
15986      Narrow->getOpcode() != ISD::AND &&
15987      Narrow->getOpcode() != ISD::OR)
15988    return SDValue();
15989
15990  SDValue N0  = Narrow->getOperand(0);
15991  SDValue N1  = Narrow->getOperand(1);
15992  DebugLoc DL = Narrow->getDebugLoc();
15993
15994  // The Left side has to be a trunc.
15995  if (N0.getOpcode() != ISD::TRUNCATE)
15996    return SDValue();
15997
15998  // The type of the truncated inputs.
15999  EVT WideVT = N0->getOperand(0)->getValueType(0);
16000  if (WideVT != VT)
16001    return SDValue();
16002
16003  // The right side has to be a 'trunc' or a constant vector.
16004  bool RHSTrunc = N1.getOpcode() == ISD::TRUNCATE;
16005  bool RHSConst = (isSplatVector(N1.getNode()) &&
16006                   isa<ConstantSDNode>(N1->getOperand(0)));
16007  if (!RHSTrunc && !RHSConst)
16008    return SDValue();
16009
16010  const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16011
16012  if (!TLI.isOperationLegalOrPromote(Narrow->getOpcode(), WideVT))
16013    return SDValue();
16014
16015  // Set N0 and N1 to hold the inputs to the new wide operation.
16016  N0 = N0->getOperand(0);
16017  if (RHSConst) {
16018    N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT.getScalarType(),
16019                     N1->getOperand(0));
16020    SmallVector<SDValue, 8> C(WideVT.getVectorNumElements(), N1);
16021    N1 = DAG.getNode(ISD::BUILD_VECTOR, DL, WideVT, &C[0], C.size());
16022  } else if (RHSTrunc) {
16023    N1 = N1->getOperand(0);
16024  }
16025
16026  // Generate the wide operation.
16027  SDValue Op = DAG.getNode(Narrow->getOpcode(), DL, WideVT, N0, N1);
16028  unsigned Opcode = N->getOpcode();
16029  switch (Opcode) {
16030  case ISD::ANY_EXTEND:
16031    return Op;
16032  case ISD::ZERO_EXTEND: {
16033    unsigned InBits = NarrowVT.getScalarType().getSizeInBits();
16034    APInt Mask = APInt::getAllOnesValue(InBits);
16035    Mask = Mask.zext(VT.getScalarType().getSizeInBits());
16036    return DAG.getNode(ISD::AND, DL, VT,
16037                       Op, DAG.getConstant(Mask, VT));
16038  }
16039  case ISD::SIGN_EXTEND:
16040    return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT,
16041                       Op, DAG.getValueType(NarrowVT));
16042  default:
16043    llvm_unreachable("Unexpected opcode");
16044  }
16045}
16046
16047static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
16048                                 TargetLowering::DAGCombinerInfo &DCI,
16049                                 const X86Subtarget *Subtarget) {
16050  EVT VT = N->getValueType(0);
16051  if (DCI.isBeforeLegalizeOps())
16052    return SDValue();
16053
16054  SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
16055  if (R.getNode())
16056    return R;
16057
16058  // Create BLSI, and BLSR instructions
16059  // BLSI is X & (-X)
16060  // BLSR is X & (X-1)
16061  if (Subtarget->hasBMI() && (VT == MVT::i32 || VT == MVT::i64)) {
16062    SDValue N0 = N->getOperand(0);
16063    SDValue N1 = N->getOperand(1);
16064    DebugLoc DL = N->getDebugLoc();
16065
16066    // Check LHS for neg
16067    if (N0.getOpcode() == ISD::SUB && N0.getOperand(1) == N1 &&
16068        isZero(N0.getOperand(0)))
16069      return DAG.getNode(X86ISD::BLSI, DL, VT, N1);
16070
16071    // Check RHS for neg
16072    if (N1.getOpcode() == ISD::SUB && N1.getOperand(1) == N0 &&
16073        isZero(N1.getOperand(0)))
16074      return DAG.getNode(X86ISD::BLSI, DL, VT, N0);
16075
16076    // Check LHS for X-1
16077    if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1 &&
16078        isAllOnes(N0.getOperand(1)))
16079      return DAG.getNode(X86ISD::BLSR, DL, VT, N1);
16080
16081    // Check RHS for X-1
16082    if (N1.getOpcode() == ISD::ADD && N1.getOperand(0) == N0 &&
16083        isAllOnes(N1.getOperand(1)))
16084      return DAG.getNode(X86ISD::BLSR, DL, VT, N0);
16085
16086    return SDValue();
16087  }
16088
16089  // Want to form ANDNP nodes:
16090  // 1) In the hopes of then easily combining them with OR and AND nodes
16091  //    to form PBLEND/PSIGN.
16092  // 2) To match ANDN packed intrinsics
16093  if (VT != MVT::v2i64 && VT != MVT::v4i64)
16094    return SDValue();
16095
16096  SDValue N0 = N->getOperand(0);
16097  SDValue N1 = N->getOperand(1);
16098  DebugLoc DL = N->getDebugLoc();
16099
16100  // Check LHS for vnot
16101  if (N0.getOpcode() == ISD::XOR &&
16102      //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
16103      CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
16104    return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
16105
16106  // Check RHS for vnot
16107  if (N1.getOpcode() == ISD::XOR &&
16108      //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
16109      CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
16110    return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
16111
16112  return SDValue();
16113}
16114
16115static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
16116                                TargetLowering::DAGCombinerInfo &DCI,
16117                                const X86Subtarget *Subtarget) {
16118  EVT VT = N->getValueType(0);
16119  if (DCI.isBeforeLegalizeOps())
16120    return SDValue();
16121
16122  SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
16123  if (R.getNode())
16124    return R;
16125
16126  SDValue N0 = N->getOperand(0);
16127  SDValue N1 = N->getOperand(1);
16128
16129  // look for psign/blend
16130  if (VT == MVT::v2i64 || VT == MVT::v4i64) {
16131    if (!Subtarget->hasSSSE3() ||
16132        (VT == MVT::v4i64 && !Subtarget->hasInt256()))
16133      return SDValue();
16134
16135    // Canonicalize pandn to RHS
16136    if (N0.getOpcode() == X86ISD::ANDNP)
16137      std::swap(N0, N1);
16138    // or (and (m, y), (pandn m, x))
16139    if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
16140      SDValue Mask = N1.getOperand(0);
16141      SDValue X    = N1.getOperand(1);
16142      SDValue Y;
16143      if (N0.getOperand(0) == Mask)
16144        Y = N0.getOperand(1);
16145      if (N0.getOperand(1) == Mask)
16146        Y = N0.getOperand(0);
16147
16148      // Check to see if the mask appeared in both the AND and ANDNP and
16149      if (!Y.getNode())
16150        return SDValue();
16151
16152      // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
16153      // Look through mask bitcast.
16154      if (Mask.getOpcode() == ISD::BITCAST)
16155        Mask = Mask.getOperand(0);
16156      if (X.getOpcode() == ISD::BITCAST)
16157        X = X.getOperand(0);
16158      if (Y.getOpcode() == ISD::BITCAST)
16159        Y = Y.getOperand(0);
16160
16161      EVT MaskVT = Mask.getValueType();
16162
16163      // Validate that the Mask operand is a vector sra node.
16164      // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
16165      // there is no psrai.b
16166      if (Mask.getOpcode() != X86ISD::VSRAI)
16167        return SDValue();
16168
16169      // Check that the SRA is all signbits.
16170      SDValue SraC = Mask.getOperand(1);
16171      unsigned SraAmt  = cast<ConstantSDNode>(SraC)->getZExtValue();
16172      unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
16173      if ((SraAmt + 1) != EltBits)
16174        return SDValue();
16175
16176      DebugLoc DL = N->getDebugLoc();
16177
16178      // We are going to replace the AND, OR, NAND with either BLEND
16179      // or PSIGN, which only look at the MSB. The VSRAI instruction
16180      // does not affect the highest bit, so we can get rid of it.
16181      Mask = Mask.getOperand(0);
16182
16183      // Now we know we at least have a plendvb with the mask val.  See if
16184      // we can form a psignb/w/d.
16185      // psign = x.type == y.type == mask.type && y = sub(0, x);
16186      if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
16187          ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
16188          X.getValueType() == MaskVT && Y.getValueType() == MaskVT) {
16189        assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
16190               "Unsupported VT for PSIGN");
16191        Mask = DAG.getNode(X86ISD::PSIGN, DL, MaskVT, X, Mask);
16192        return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
16193      }
16194      // PBLENDVB only available on SSE 4.1
16195      if (!Subtarget->hasSSE41())
16196        return SDValue();
16197
16198      EVT BlendVT = (VT == MVT::v4i64) ? MVT::v32i8 : MVT::v16i8;
16199
16200      X = DAG.getNode(ISD::BITCAST, DL, BlendVT, X);
16201      Y = DAG.getNode(ISD::BITCAST, DL, BlendVT, Y);
16202      Mask = DAG.getNode(ISD::BITCAST, DL, BlendVT, Mask);
16203      Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, Y, X);
16204      return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
16205    }
16206  }
16207
16208  if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
16209    return SDValue();
16210
16211  // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
16212  if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
16213    std::swap(N0, N1);
16214  if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
16215    return SDValue();
16216  if (!N0.hasOneUse() || !N1.hasOneUse())
16217    return SDValue();
16218
16219  SDValue ShAmt0 = N0.getOperand(1);
16220  if (ShAmt0.getValueType() != MVT::i8)
16221    return SDValue();
16222  SDValue ShAmt1 = N1.getOperand(1);
16223  if (ShAmt1.getValueType() != MVT::i8)
16224    return SDValue();
16225  if (ShAmt0.getOpcode() == ISD::TRUNCATE)
16226    ShAmt0 = ShAmt0.getOperand(0);
16227  if (ShAmt1.getOpcode() == ISD::TRUNCATE)
16228    ShAmt1 = ShAmt1.getOperand(0);
16229
16230  DebugLoc DL = N->getDebugLoc();
16231  unsigned Opc = X86ISD::SHLD;
16232  SDValue Op0 = N0.getOperand(0);
16233  SDValue Op1 = N1.getOperand(0);
16234  if (ShAmt0.getOpcode() == ISD::SUB) {
16235    Opc = X86ISD::SHRD;
16236    std::swap(Op0, Op1);
16237    std::swap(ShAmt0, ShAmt1);
16238  }
16239
16240  unsigned Bits = VT.getSizeInBits();
16241  if (ShAmt1.getOpcode() == ISD::SUB) {
16242    SDValue Sum = ShAmt1.getOperand(0);
16243    if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
16244      SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
16245      if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
16246        ShAmt1Op1 = ShAmt1Op1.getOperand(0);
16247      if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
16248        return DAG.getNode(Opc, DL, VT,
16249                           Op0, Op1,
16250                           DAG.getNode(ISD::TRUNCATE, DL,
16251                                       MVT::i8, ShAmt0));
16252    }
16253  } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
16254    ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
16255    if (ShAmt0C &&
16256        ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
16257      return DAG.getNode(Opc, DL, VT,
16258                         N0.getOperand(0), N1.getOperand(0),
16259                         DAG.getNode(ISD::TRUNCATE, DL,
16260                                       MVT::i8, ShAmt0));
16261  }
16262
16263  return SDValue();
16264}
16265
16266// Generate NEG and CMOV for integer abs.
16267static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
16268  EVT VT = N->getValueType(0);
16269
16270  // Since X86 does not have CMOV for 8-bit integer, we don't convert
16271  // 8-bit integer abs to NEG and CMOV.
16272  if (VT.isInteger() && VT.getSizeInBits() == 8)
16273    return SDValue();
16274
16275  SDValue N0 = N->getOperand(0);
16276  SDValue N1 = N->getOperand(1);
16277  DebugLoc DL = N->getDebugLoc();
16278
16279  // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
16280  // and change it to SUB and CMOV.
16281  if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
16282      N0.getOpcode() == ISD::ADD &&
16283      N0.getOperand(1) == N1 &&
16284      N1.getOpcode() == ISD::SRA &&
16285      N1.getOperand(0) == N0.getOperand(0))
16286    if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
16287      if (Y1C->getAPIntValue() == VT.getSizeInBits()-1) {
16288        // Generate SUB & CMOV.
16289        SDValue Neg = DAG.getNode(X86ISD::SUB, DL, DAG.getVTList(VT, MVT::i32),
16290                                  DAG.getConstant(0, VT), N0.getOperand(0));
16291
16292        SDValue Ops[] = { N0.getOperand(0), Neg,
16293                          DAG.getConstant(X86::COND_GE, MVT::i8),
16294                          SDValue(Neg.getNode(), 1) };
16295        return DAG.getNode(X86ISD::CMOV, DL, DAG.getVTList(VT, MVT::Glue),
16296                           Ops, array_lengthof(Ops));
16297      }
16298  return SDValue();
16299}
16300
16301// PerformXorCombine - Attempts to turn XOR nodes into BLSMSK nodes
16302static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
16303                                 TargetLowering::DAGCombinerInfo &DCI,
16304                                 const X86Subtarget *Subtarget) {
16305  EVT VT = N->getValueType(0);
16306  if (DCI.isBeforeLegalizeOps())
16307    return SDValue();
16308
16309  if (Subtarget->hasCMov()) {
16310    SDValue RV = performIntegerAbsCombine(N, DAG);
16311    if (RV.getNode())
16312      return RV;
16313  }
16314
16315  // Try forming BMI if it is available.
16316  if (!Subtarget->hasBMI())
16317    return SDValue();
16318
16319  if (VT != MVT::i32 && VT != MVT::i64)
16320    return SDValue();
16321
16322  assert(Subtarget->hasBMI() && "Creating BLSMSK requires BMI instructions");
16323
16324  // Create BLSMSK instructions by finding X ^ (X-1)
16325  SDValue N0 = N->getOperand(0);
16326  SDValue N1 = N->getOperand(1);
16327  DebugLoc DL = N->getDebugLoc();
16328
16329  if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1 &&
16330      isAllOnes(N0.getOperand(1)))
16331    return DAG.getNode(X86ISD::BLSMSK, DL, VT, N1);
16332
16333  if (N1.getOpcode() == ISD::ADD && N1.getOperand(0) == N0 &&
16334      isAllOnes(N1.getOperand(1)))
16335    return DAG.getNode(X86ISD::BLSMSK, DL, VT, N0);
16336
16337  return SDValue();
16338}
16339
16340/// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
16341static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
16342                                  TargetLowering::DAGCombinerInfo &DCI,
16343                                  const X86Subtarget *Subtarget) {
16344  LoadSDNode *Ld = cast<LoadSDNode>(N);
16345  EVT RegVT = Ld->getValueType(0);
16346  EVT MemVT = Ld->getMemoryVT();
16347  DebugLoc dl = Ld->getDebugLoc();
16348  const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16349
16350  ISD::LoadExtType Ext = Ld->getExtensionType();
16351
16352  // If this is a vector EXT Load then attempt to optimize it using a
16353  // shuffle. If SSSE3 is not available we may emit an illegal shuffle but the
16354  // expansion is still better than scalar code.
16355  // We generate X86ISD::VSEXT for SEXTLOADs if it's available, otherwise we'll
16356  // emit a shuffle and a arithmetic shift.
16357  // TODO: It is possible to support ZExt by zeroing the undef values
16358  // during the shuffle phase or after the shuffle.
16359  if (RegVT.isVector() && RegVT.isInteger() && Subtarget->hasSSE2() &&
16360      (Ext == ISD::EXTLOAD || Ext == ISD::SEXTLOAD)) {
16361    assert(MemVT != RegVT && "Cannot extend to the same type");
16362    assert(MemVT.isVector() && "Must load a vector from memory");
16363
16364    unsigned NumElems = RegVT.getVectorNumElements();
16365    unsigned RegSz = RegVT.getSizeInBits();
16366    unsigned MemSz = MemVT.getSizeInBits();
16367    assert(RegSz > MemSz && "Register size must be greater than the mem size");
16368
16369    if (Ext == ISD::SEXTLOAD && RegSz == 256 && !Subtarget->hasInt256())
16370      return SDValue();
16371
16372    // All sizes must be a power of two.
16373    if (!isPowerOf2_32(RegSz * MemSz * NumElems))
16374      return SDValue();
16375
16376    // Attempt to load the original value using scalar loads.
16377    // Find the largest scalar type that divides the total loaded size.
16378    MVT SclrLoadTy = MVT::i8;
16379    for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
16380         tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
16381      MVT Tp = (MVT::SimpleValueType)tp;
16382      if (TLI.isTypeLegal(Tp) && ((MemSz % Tp.getSizeInBits()) == 0)) {
16383        SclrLoadTy = Tp;
16384      }
16385    }
16386
16387    // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
16388    if (TLI.isTypeLegal(MVT::f64) && SclrLoadTy.getSizeInBits() < 64 &&
16389        (64 <= MemSz))
16390      SclrLoadTy = MVT::f64;
16391
16392    // Calculate the number of scalar loads that we need to perform
16393    // in order to load our vector from memory.
16394    unsigned NumLoads = MemSz / SclrLoadTy.getSizeInBits();
16395    if (Ext == ISD::SEXTLOAD && NumLoads > 1)
16396      return SDValue();
16397
16398    unsigned loadRegZize = RegSz;
16399    if (Ext == ISD::SEXTLOAD && RegSz == 256)
16400      loadRegZize /= 2;
16401
16402    // Represent our vector as a sequence of elements which are the
16403    // largest scalar that we can load.
16404    EVT LoadUnitVecVT = EVT::getVectorVT(*DAG.getContext(), SclrLoadTy,
16405      loadRegZize/SclrLoadTy.getSizeInBits());
16406
16407    // Represent the data using the same element type that is stored in
16408    // memory. In practice, we ''widen'' MemVT.
16409    EVT WideVecVT =
16410	  EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
16411                       loadRegZize/MemVT.getScalarType().getSizeInBits());
16412
16413    assert(WideVecVT.getSizeInBits() == LoadUnitVecVT.getSizeInBits() &&
16414      "Invalid vector type");
16415
16416    // We can't shuffle using an illegal type.
16417    if (!TLI.isTypeLegal(WideVecVT))
16418      return SDValue();
16419
16420    SmallVector<SDValue, 8> Chains;
16421    SDValue Ptr = Ld->getBasePtr();
16422    SDValue Increment = DAG.getConstant(SclrLoadTy.getSizeInBits()/8,
16423                                        TLI.getPointerTy());
16424    SDValue Res = DAG.getUNDEF(LoadUnitVecVT);
16425
16426    for (unsigned i = 0; i < NumLoads; ++i) {
16427      // Perform a single load.
16428      SDValue ScalarLoad = DAG.getLoad(SclrLoadTy, dl, Ld->getChain(),
16429                                       Ptr, Ld->getPointerInfo(),
16430                                       Ld->isVolatile(), Ld->isNonTemporal(),
16431                                       Ld->isInvariant(), Ld->getAlignment());
16432      Chains.push_back(ScalarLoad.getValue(1));
16433      // Create the first element type using SCALAR_TO_VECTOR in order to avoid
16434      // another round of DAGCombining.
16435      if (i == 0)
16436        Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LoadUnitVecVT, ScalarLoad);
16437      else
16438        Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, LoadUnitVecVT, Res,
16439                          ScalarLoad, DAG.getIntPtrConstant(i));
16440
16441      Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
16442    }
16443
16444    SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Chains[0],
16445                               Chains.size());
16446
16447    // Bitcast the loaded value to a vector of the original element type, in
16448    // the size of the target vector type.
16449    SDValue SlicedVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Res);
16450    unsigned SizeRatio = RegSz/MemSz;
16451
16452    if (Ext == ISD::SEXTLOAD) {
16453      // If we have SSE4.1 we can directly emit a VSEXT node.
16454      if (Subtarget->hasSSE41()) {
16455        SDValue Sext = DAG.getNode(X86ISD::VSEXT, dl, RegVT, SlicedVec);
16456        return DCI.CombineTo(N, Sext, TF, true);
16457      }
16458
16459      // Otherwise we'll shuffle the small elements in the high bits of the
16460      // larger type and perform an arithmetic shift. If the shift is not legal
16461      // it's better to scalarize.
16462      if (!TLI.isOperationLegalOrCustom(ISD::SRA, RegVT))
16463        return SDValue();
16464
16465      // Redistribute the loaded elements into the different locations.
16466      SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
16467      for (unsigned i = 0; i != NumElems; ++i)
16468        ShuffleVec[i*SizeRatio + SizeRatio-1] = i;
16469
16470      SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
16471                                           DAG.getUNDEF(WideVecVT),
16472                                           &ShuffleVec[0]);
16473
16474      Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
16475
16476      // Build the arithmetic shift.
16477      unsigned Amt = RegVT.getVectorElementType().getSizeInBits() -
16478                     MemVT.getVectorElementType().getSizeInBits();
16479      SmallVector<SDValue, 8> C(NumElems,
16480                                DAG.getConstant(Amt, RegVT.getScalarType()));
16481      SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, RegVT, &C[0], C.size());
16482      Shuff = DAG.getNode(ISD::SRA, dl, RegVT, Shuff, BV);
16483
16484      return DCI.CombineTo(N, Shuff, TF, true);
16485    }
16486
16487    // Redistribute the loaded elements into the different locations.
16488    SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
16489    for (unsigned i = 0; i != NumElems; ++i)
16490      ShuffleVec[i*SizeRatio] = i;
16491
16492    SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
16493                                         DAG.getUNDEF(WideVecVT),
16494                                         &ShuffleVec[0]);
16495
16496    // Bitcast to the requested type.
16497    Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
16498    // Replace the original load with the new sequence
16499    // and return the new chain.
16500    return DCI.CombineTo(N, Shuff, TF, true);
16501  }
16502
16503  return SDValue();
16504}
16505
16506/// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
16507static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
16508                                   const X86Subtarget *Subtarget) {
16509  StoreSDNode *St = cast<StoreSDNode>(N);
16510  EVT VT = St->getValue().getValueType();
16511  EVT StVT = St->getMemoryVT();
16512  DebugLoc dl = St->getDebugLoc();
16513  SDValue StoredVal = St->getOperand(1);
16514  const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16515
16516  // If we are saving a concatenation of two XMM registers, perform two stores.
16517  // On Sandy Bridge, 256-bit memory operations are executed by two
16518  // 128-bit ports. However, on Haswell it is better to issue a single 256-bit
16519  // memory  operation.
16520  if (VT.is256BitVector() && !Subtarget->hasInt256() &&
16521      StoredVal.getNode()->getOpcode() == ISD::CONCAT_VECTORS &&
16522      StoredVal.getNumOperands() == 2) {
16523    SDValue Value0 = StoredVal.getOperand(0);
16524    SDValue Value1 = StoredVal.getOperand(1);
16525
16526    SDValue Stride = DAG.getConstant(16, TLI.getPointerTy());
16527    SDValue Ptr0 = St->getBasePtr();
16528    SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
16529
16530    SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
16531                                St->getPointerInfo(), St->isVolatile(),
16532                                St->isNonTemporal(), St->getAlignment());
16533    SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
16534                                St->getPointerInfo(), St->isVolatile(),
16535                                St->isNonTemporal(), St->getAlignment());
16536    return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
16537  }
16538
16539  // Optimize trunc store (of multiple scalars) to shuffle and store.
16540  // First, pack all of the elements in one place. Next, store to memory
16541  // in fewer chunks.
16542  if (St->isTruncatingStore() && VT.isVector()) {
16543    const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16544    unsigned NumElems = VT.getVectorNumElements();
16545    assert(StVT != VT && "Cannot truncate to the same type");
16546    unsigned FromSz = VT.getVectorElementType().getSizeInBits();
16547    unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
16548
16549    // From, To sizes and ElemCount must be pow of two
16550    if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
16551    // We are going to use the original vector elt for storing.
16552    // Accumulated smaller vector elements must be a multiple of the store size.
16553    if (0 != (NumElems * FromSz) % ToSz) return SDValue();
16554
16555    unsigned SizeRatio  = FromSz / ToSz;
16556
16557    assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
16558
16559    // Create a type on which we perform the shuffle
16560    EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
16561            StVT.getScalarType(), NumElems*SizeRatio);
16562
16563    assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
16564
16565    SDValue WideVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, St->getValue());
16566    SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
16567    for (unsigned i = 0; i != NumElems; ++i)
16568      ShuffleVec[i] = i * SizeRatio;
16569
16570    // Can't shuffle using an illegal type.
16571    if (!TLI.isTypeLegal(WideVecVT))
16572      return SDValue();
16573
16574    SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
16575                                         DAG.getUNDEF(WideVecVT),
16576                                         &ShuffleVec[0]);
16577    // At this point all of the data is stored at the bottom of the
16578    // register. We now need to save it to mem.
16579
16580    // Find the largest store unit
16581    MVT StoreType = MVT::i8;
16582    for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
16583         tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
16584      MVT Tp = (MVT::SimpleValueType)tp;
16585      if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToSz)
16586        StoreType = Tp;
16587    }
16588
16589    // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
16590    if (TLI.isTypeLegal(MVT::f64) && StoreType.getSizeInBits() < 64 &&
16591        (64 <= NumElems * ToSz))
16592      StoreType = MVT::f64;
16593
16594    // Bitcast the original vector into a vector of store-size units
16595    EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
16596            StoreType, VT.getSizeInBits()/StoreType.getSizeInBits());
16597    assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
16598    SDValue ShuffWide = DAG.getNode(ISD::BITCAST, dl, StoreVecVT, Shuff);
16599    SmallVector<SDValue, 8> Chains;
16600    SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
16601                                        TLI.getPointerTy());
16602    SDValue Ptr = St->getBasePtr();
16603
16604    // Perform one or more big stores into memory.
16605    for (unsigned i=0, e=(ToSz*NumElems)/StoreType.getSizeInBits(); i!=e; ++i) {
16606      SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
16607                                   StoreType, ShuffWide,
16608                                   DAG.getIntPtrConstant(i));
16609      SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
16610                                St->getPointerInfo(), St->isVolatile(),
16611                                St->isNonTemporal(), St->getAlignment());
16612      Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
16613      Chains.push_back(Ch);
16614    }
16615
16616    return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Chains[0],
16617                               Chains.size());
16618  }
16619
16620  // Turn load->store of MMX types into GPR load/stores.  This avoids clobbering
16621  // the FP state in cases where an emms may be missing.
16622  // A preferable solution to the general problem is to figure out the right
16623  // places to insert EMMS.  This qualifies as a quick hack.
16624
16625  // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
16626  if (VT.getSizeInBits() != 64)
16627    return SDValue();
16628
16629  const Function *F = DAG.getMachineFunction().getFunction();
16630  bool NoImplicitFloatOps = F->getAttributes().
16631    hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
16632  bool F64IsLegal = !DAG.getTarget().Options.UseSoftFloat && !NoImplicitFloatOps
16633                     && Subtarget->hasSSE2();
16634  if ((VT.isVector() ||
16635       (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
16636      isa<LoadSDNode>(St->getValue()) &&
16637      !cast<LoadSDNode>(St->getValue())->isVolatile() &&
16638      St->getChain().hasOneUse() && !St->isVolatile()) {
16639    SDNode* LdVal = St->getValue().getNode();
16640    LoadSDNode *Ld = 0;
16641    int TokenFactorIndex = -1;
16642    SmallVector<SDValue, 8> Ops;
16643    SDNode* ChainVal = St->getChain().getNode();
16644    // Must be a store of a load.  We currently handle two cases:  the load
16645    // is a direct child, and it's under an intervening TokenFactor.  It is
16646    // possible to dig deeper under nested TokenFactors.
16647    if (ChainVal == LdVal)
16648      Ld = cast<LoadSDNode>(St->getChain());
16649    else if (St->getValue().hasOneUse() &&
16650             ChainVal->getOpcode() == ISD::TokenFactor) {
16651      for (unsigned i = 0, e = ChainVal->getNumOperands(); i != e; ++i) {
16652        if (ChainVal->getOperand(i).getNode() == LdVal) {
16653          TokenFactorIndex = i;
16654          Ld = cast<LoadSDNode>(St->getValue());
16655        } else
16656          Ops.push_back(ChainVal->getOperand(i));
16657      }
16658    }
16659
16660    if (!Ld || !ISD::isNormalLoad(Ld))
16661      return SDValue();
16662
16663    // If this is not the MMX case, i.e. we are just turning i64 load/store
16664    // into f64 load/store, avoid the transformation if there are multiple
16665    // uses of the loaded value.
16666    if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
16667      return SDValue();
16668
16669    DebugLoc LdDL = Ld->getDebugLoc();
16670    DebugLoc StDL = N->getDebugLoc();
16671    // If we are a 64-bit capable x86, lower to a single movq load/store pair.
16672    // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
16673    // pair instead.
16674    if (Subtarget->is64Bit() || F64IsLegal) {
16675      EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
16676      SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
16677                                  Ld->getPointerInfo(), Ld->isVolatile(),
16678                                  Ld->isNonTemporal(), Ld->isInvariant(),
16679                                  Ld->getAlignment());
16680      SDValue NewChain = NewLd.getValue(1);
16681      if (TokenFactorIndex != -1) {
16682        Ops.push_back(NewChain);
16683        NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
16684                               Ops.size());
16685      }
16686      return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
16687                          St->getPointerInfo(),
16688                          St->isVolatile(), St->isNonTemporal(),
16689                          St->getAlignment());
16690    }
16691
16692    // Otherwise, lower to two pairs of 32-bit loads / stores.
16693    SDValue LoAddr = Ld->getBasePtr();
16694    SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
16695                                 DAG.getConstant(4, MVT::i32));
16696
16697    SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
16698                               Ld->getPointerInfo(),
16699                               Ld->isVolatile(), Ld->isNonTemporal(),
16700                               Ld->isInvariant(), Ld->getAlignment());
16701    SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
16702                               Ld->getPointerInfo().getWithOffset(4),
16703                               Ld->isVolatile(), Ld->isNonTemporal(),
16704                               Ld->isInvariant(),
16705                               MinAlign(Ld->getAlignment(), 4));
16706
16707    SDValue NewChain = LoLd.getValue(1);
16708    if (TokenFactorIndex != -1) {
16709      Ops.push_back(LoLd);
16710      Ops.push_back(HiLd);
16711      NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
16712                             Ops.size());
16713    }
16714
16715    LoAddr = St->getBasePtr();
16716    HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
16717                         DAG.getConstant(4, MVT::i32));
16718
16719    SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
16720                                St->getPointerInfo(),
16721                                St->isVolatile(), St->isNonTemporal(),
16722                                St->getAlignment());
16723    SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
16724                                St->getPointerInfo().getWithOffset(4),
16725                                St->isVolatile(),
16726                                St->isNonTemporal(),
16727                                MinAlign(St->getAlignment(), 4));
16728    return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
16729  }
16730  return SDValue();
16731}
16732
16733/// isHorizontalBinOp - Return 'true' if this vector operation is "horizontal"
16734/// and return the operands for the horizontal operation in LHS and RHS.  A
16735/// horizontal operation performs the binary operation on successive elements
16736/// of its first operand, then on successive elements of its second operand,
16737/// returning the resulting values in a vector.  For example, if
16738///   A = < float a0, float a1, float a2, float a3 >
16739/// and
16740///   B = < float b0, float b1, float b2, float b3 >
16741/// then the result of doing a horizontal operation on A and B is
16742///   A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
16743/// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
16744/// A horizontal-op B, for some already available A and B, and if so then LHS is
16745/// set to A, RHS to B, and the routine returns 'true'.
16746/// Note that the binary operation should have the property that if one of the
16747/// operands is UNDEF then the result is UNDEF.
16748static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool IsCommutative) {
16749  // Look for the following pattern: if
16750  //   A = < float a0, float a1, float a2, float a3 >
16751  //   B = < float b0, float b1, float b2, float b3 >
16752  // and
16753  //   LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
16754  //   RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
16755  // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
16756  // which is A horizontal-op B.
16757
16758  // At least one of the operands should be a vector shuffle.
16759  if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
16760      RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
16761    return false;
16762
16763  EVT VT = LHS.getValueType();
16764
16765  assert((VT.is128BitVector() || VT.is256BitVector()) &&
16766         "Unsupported vector type for horizontal add/sub");
16767
16768  // Handle 128 and 256-bit vector lengths. AVX defines horizontal add/sub to
16769  // operate independently on 128-bit lanes.
16770  unsigned NumElts = VT.getVectorNumElements();
16771  unsigned NumLanes = VT.getSizeInBits()/128;
16772  unsigned NumLaneElts = NumElts / NumLanes;
16773  assert((NumLaneElts % 2 == 0) &&
16774         "Vector type should have an even number of elements in each lane");
16775  unsigned HalfLaneElts = NumLaneElts/2;
16776
16777  // View LHS in the form
16778  //   LHS = VECTOR_SHUFFLE A, B, LMask
16779  // If LHS is not a shuffle then pretend it is the shuffle
16780  //   LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
16781  // NOTE: in what follows a default initialized SDValue represents an UNDEF of
16782  // type VT.
16783  SDValue A, B;
16784  SmallVector<int, 16> LMask(NumElts);
16785  if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
16786    if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
16787      A = LHS.getOperand(0);
16788    if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
16789      B = LHS.getOperand(1);
16790    ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(LHS.getNode())->getMask();
16791    std::copy(Mask.begin(), Mask.end(), LMask.begin());
16792  } else {
16793    if (LHS.getOpcode() != ISD::UNDEF)
16794      A = LHS;
16795    for (unsigned i = 0; i != NumElts; ++i)
16796      LMask[i] = i;
16797  }
16798
16799  // Likewise, view RHS in the form
16800  //   RHS = VECTOR_SHUFFLE C, D, RMask
16801  SDValue C, D;
16802  SmallVector<int, 16> RMask(NumElts);
16803  if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
16804    if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
16805      C = RHS.getOperand(0);
16806    if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
16807      D = RHS.getOperand(1);
16808    ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(RHS.getNode())->getMask();
16809    std::copy(Mask.begin(), Mask.end(), RMask.begin());
16810  } else {
16811    if (RHS.getOpcode() != ISD::UNDEF)
16812      C = RHS;
16813    for (unsigned i = 0; i != NumElts; ++i)
16814      RMask[i] = i;
16815  }
16816
16817  // Check that the shuffles are both shuffling the same vectors.
16818  if (!(A == C && B == D) && !(A == D && B == C))
16819    return false;
16820
16821  // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
16822  if (!A.getNode() && !B.getNode())
16823    return false;
16824
16825  // If A and B occur in reverse order in RHS, then "swap" them (which means
16826  // rewriting the mask).
16827  if (A != C)
16828    CommuteVectorShuffleMask(RMask, NumElts);
16829
16830  // At this point LHS and RHS are equivalent to
16831  //   LHS = VECTOR_SHUFFLE A, B, LMask
16832  //   RHS = VECTOR_SHUFFLE A, B, RMask
16833  // Check that the masks correspond to performing a horizontal operation.
16834  for (unsigned i = 0; i != NumElts; ++i) {
16835    int LIdx = LMask[i], RIdx = RMask[i];
16836
16837    // Ignore any UNDEF components.
16838    if (LIdx < 0 || RIdx < 0 ||
16839        (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) ||
16840        (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts)))
16841      continue;
16842
16843    // Check that successive elements are being operated on.  If not, this is
16844    // not a horizontal operation.
16845    unsigned Src = (i/HalfLaneElts) % 2; // each lane is split between srcs
16846    unsigned LaneStart = (i/NumLaneElts) * NumLaneElts;
16847    int Index = 2*(i%HalfLaneElts) + NumElts*Src + LaneStart;
16848    if (!(LIdx == Index && RIdx == Index + 1) &&
16849        !(IsCommutative && LIdx == Index + 1 && RIdx == Index))
16850      return false;
16851  }
16852
16853  LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
16854  RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
16855  return true;
16856}
16857
16858/// PerformFADDCombine - Do target-specific dag combines on floating point adds.
16859static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
16860                                  const X86Subtarget *Subtarget) {
16861  EVT VT = N->getValueType(0);
16862  SDValue LHS = N->getOperand(0);
16863  SDValue RHS = N->getOperand(1);
16864
16865  // Try to synthesize horizontal adds from adds of shuffles.
16866  if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
16867       (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
16868      isHorizontalBinOp(LHS, RHS, true))
16869    return DAG.getNode(X86ISD::FHADD, N->getDebugLoc(), VT, LHS, RHS);
16870  return SDValue();
16871}
16872
16873/// PerformFSUBCombine - Do target-specific dag combines on floating point subs.
16874static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
16875                                  const X86Subtarget *Subtarget) {
16876  EVT VT = N->getValueType(0);
16877  SDValue LHS = N->getOperand(0);
16878  SDValue RHS = N->getOperand(1);
16879
16880  // Try to synthesize horizontal subs from subs of shuffles.
16881  if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
16882       (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
16883      isHorizontalBinOp(LHS, RHS, false))
16884    return DAG.getNode(X86ISD::FHSUB, N->getDebugLoc(), VT, LHS, RHS);
16885  return SDValue();
16886}
16887
16888/// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
16889/// X86ISD::FXOR nodes.
16890static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
16891  assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
16892  // F[X]OR(0.0, x) -> x
16893  // F[X]OR(x, 0.0) -> x
16894  if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
16895    if (C->getValueAPF().isPosZero())
16896      return N->getOperand(1);
16897  if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
16898    if (C->getValueAPF().isPosZero())
16899      return N->getOperand(0);
16900  return SDValue();
16901}
16902
16903/// PerformFMinFMaxCombine - Do target-specific dag combines on X86ISD::FMIN and
16904/// X86ISD::FMAX nodes.
16905static SDValue PerformFMinFMaxCombine(SDNode *N, SelectionDAG &DAG) {
16906  assert(N->getOpcode() == X86ISD::FMIN || N->getOpcode() == X86ISD::FMAX);
16907
16908  // Only perform optimizations if UnsafeMath is used.
16909  if (!DAG.getTarget().Options.UnsafeFPMath)
16910    return SDValue();
16911
16912  // If we run in unsafe-math mode, then convert the FMAX and FMIN nodes
16913  // into FMINC and FMAXC, which are Commutative operations.
16914  unsigned NewOp = 0;
16915  switch (N->getOpcode()) {
16916    default: llvm_unreachable("unknown opcode");
16917    case X86ISD::FMIN:  NewOp = X86ISD::FMINC; break;
16918    case X86ISD::FMAX:  NewOp = X86ISD::FMAXC; break;
16919  }
16920
16921  return DAG.getNode(NewOp, N->getDebugLoc(), N->getValueType(0),
16922                     N->getOperand(0), N->getOperand(1));
16923}
16924
16925/// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
16926static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
16927  // FAND(0.0, x) -> 0.0
16928  // FAND(x, 0.0) -> 0.0
16929  if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
16930    if (C->getValueAPF().isPosZero())
16931      return N->getOperand(0);
16932  if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
16933    if (C->getValueAPF().isPosZero())
16934      return N->getOperand(1);
16935  return SDValue();
16936}
16937
16938static SDValue PerformBTCombine(SDNode *N,
16939                                SelectionDAG &DAG,
16940                                TargetLowering::DAGCombinerInfo &DCI) {
16941  // BT ignores high bits in the bit index operand.
16942  SDValue Op1 = N->getOperand(1);
16943  if (Op1.hasOneUse()) {
16944    unsigned BitWidth = Op1.getValueSizeInBits();
16945    APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
16946    APInt KnownZero, KnownOne;
16947    TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
16948                                          !DCI.isBeforeLegalizeOps());
16949    const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16950    if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
16951        TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
16952      DCI.CommitTargetLoweringOpt(TLO);
16953  }
16954  return SDValue();
16955}
16956
16957static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
16958  SDValue Op = N->getOperand(0);
16959  if (Op.getOpcode() == ISD::BITCAST)
16960    Op = Op.getOperand(0);
16961  EVT VT = N->getValueType(0), OpVT = Op.getValueType();
16962  if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
16963      VT.getVectorElementType().getSizeInBits() ==
16964      OpVT.getVectorElementType().getSizeInBits()) {
16965    return DAG.getNode(ISD::BITCAST, N->getDebugLoc(), VT, Op);
16966  }
16967  return SDValue();
16968}
16969
16970static SDValue PerformSExtCombine(SDNode *N, SelectionDAG &DAG,
16971                                  TargetLowering::DAGCombinerInfo &DCI,
16972                                  const X86Subtarget *Subtarget) {
16973  if (!DCI.isBeforeLegalizeOps())
16974    return SDValue();
16975
16976  if (!Subtarget->hasFp256())
16977    return SDValue();
16978
16979  EVT VT = N->getValueType(0);
16980  if (VT.isVector() && VT.getSizeInBits() == 256) {
16981    SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
16982    if (R.getNode())
16983      return R;
16984  }
16985
16986  return SDValue();
16987}
16988
16989static SDValue PerformFMACombine(SDNode *N, SelectionDAG &DAG,
16990                                 const X86Subtarget* Subtarget) {
16991  DebugLoc dl = N->getDebugLoc();
16992  EVT VT = N->getValueType(0);
16993
16994  // Let legalize expand this if it isn't a legal type yet.
16995  if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
16996    return SDValue();
16997
16998  EVT ScalarVT = VT.getScalarType();
16999  if ((ScalarVT != MVT::f32 && ScalarVT != MVT::f64) ||
17000      (!Subtarget->hasFMA() && !Subtarget->hasFMA4()))
17001    return SDValue();
17002
17003  SDValue A = N->getOperand(0);
17004  SDValue B = N->getOperand(1);
17005  SDValue C = N->getOperand(2);
17006
17007  bool NegA = (A.getOpcode() == ISD::FNEG);
17008  bool NegB = (B.getOpcode() == ISD::FNEG);
17009  bool NegC = (C.getOpcode() == ISD::FNEG);
17010
17011  // Negative multiplication when NegA xor NegB
17012  bool NegMul = (NegA != NegB);
17013  if (NegA)
17014    A = A.getOperand(0);
17015  if (NegB)
17016    B = B.getOperand(0);
17017  if (NegC)
17018    C = C.getOperand(0);
17019
17020  unsigned Opcode;
17021  if (!NegMul)
17022    Opcode = (!NegC) ? X86ISD::FMADD : X86ISD::FMSUB;
17023  else
17024    Opcode = (!NegC) ? X86ISD::FNMADD : X86ISD::FNMSUB;
17025
17026  return DAG.getNode(Opcode, dl, VT, A, B, C);
17027}
17028
17029static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG,
17030                                  TargetLowering::DAGCombinerInfo &DCI,
17031                                  const X86Subtarget *Subtarget) {
17032  // (i32 zext (and (i8  x86isd::setcc_carry), 1)) ->
17033  //           (and (i32 x86isd::setcc_carry), 1)
17034  // This eliminates the zext. This transformation is necessary because
17035  // ISD::SETCC is always legalized to i8.
17036  DebugLoc dl = N->getDebugLoc();
17037  SDValue N0 = N->getOperand(0);
17038  EVT VT = N->getValueType(0);
17039
17040  if (N0.getOpcode() == ISD::AND &&
17041      N0.hasOneUse() &&
17042      N0.getOperand(0).hasOneUse()) {
17043    SDValue N00 = N0.getOperand(0);
17044    if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
17045      ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
17046      if (!C || C->getZExtValue() != 1)
17047        return SDValue();
17048      return DAG.getNode(ISD::AND, dl, VT,
17049                         DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
17050                                     N00.getOperand(0), N00.getOperand(1)),
17051                         DAG.getConstant(1, VT));
17052    }
17053  }
17054
17055  if (VT.isVector() && VT.getSizeInBits() == 256) {
17056    SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
17057    if (R.getNode())
17058      return R;
17059  }
17060
17061  return SDValue();
17062}
17063
17064// Optimize x == -y --> x+y == 0
17065//          x != -y --> x+y != 0
17066static SDValue PerformISDSETCCCombine(SDNode *N, SelectionDAG &DAG) {
17067  ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
17068  SDValue LHS = N->getOperand(0);
17069  SDValue RHS = N->getOperand(1);
17070
17071  if ((CC == ISD::SETNE || CC == ISD::SETEQ) && LHS.getOpcode() == ISD::SUB)
17072    if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(LHS.getOperand(0)))
17073      if (C->getAPIntValue() == 0 && LHS.hasOneUse()) {
17074        SDValue addV = DAG.getNode(ISD::ADD, N->getDebugLoc(),
17075                                   LHS.getValueType(), RHS, LHS.getOperand(1));
17076        return DAG.getSetCC(N->getDebugLoc(), N->getValueType(0),
17077                            addV, DAG.getConstant(0, addV.getValueType()), CC);
17078      }
17079  if ((CC == ISD::SETNE || CC == ISD::SETEQ) && RHS.getOpcode() == ISD::SUB)
17080    if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS.getOperand(0)))
17081      if (C->getAPIntValue() == 0 && RHS.hasOneUse()) {
17082        SDValue addV = DAG.getNode(ISD::ADD, N->getDebugLoc(),
17083                                   RHS.getValueType(), LHS, RHS.getOperand(1));
17084        return DAG.getSetCC(N->getDebugLoc(), N->getValueType(0),
17085                            addV, DAG.getConstant(0, addV.getValueType()), CC);
17086      }
17087  return SDValue();
17088}
17089
17090// Helper function of PerformSETCCCombine. It is to materialize "setb reg"
17091// as "sbb reg,reg", since it can be extended without zext and produces
17092// an all-ones bit which is more useful than 0/1 in some cases.
17093static SDValue MaterializeSETB(DebugLoc DL, SDValue EFLAGS, SelectionDAG &DAG) {
17094  return DAG.getNode(ISD::AND, DL, MVT::i8,
17095                     DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
17096                                 DAG.getConstant(X86::COND_B, MVT::i8), EFLAGS),
17097                     DAG.getConstant(1, MVT::i8));
17098}
17099
17100// Optimize  RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
17101static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG,
17102                                   TargetLowering::DAGCombinerInfo &DCI,
17103                                   const X86Subtarget *Subtarget) {
17104  DebugLoc DL = N->getDebugLoc();
17105  X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(0));
17106  SDValue EFLAGS = N->getOperand(1);
17107
17108  if (CC == X86::COND_A) {
17109    // Try to convert COND_A into COND_B in an attempt to facilitate
17110    // materializing "setb reg".
17111    //
17112    // Do not flip "e > c", where "c" is a constant, because Cmp instruction
17113    // cannot take an immediate as its first operand.
17114    //
17115    if (EFLAGS.getOpcode() == X86ISD::SUB && EFLAGS.hasOneUse() &&
17116        EFLAGS.getValueType().isInteger() &&
17117        !isa<ConstantSDNode>(EFLAGS.getOperand(1))) {
17118      SDValue NewSub = DAG.getNode(X86ISD::SUB, EFLAGS.getDebugLoc(),
17119                                   EFLAGS.getNode()->getVTList(),
17120                                   EFLAGS.getOperand(1), EFLAGS.getOperand(0));
17121      SDValue NewEFLAGS = SDValue(NewSub.getNode(), EFLAGS.getResNo());
17122      return MaterializeSETB(DL, NewEFLAGS, DAG);
17123    }
17124  }
17125
17126  // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
17127  // a zext and produces an all-ones bit which is more useful than 0/1 in some
17128  // cases.
17129  if (CC == X86::COND_B)
17130    return MaterializeSETB(DL, EFLAGS, DAG);
17131
17132  SDValue Flags;
17133
17134  Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
17135  if (Flags.getNode()) {
17136    SDValue Cond = DAG.getConstant(CC, MVT::i8);
17137    return DAG.getNode(X86ISD::SETCC, DL, N->getVTList(), Cond, Flags);
17138  }
17139
17140  return SDValue();
17141}
17142
17143// Optimize branch condition evaluation.
17144//
17145static SDValue PerformBrCondCombine(SDNode *N, SelectionDAG &DAG,
17146                                    TargetLowering::DAGCombinerInfo &DCI,
17147                                    const X86Subtarget *Subtarget) {
17148  DebugLoc DL = N->getDebugLoc();
17149  SDValue Chain = N->getOperand(0);
17150  SDValue Dest = N->getOperand(1);
17151  SDValue EFLAGS = N->getOperand(3);
17152  X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(2));
17153
17154  SDValue Flags;
17155
17156  Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
17157  if (Flags.getNode()) {
17158    SDValue Cond = DAG.getConstant(CC, MVT::i8);
17159    return DAG.getNode(X86ISD::BRCOND, DL, N->getVTList(), Chain, Dest, Cond,
17160                       Flags);
17161  }
17162
17163  return SDValue();
17164}
17165
17166static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
17167                                        const X86TargetLowering *XTLI) {
17168  SDValue Op0 = N->getOperand(0);
17169  EVT InVT = Op0->getValueType(0);
17170
17171  // SINT_TO_FP(v4i8) -> SINT_TO_FP(SEXT(v4i8 to v4i32))
17172  if (InVT == MVT::v8i8 || InVT == MVT::v4i8) {
17173    DebugLoc dl = N->getDebugLoc();
17174    MVT DstVT = InVT == MVT::v4i8 ? MVT::v4i32 : MVT::v8i32;
17175    SDValue P = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Op0);
17176    return DAG.getNode(ISD::SINT_TO_FP, dl, N->getValueType(0), P);
17177  }
17178
17179  // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
17180  // a 32-bit target where SSE doesn't support i64->FP operations.
17181  if (Op0.getOpcode() == ISD::LOAD) {
17182    LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
17183    EVT VT = Ld->getValueType(0);
17184    if (!Ld->isVolatile() && !N->getValueType(0).isVector() &&
17185        ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
17186        !XTLI->getSubtarget()->is64Bit() &&
17187        !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
17188      SDValue FILDChain = XTLI->BuildFILD(SDValue(N, 0), Ld->getValueType(0),
17189                                          Ld->getChain(), Op0, DAG);
17190      DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
17191      return FILDChain;
17192    }
17193  }
17194  return SDValue();
17195}
17196
17197// Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
17198static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
17199                                 X86TargetLowering::DAGCombinerInfo &DCI) {
17200  // If the LHS and RHS of the ADC node are zero, then it can't overflow and
17201  // the result is either zero or one (depending on the input carry bit).
17202  // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
17203  if (X86::isZeroNode(N->getOperand(0)) &&
17204      X86::isZeroNode(N->getOperand(1)) &&
17205      // We don't have a good way to replace an EFLAGS use, so only do this when
17206      // dead right now.
17207      SDValue(N, 1).use_empty()) {
17208    DebugLoc DL = N->getDebugLoc();
17209    EVT VT = N->getValueType(0);
17210    SDValue CarryOut = DAG.getConstant(0, N->getValueType(1));
17211    SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
17212                               DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
17213                                           DAG.getConstant(X86::COND_B,MVT::i8),
17214                                           N->getOperand(2)),
17215                               DAG.getConstant(1, VT));
17216    return DCI.CombineTo(N, Res1, CarryOut);
17217  }
17218
17219  return SDValue();
17220}
17221
17222// fold (add Y, (sete  X, 0)) -> adc  0, Y
17223//      (add Y, (setne X, 0)) -> sbb -1, Y
17224//      (sub (sete  X, 0), Y) -> sbb  0, Y
17225//      (sub (setne X, 0), Y) -> adc -1, Y
17226static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
17227  DebugLoc DL = N->getDebugLoc();
17228
17229  // Look through ZExts.
17230  SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
17231  if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
17232    return SDValue();
17233
17234  SDValue SetCC = Ext.getOperand(0);
17235  if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
17236    return SDValue();
17237
17238  X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
17239  if (CC != X86::COND_E && CC != X86::COND_NE)
17240    return SDValue();
17241
17242  SDValue Cmp = SetCC.getOperand(1);
17243  if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
17244      !X86::isZeroNode(Cmp.getOperand(1)) ||
17245      !Cmp.getOperand(0).getValueType().isInteger())
17246    return SDValue();
17247
17248  SDValue CmpOp0 = Cmp.getOperand(0);
17249  SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
17250                               DAG.getConstant(1, CmpOp0.getValueType()));
17251
17252  SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
17253  if (CC == X86::COND_NE)
17254    return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
17255                       DL, OtherVal.getValueType(), OtherVal,
17256                       DAG.getConstant(-1ULL, OtherVal.getValueType()), NewCmp);
17257  return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
17258                     DL, OtherVal.getValueType(), OtherVal,
17259                     DAG.getConstant(0, OtherVal.getValueType()), NewCmp);
17260}
17261
17262/// PerformADDCombine - Do target-specific dag combines on integer adds.
17263static SDValue PerformAddCombine(SDNode *N, SelectionDAG &DAG,
17264                                 const X86Subtarget *Subtarget) {
17265  EVT VT = N->getValueType(0);
17266  SDValue Op0 = N->getOperand(0);
17267  SDValue Op1 = N->getOperand(1);
17268
17269  // Try to synthesize horizontal adds from adds of shuffles.
17270  if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
17271       (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
17272      isHorizontalBinOp(Op0, Op1, true))
17273    return DAG.getNode(X86ISD::HADD, N->getDebugLoc(), VT, Op0, Op1);
17274
17275  return OptimizeConditionalInDecrement(N, DAG);
17276}
17277
17278static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG,
17279                                 const X86Subtarget *Subtarget) {
17280  SDValue Op0 = N->getOperand(0);
17281  SDValue Op1 = N->getOperand(1);
17282
17283  // X86 can't encode an immediate LHS of a sub. See if we can push the
17284  // negation into a preceding instruction.
17285  if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
17286    // If the RHS of the sub is a XOR with one use and a constant, invert the
17287    // immediate. Then add one to the LHS of the sub so we can turn
17288    // X-Y -> X+~Y+1, saving one register.
17289    if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
17290        isa<ConstantSDNode>(Op1.getOperand(1))) {
17291      APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
17292      EVT VT = Op0.getValueType();
17293      SDValue NewXor = DAG.getNode(ISD::XOR, Op1.getDebugLoc(), VT,
17294                                   Op1.getOperand(0),
17295                                   DAG.getConstant(~XorC, VT));
17296      return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, NewXor,
17297                         DAG.getConstant(C->getAPIntValue()+1, VT));
17298    }
17299  }
17300
17301  // Try to synthesize horizontal adds from adds of shuffles.
17302  EVT VT = N->getValueType(0);
17303  if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
17304       (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
17305      isHorizontalBinOp(Op0, Op1, true))
17306    return DAG.getNode(X86ISD::HSUB, N->getDebugLoc(), VT, Op0, Op1);
17307
17308  return OptimizeConditionalInDecrement(N, DAG);
17309}
17310
17311/// performVZEXTCombine - Performs build vector combines
17312static SDValue performVZEXTCombine(SDNode *N, SelectionDAG &DAG,
17313                                        TargetLowering::DAGCombinerInfo &DCI,
17314                                        const X86Subtarget *Subtarget) {
17315  // (vzext (bitcast (vzext (x)) -> (vzext x)
17316  SDValue In = N->getOperand(0);
17317  while (In.getOpcode() == ISD::BITCAST)
17318    In = In.getOperand(0);
17319
17320  if (In.getOpcode() != X86ISD::VZEXT)
17321    return SDValue();
17322
17323  return DAG.getNode(X86ISD::VZEXT, N->getDebugLoc(), N->getValueType(0), In.getOperand(0));
17324}
17325
17326SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
17327                                             DAGCombinerInfo &DCI) const {
17328  SelectionDAG &DAG = DCI.DAG;
17329  switch (N->getOpcode()) {
17330  default: break;
17331  case ISD::EXTRACT_VECTOR_ELT:
17332    return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, DCI);
17333  case ISD::VSELECT:
17334  case ISD::SELECT:         return PerformSELECTCombine(N, DAG, DCI, Subtarget);
17335  case X86ISD::CMOV:        return PerformCMOVCombine(N, DAG, DCI, Subtarget);
17336  case ISD::ADD:            return PerformAddCombine(N, DAG, Subtarget);
17337  case ISD::SUB:            return PerformSubCombine(N, DAG, Subtarget);
17338  case X86ISD::ADC:         return PerformADCCombine(N, DAG, DCI);
17339  case ISD::MUL:            return PerformMulCombine(N, DAG, DCI);
17340  case ISD::SHL:
17341  case ISD::SRA:
17342  case ISD::SRL:            return PerformShiftCombine(N, DAG, DCI, Subtarget);
17343  case ISD::AND:            return PerformAndCombine(N, DAG, DCI, Subtarget);
17344  case ISD::OR:             return PerformOrCombine(N, DAG, DCI, Subtarget);
17345  case ISD::XOR:            return PerformXorCombine(N, DAG, DCI, Subtarget);
17346  case ISD::LOAD:           return PerformLOADCombine(N, DAG, DCI, Subtarget);
17347  case ISD::STORE:          return PerformSTORECombine(N, DAG, Subtarget);
17348  case ISD::SINT_TO_FP:     return PerformSINT_TO_FPCombine(N, DAG, this);
17349  case ISD::FADD:           return PerformFADDCombine(N, DAG, Subtarget);
17350  case ISD::FSUB:           return PerformFSUBCombine(N, DAG, Subtarget);
17351  case X86ISD::FXOR:
17352  case X86ISD::FOR:         return PerformFORCombine(N, DAG);
17353  case X86ISD::FMIN:
17354  case X86ISD::FMAX:        return PerformFMinFMaxCombine(N, DAG);
17355  case X86ISD::FAND:        return PerformFANDCombine(N, DAG);
17356  case X86ISD::BT:          return PerformBTCombine(N, DAG, DCI);
17357  case X86ISD::VZEXT_MOVL:  return PerformVZEXT_MOVLCombine(N, DAG);
17358  case ISD::ANY_EXTEND:
17359  case ISD::ZERO_EXTEND:    return PerformZExtCombine(N, DAG, DCI, Subtarget);
17360  case ISD::SIGN_EXTEND:    return PerformSExtCombine(N, DAG, DCI, Subtarget);
17361  case ISD::TRUNCATE:       return PerformTruncateCombine(N, DAG,DCI,Subtarget);
17362  case ISD::SETCC:          return PerformISDSETCCCombine(N, DAG);
17363  case X86ISD::SETCC:       return PerformSETCCCombine(N, DAG, DCI, Subtarget);
17364  case X86ISD::BRCOND:      return PerformBrCondCombine(N, DAG, DCI, Subtarget);
17365  case X86ISD::VZEXT:       return performVZEXTCombine(N, DAG, DCI, Subtarget);
17366  case X86ISD::SHUFP:       // Handle all target specific shuffles
17367  case X86ISD::PALIGN:
17368  case X86ISD::UNPCKH:
17369  case X86ISD::UNPCKL:
17370  case X86ISD::MOVHLPS:
17371  case X86ISD::MOVLHPS:
17372  case X86ISD::PSHUFD:
17373  case X86ISD::PSHUFHW:
17374  case X86ISD::PSHUFLW:
17375  case X86ISD::MOVSS:
17376  case X86ISD::MOVSD:
17377  case X86ISD::VPERMILP:
17378  case X86ISD::VPERM2X128:
17379  case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
17380  case ISD::FMA:            return PerformFMACombine(N, DAG, Subtarget);
17381  }
17382
17383  return SDValue();
17384}
17385
17386/// isTypeDesirableForOp - Return true if the target has native support for
17387/// the specified value type and it is 'desirable' to use the type for the
17388/// given node type. e.g. On x86 i16 is legal, but undesirable since i16
17389/// instruction encodings are longer and some i16 instructions are slow.
17390bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
17391  if (!isTypeLegal(VT))
17392    return false;
17393  if (VT != MVT::i16)
17394    return true;
17395
17396  switch (Opc) {
17397  default:
17398    return true;
17399  case ISD::LOAD:
17400  case ISD::SIGN_EXTEND:
17401  case ISD::ZERO_EXTEND:
17402  case ISD::ANY_EXTEND:
17403  case ISD::SHL:
17404  case ISD::SRL:
17405  case ISD::SUB:
17406  case ISD::ADD:
17407  case ISD::MUL:
17408  case ISD::AND:
17409  case ISD::OR:
17410  case ISD::XOR:
17411    return false;
17412  }
17413}
17414
17415/// IsDesirableToPromoteOp - This method query the target whether it is
17416/// beneficial for dag combiner to promote the specified node. If true, it
17417/// should return the desired promotion type by reference.
17418bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
17419  EVT VT = Op.getValueType();
17420  if (VT != MVT::i16)
17421    return false;
17422
17423  bool Promote = false;
17424  bool Commute = false;
17425  switch (Op.getOpcode()) {
17426  default: break;
17427  case ISD::LOAD: {
17428    LoadSDNode *LD = cast<LoadSDNode>(Op);
17429    // If the non-extending load has a single use and it's not live out, then it
17430    // might be folded.
17431    if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
17432                                                     Op.hasOneUse()*/) {
17433      for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
17434             UE = Op.getNode()->use_end(); UI != UE; ++UI) {
17435        // The only case where we'd want to promote LOAD (rather then it being
17436        // promoted as an operand is when it's only use is liveout.
17437        if (UI->getOpcode() != ISD::CopyToReg)
17438          return false;
17439      }
17440    }
17441    Promote = true;
17442    break;
17443  }
17444  case ISD::SIGN_EXTEND:
17445  case ISD::ZERO_EXTEND:
17446  case ISD::ANY_EXTEND:
17447    Promote = true;
17448    break;
17449  case ISD::SHL:
17450  case ISD::SRL: {
17451    SDValue N0 = Op.getOperand(0);
17452    // Look out for (store (shl (load), x)).
17453    if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
17454      return false;
17455    Promote = true;
17456    break;
17457  }
17458  case ISD::ADD:
17459  case ISD::MUL:
17460  case ISD::AND:
17461  case ISD::OR:
17462  case ISD::XOR:
17463    Commute = true;
17464    // fallthrough
17465  case ISD::SUB: {
17466    SDValue N0 = Op.getOperand(0);
17467    SDValue N1 = Op.getOperand(1);
17468    if (!Commute && MayFoldLoad(N1))
17469      return false;
17470    // Avoid disabling potential load folding opportunities.
17471    if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
17472      return false;
17473    if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
17474      return false;
17475    Promote = true;
17476  }
17477  }
17478
17479  PVT = MVT::i32;
17480  return Promote;
17481}
17482
17483//===----------------------------------------------------------------------===//
17484//                           X86 Inline Assembly Support
17485//===----------------------------------------------------------------------===//
17486
17487namespace {
17488  // Helper to match a string separated by whitespace.
17489  bool matchAsmImpl(StringRef s, ArrayRef<const StringRef *> args) {
17490    s = s.substr(s.find_first_not_of(" \t")); // Skip leading whitespace.
17491
17492    for (unsigned i = 0, e = args.size(); i != e; ++i) {
17493      StringRef piece(*args[i]);
17494      if (!s.startswith(piece)) // Check if the piece matches.
17495        return false;
17496
17497      s = s.substr(piece.size());
17498      StringRef::size_type pos = s.find_first_not_of(" \t");
17499      if (pos == 0) // We matched a prefix.
17500        return false;
17501
17502      s = s.substr(pos);
17503    }
17504
17505    return s.empty();
17506  }
17507  const VariadicFunction1<bool, StringRef, StringRef, matchAsmImpl> matchAsm={};
17508}
17509
17510bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
17511  InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
17512
17513  std::string AsmStr = IA->getAsmString();
17514
17515  IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
17516  if (!Ty || Ty->getBitWidth() % 16 != 0)
17517    return false;
17518
17519  // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
17520  SmallVector<StringRef, 4> AsmPieces;
17521  SplitString(AsmStr, AsmPieces, ";\n");
17522
17523  switch (AsmPieces.size()) {
17524  default: return false;
17525  case 1:
17526    // FIXME: this should verify that we are targeting a 486 or better.  If not,
17527    // we will turn this bswap into something that will be lowered to logical
17528    // ops instead of emitting the bswap asm.  For now, we don't support 486 or
17529    // lower so don't worry about this.
17530    // bswap $0
17531    if (matchAsm(AsmPieces[0], "bswap", "$0") ||
17532        matchAsm(AsmPieces[0], "bswapl", "$0") ||
17533        matchAsm(AsmPieces[0], "bswapq", "$0") ||
17534        matchAsm(AsmPieces[0], "bswap", "${0:q}") ||
17535        matchAsm(AsmPieces[0], "bswapl", "${0:q}") ||
17536        matchAsm(AsmPieces[0], "bswapq", "${0:q}")) {
17537      // No need to check constraints, nothing other than the equivalent of
17538      // "=r,0" would be valid here.
17539      return IntrinsicLowering::LowerToByteSwap(CI);
17540    }
17541
17542    // rorw $$8, ${0:w}  -->  llvm.bswap.i16
17543    if (CI->getType()->isIntegerTy(16) &&
17544        IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
17545        (matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") ||
17546         matchAsm(AsmPieces[0], "rolw", "$$8,", "${0:w}"))) {
17547      AsmPieces.clear();
17548      const std::string &ConstraintsStr = IA->getConstraintString();
17549      SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
17550      std::sort(AsmPieces.begin(), AsmPieces.end());
17551      if (AsmPieces.size() == 4 &&
17552          AsmPieces[0] == "~{cc}" &&
17553          AsmPieces[1] == "~{dirflag}" &&
17554          AsmPieces[2] == "~{flags}" &&
17555          AsmPieces[3] == "~{fpsr}")
17556      return IntrinsicLowering::LowerToByteSwap(CI);
17557    }
17558    break;
17559  case 3:
17560    if (CI->getType()->isIntegerTy(32) &&
17561        IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
17562        matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") &&
17563        matchAsm(AsmPieces[1], "rorl", "$$16,", "$0") &&
17564        matchAsm(AsmPieces[2], "rorw", "$$8,", "${0:w}")) {
17565      AsmPieces.clear();
17566      const std::string &ConstraintsStr = IA->getConstraintString();
17567      SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
17568      std::sort(AsmPieces.begin(), AsmPieces.end());
17569      if (AsmPieces.size() == 4 &&
17570          AsmPieces[0] == "~{cc}" &&
17571          AsmPieces[1] == "~{dirflag}" &&
17572          AsmPieces[2] == "~{flags}" &&
17573          AsmPieces[3] == "~{fpsr}")
17574        return IntrinsicLowering::LowerToByteSwap(CI);
17575    }
17576
17577    if (CI->getType()->isIntegerTy(64)) {
17578      InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
17579      if (Constraints.size() >= 2 &&
17580          Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
17581          Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
17582        // bswap %eax / bswap %edx / xchgl %eax, %edx  -> llvm.bswap.i64
17583        if (matchAsm(AsmPieces[0], "bswap", "%eax") &&
17584            matchAsm(AsmPieces[1], "bswap", "%edx") &&
17585            matchAsm(AsmPieces[2], "xchgl", "%eax,", "%edx"))
17586          return IntrinsicLowering::LowerToByteSwap(CI);
17587      }
17588    }
17589    break;
17590  }
17591  return false;
17592}
17593
17594/// getConstraintType - Given a constraint letter, return the type of
17595/// constraint it is for this target.
17596X86TargetLowering::ConstraintType
17597X86TargetLowering::getConstraintType(const std::string &Constraint) const {
17598  if (Constraint.size() == 1) {
17599    switch (Constraint[0]) {
17600    case 'R':
17601    case 'q':
17602    case 'Q':
17603    case 'f':
17604    case 't':
17605    case 'u':
17606    case 'y':
17607    case 'x':
17608    case 'Y':
17609    case 'l':
17610      return C_RegisterClass;
17611    case 'a':
17612    case 'b':
17613    case 'c':
17614    case 'd':
17615    case 'S':
17616    case 'D':
17617    case 'A':
17618      return C_Register;
17619    case 'I':
17620    case 'J':
17621    case 'K':
17622    case 'L':
17623    case 'M':
17624    case 'N':
17625    case 'G':
17626    case 'C':
17627    case 'e':
17628    case 'Z':
17629      return C_Other;
17630    default:
17631      break;
17632    }
17633  }
17634  return TargetLowering::getConstraintType(Constraint);
17635}
17636
17637/// Examine constraint type and operand type and determine a weight value.
17638/// This object must already have been set up with the operand type
17639/// and the current alternative constraint selected.
17640TargetLowering::ConstraintWeight
17641  X86TargetLowering::getSingleConstraintMatchWeight(
17642    AsmOperandInfo &info, const char *constraint) const {
17643  ConstraintWeight weight = CW_Invalid;
17644  Value *CallOperandVal = info.CallOperandVal;
17645    // If we don't have a value, we can't do a match,
17646    // but allow it at the lowest weight.
17647  if (CallOperandVal == NULL)
17648    return CW_Default;
17649  Type *type = CallOperandVal->getType();
17650  // Look at the constraint type.
17651  switch (*constraint) {
17652  default:
17653    weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
17654  case 'R':
17655  case 'q':
17656  case 'Q':
17657  case 'a':
17658  case 'b':
17659  case 'c':
17660  case 'd':
17661  case 'S':
17662  case 'D':
17663  case 'A':
17664    if (CallOperandVal->getType()->isIntegerTy())
17665      weight = CW_SpecificReg;
17666    break;
17667  case 'f':
17668  case 't':
17669  case 'u':
17670    if (type->isFloatingPointTy())
17671      weight = CW_SpecificReg;
17672    break;
17673  case 'y':
17674    if (type->isX86_MMXTy() && Subtarget->hasMMX())
17675      weight = CW_SpecificReg;
17676    break;
17677  case 'x':
17678  case 'Y':
17679    if (((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasSSE1()) ||
17680        ((type->getPrimitiveSizeInBits() == 256) && Subtarget->hasFp256()))
17681      weight = CW_Register;
17682    break;
17683  case 'I':
17684    if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
17685      if (C->getZExtValue() <= 31)
17686        weight = CW_Constant;
17687    }
17688    break;
17689  case 'J':
17690    if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
17691      if (C->getZExtValue() <= 63)
17692        weight = CW_Constant;
17693    }
17694    break;
17695  case 'K':
17696    if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
17697      if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
17698        weight = CW_Constant;
17699    }
17700    break;
17701  case 'L':
17702    if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
17703      if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
17704        weight = CW_Constant;
17705    }
17706    break;
17707  case 'M':
17708    if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
17709      if (C->getZExtValue() <= 3)
17710        weight = CW_Constant;
17711    }
17712    break;
17713  case 'N':
17714    if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
17715      if (C->getZExtValue() <= 0xff)
17716        weight = CW_Constant;
17717    }
17718    break;
17719  case 'G':
17720  case 'C':
17721    if (dyn_cast<ConstantFP>(CallOperandVal)) {
17722      weight = CW_Constant;
17723    }
17724    break;
17725  case 'e':
17726    if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
17727      if ((C->getSExtValue() >= -0x80000000LL) &&
17728          (C->getSExtValue() <= 0x7fffffffLL))
17729        weight = CW_Constant;
17730    }
17731    break;
17732  case 'Z':
17733    if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
17734      if (C->getZExtValue() <= 0xffffffff)
17735        weight = CW_Constant;
17736    }
17737    break;
17738  }
17739  return weight;
17740}
17741
17742/// LowerXConstraint - try to replace an X constraint, which matches anything,
17743/// with another that has more specific requirements based on the type of the
17744/// corresponding operand.
17745const char *X86TargetLowering::
17746LowerXConstraint(EVT ConstraintVT) const {
17747  // FP X constraints get lowered to SSE1/2 registers if available, otherwise
17748  // 'f' like normal targets.
17749  if (ConstraintVT.isFloatingPoint()) {
17750    if (Subtarget->hasSSE2())
17751      return "Y";
17752    if (Subtarget->hasSSE1())
17753      return "x";
17754  }
17755
17756  return TargetLowering::LowerXConstraint(ConstraintVT);
17757}
17758
17759/// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
17760/// vector.  If it is invalid, don't add anything to Ops.
17761void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
17762                                                     std::string &Constraint,
17763                                                     std::vector<SDValue>&Ops,
17764                                                     SelectionDAG &DAG) const {
17765  SDValue Result(0, 0);
17766
17767  // Only support length 1 constraints for now.
17768  if (Constraint.length() > 1) return;
17769
17770  char ConstraintLetter = Constraint[0];
17771  switch (ConstraintLetter) {
17772  default: break;
17773  case 'I':
17774    if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
17775      if (C->getZExtValue() <= 31) {
17776        Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
17777        break;
17778      }
17779    }
17780    return;
17781  case 'J':
17782    if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
17783      if (C->getZExtValue() <= 63) {
17784        Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
17785        break;
17786      }
17787    }
17788    return;
17789  case 'K':
17790    if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
17791      if (isInt<8>(C->getSExtValue())) {
17792        Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
17793        break;
17794      }
17795    }
17796    return;
17797  case 'N':
17798    if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
17799      if (C->getZExtValue() <= 255) {
17800        Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
17801        break;
17802      }
17803    }
17804    return;
17805  case 'e': {
17806    // 32-bit signed value
17807    if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
17808      if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
17809                                           C->getSExtValue())) {
17810        // Widen to 64 bits here to get it sign extended.
17811        Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
17812        break;
17813      }
17814    // FIXME gcc accepts some relocatable values here too, but only in certain
17815    // memory models; it's complicated.
17816    }
17817    return;
17818  }
17819  case 'Z': {
17820    // 32-bit unsigned value
17821    if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
17822      if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
17823                                           C->getZExtValue())) {
17824        Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
17825        break;
17826      }
17827    }
17828    // FIXME gcc accepts some relocatable values here too, but only in certain
17829    // memory models; it's complicated.
17830    return;
17831  }
17832  case 'i': {
17833    // Literal immediates are always ok.
17834    if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
17835      // Widen to 64 bits here to get it sign extended.
17836      Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
17837      break;
17838    }
17839
17840    // In any sort of PIC mode addresses need to be computed at runtime by
17841    // adding in a register or some sort of table lookup.  These can't
17842    // be used as immediates.
17843    if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
17844      return;
17845
17846    // If we are in non-pic codegen mode, we allow the address of a global (with
17847    // an optional displacement) to be used with 'i'.
17848    GlobalAddressSDNode *GA = 0;
17849    int64_t Offset = 0;
17850
17851    // Match either (GA), (GA+C), (GA+C1+C2), etc.
17852    while (1) {
17853      if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
17854        Offset += GA->getOffset();
17855        break;
17856      } else if (Op.getOpcode() == ISD::ADD) {
17857        if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
17858          Offset += C->getZExtValue();
17859          Op = Op.getOperand(0);
17860          continue;
17861        }
17862      } else if (Op.getOpcode() == ISD::SUB) {
17863        if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
17864          Offset += -C->getZExtValue();
17865          Op = Op.getOperand(0);
17866          continue;
17867        }
17868      }
17869
17870      // Otherwise, this isn't something we can handle, reject it.
17871      return;
17872    }
17873
17874    const GlobalValue *GV = GA->getGlobal();
17875    // If we require an extra load to get this address, as in PIC mode, we
17876    // can't accept it.
17877    if (isGlobalStubReference(Subtarget->ClassifyGlobalReference(GV,
17878                                                        getTargetMachine())))
17879      return;
17880
17881    Result = DAG.getTargetGlobalAddress(GV, Op.getDebugLoc(),
17882                                        GA->getValueType(0), Offset);
17883    break;
17884  }
17885  }
17886
17887  if (Result.getNode()) {
17888    Ops.push_back(Result);
17889    return;
17890  }
17891  return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
17892}
17893
17894std::pair<unsigned, const TargetRegisterClass*>
17895X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
17896                                                EVT VT) const {
17897  // First, see if this is a constraint that directly corresponds to an LLVM
17898  // register class.
17899  if (Constraint.size() == 1) {
17900    // GCC Constraint Letters
17901    switch (Constraint[0]) {
17902    default: break;
17903      // TODO: Slight differences here in allocation order and leaving
17904      // RIP in the class. Do they matter any more here than they do
17905      // in the normal allocation?
17906    case 'q':   // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
17907      if (Subtarget->is64Bit()) {
17908        if (VT == MVT::i32 || VT == MVT::f32)
17909          return std::make_pair(0U, &X86::GR32RegClass);
17910        if (VT == MVT::i16)
17911          return std::make_pair(0U, &X86::GR16RegClass);
17912        if (VT == MVT::i8 || VT == MVT::i1)
17913          return std::make_pair(0U, &X86::GR8RegClass);
17914        if (VT == MVT::i64 || VT == MVT::f64)
17915          return std::make_pair(0U, &X86::GR64RegClass);
17916        break;
17917      }
17918      // 32-bit fallthrough
17919    case 'Q':   // Q_REGS
17920      if (VT == MVT::i32 || VT == MVT::f32)
17921        return std::make_pair(0U, &X86::GR32_ABCDRegClass);
17922      if (VT == MVT::i16)
17923        return std::make_pair(0U, &X86::GR16_ABCDRegClass);
17924      if (VT == MVT::i8 || VT == MVT::i1)
17925        return std::make_pair(0U, &X86::GR8_ABCD_LRegClass);
17926      if (VT == MVT::i64)
17927        return std::make_pair(0U, &X86::GR64_ABCDRegClass);
17928      break;
17929    case 'r':   // GENERAL_REGS
17930    case 'l':   // INDEX_REGS
17931      if (VT == MVT::i8 || VT == MVT::i1)
17932        return std::make_pair(0U, &X86::GR8RegClass);
17933      if (VT == MVT::i16)
17934        return std::make_pair(0U, &X86::GR16RegClass);
17935      if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
17936        return std::make_pair(0U, &X86::GR32RegClass);
17937      return std::make_pair(0U, &X86::GR64RegClass);
17938    case 'R':   // LEGACY_REGS
17939      if (VT == MVT::i8 || VT == MVT::i1)
17940        return std::make_pair(0U, &X86::GR8_NOREXRegClass);
17941      if (VT == MVT::i16)
17942        return std::make_pair(0U, &X86::GR16_NOREXRegClass);
17943      if (VT == MVT::i32 || !Subtarget->is64Bit())
17944        return std::make_pair(0U, &X86::GR32_NOREXRegClass);
17945      return std::make_pair(0U, &X86::GR64_NOREXRegClass);
17946    case 'f':  // FP Stack registers.
17947      // If SSE is enabled for this VT, use f80 to ensure the isel moves the
17948      // value to the correct fpstack register class.
17949      if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
17950        return std::make_pair(0U, &X86::RFP32RegClass);
17951      if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
17952        return std::make_pair(0U, &X86::RFP64RegClass);
17953      return std::make_pair(0U, &X86::RFP80RegClass);
17954    case 'y':   // MMX_REGS if MMX allowed.
17955      if (!Subtarget->hasMMX()) break;
17956      return std::make_pair(0U, &X86::VR64RegClass);
17957    case 'Y':   // SSE_REGS if SSE2 allowed
17958      if (!Subtarget->hasSSE2()) break;
17959      // FALL THROUGH.
17960    case 'x':   // SSE_REGS if SSE1 allowed or AVX_REGS if AVX allowed
17961      if (!Subtarget->hasSSE1()) break;
17962
17963      switch (VT.getSimpleVT().SimpleTy) {
17964      default: break;
17965      // Scalar SSE types.
17966      case MVT::f32:
17967      case MVT::i32:
17968        return std::make_pair(0U, &X86::FR32RegClass);
17969      case MVT::f64:
17970      case MVT::i64:
17971        return std::make_pair(0U, &X86::FR64RegClass);
17972      // Vector types.
17973      case MVT::v16i8:
17974      case MVT::v8i16:
17975      case MVT::v4i32:
17976      case MVT::v2i64:
17977      case MVT::v4f32:
17978      case MVT::v2f64:
17979        return std::make_pair(0U, &X86::VR128RegClass);
17980      // AVX types.
17981      case MVT::v32i8:
17982      case MVT::v16i16:
17983      case MVT::v8i32:
17984      case MVT::v4i64:
17985      case MVT::v8f32:
17986      case MVT::v4f64:
17987        return std::make_pair(0U, &X86::VR256RegClass);
17988      }
17989      break;
17990    }
17991  }
17992
17993  // Use the default implementation in TargetLowering to convert the register
17994  // constraint into a member of a register class.
17995  std::pair<unsigned, const TargetRegisterClass*> Res;
17996  Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
17997
17998  // Not found as a standard register?
17999  if (Res.second == 0) {
18000    // Map st(0) -> st(7) -> ST0
18001    if (Constraint.size() == 7 && Constraint[0] == '{' &&
18002        tolower(Constraint[1]) == 's' &&
18003        tolower(Constraint[2]) == 't' &&
18004        Constraint[3] == '(' &&
18005        (Constraint[4] >= '0' && Constraint[4] <= '7') &&
18006        Constraint[5] == ')' &&
18007        Constraint[6] == '}') {
18008
18009      Res.first = X86::ST0+Constraint[4]-'0';
18010      Res.second = &X86::RFP80RegClass;
18011      return Res;
18012    }
18013
18014    // GCC allows "st(0)" to be called just plain "st".
18015    if (StringRef("{st}").equals_lower(Constraint)) {
18016      Res.first = X86::ST0;
18017      Res.second = &X86::RFP80RegClass;
18018      return Res;
18019    }
18020
18021    // flags -> EFLAGS
18022    if (StringRef("{flags}").equals_lower(Constraint)) {
18023      Res.first = X86::EFLAGS;
18024      Res.second = &X86::CCRRegClass;
18025      return Res;
18026    }
18027
18028    // 'A' means EAX + EDX.
18029    if (Constraint == "A") {
18030      Res.first = X86::EAX;
18031      Res.second = &X86::GR32_ADRegClass;
18032      return Res;
18033    }
18034    return Res;
18035  }
18036
18037  // Otherwise, check to see if this is a register class of the wrong value
18038  // type.  For example, we want to map "{ax},i32" -> {eax}, we don't want it to
18039  // turn into {ax},{dx}.
18040  if (Res.second->hasType(VT))
18041    return Res;   // Correct type already, nothing to do.
18042
18043  // All of the single-register GCC register classes map their values onto
18044  // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp".  If we
18045  // really want an 8-bit or 32-bit register, map to the appropriate register
18046  // class and return the appropriate register.
18047  if (Res.second == &X86::GR16RegClass) {
18048    if (VT == MVT::i8) {
18049      unsigned DestReg = 0;
18050      switch (Res.first) {
18051      default: break;
18052      case X86::AX: DestReg = X86::AL; break;
18053      case X86::DX: DestReg = X86::DL; break;
18054      case X86::CX: DestReg = X86::CL; break;
18055      case X86::BX: DestReg = X86::BL; break;
18056      }
18057      if (DestReg) {
18058        Res.first = DestReg;
18059        Res.second = &X86::GR8RegClass;
18060      }
18061    } else if (VT == MVT::i32) {
18062      unsigned DestReg = 0;
18063      switch (Res.first) {
18064      default: break;
18065      case X86::AX: DestReg = X86::EAX; break;
18066      case X86::DX: DestReg = X86::EDX; break;
18067      case X86::CX: DestReg = X86::ECX; break;
18068      case X86::BX: DestReg = X86::EBX; break;
18069      case X86::SI: DestReg = X86::ESI; break;
18070      case X86::DI: DestReg = X86::EDI; break;
18071      case X86::BP: DestReg = X86::EBP; break;
18072      case X86::SP: DestReg = X86::ESP; break;
18073      }
18074      if (DestReg) {
18075        Res.first = DestReg;
18076        Res.second = &X86::GR32RegClass;
18077      }
18078    } else if (VT == MVT::i64) {
18079      unsigned DestReg = 0;
18080      switch (Res.first) {
18081      default: break;
18082      case X86::AX: DestReg = X86::RAX; break;
18083      case X86::DX: DestReg = X86::RDX; break;
18084      case X86::CX: DestReg = X86::RCX; break;
18085      case X86::BX: DestReg = X86::RBX; break;
18086      case X86::SI: DestReg = X86::RSI; break;
18087      case X86::DI: DestReg = X86::RDI; break;
18088      case X86::BP: DestReg = X86::RBP; break;
18089      case X86::SP: DestReg = X86::RSP; break;
18090      }
18091      if (DestReg) {
18092        Res.first = DestReg;
18093        Res.second = &X86::GR64RegClass;
18094      }
18095    }
18096  } else if (Res.second == &X86::FR32RegClass ||
18097             Res.second == &X86::FR64RegClass ||
18098             Res.second == &X86::VR128RegClass) {
18099    // Handle references to XMM physical registers that got mapped into the
18100    // wrong class.  This can happen with constraints like {xmm0} where the
18101    // target independent register mapper will just pick the first match it can
18102    // find, ignoring the required type.
18103
18104    if (VT == MVT::f32 || VT == MVT::i32)
18105      Res.second = &X86::FR32RegClass;
18106    else if (VT == MVT::f64 || VT == MVT::i64)
18107      Res.second = &X86::FR64RegClass;
18108    else if (X86::VR128RegClass.hasType(VT))
18109      Res.second = &X86::VR128RegClass;
18110    else if (X86::VR256RegClass.hasType(VT))
18111      Res.second = &X86::VR256RegClass;
18112  }
18113
18114  return Res;
18115}
18116