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 "X86.h"
17#include "X86InstrBuilder.h"
18#include "X86ISelLowering.h"
19#include "X86TargetMachine.h"
20#include "X86TargetObjectFile.h"
21#include "Utils/X86ShuffleDecode.h"
22#include "llvm/CallingConv.h"
23#include "llvm/Constants.h"
24#include "llvm/DerivedTypes.h"
25#include "llvm/GlobalAlias.h"
26#include "llvm/GlobalVariable.h"
27#include "llvm/Function.h"
28#include "llvm/Instructions.h"
29#include "llvm/Intrinsics.h"
30#include "llvm/LLVMContext.h"
31#include "llvm/CodeGen/IntrinsicLowering.h"
32#include "llvm/CodeGen/MachineFrameInfo.h"
33#include "llvm/CodeGen/MachineFunction.h"
34#include "llvm/CodeGen/MachineInstrBuilder.h"
35#include "llvm/CodeGen/MachineJumpTableInfo.h"
36#include "llvm/CodeGen/MachineModuleInfo.h"
37#include "llvm/CodeGen/MachineRegisterInfo.h"
38#include "llvm/CodeGen/PseudoSourceValue.h"
39#include "llvm/MC/MCAsmInfo.h"
40#include "llvm/MC/MCContext.h"
41#include "llvm/MC/MCExpr.h"
42#include "llvm/MC/MCSymbol.h"
43#include "llvm/ADT/BitVector.h"
44#include "llvm/ADT/SmallSet.h"
45#include "llvm/ADT/Statistic.h"
46#include "llvm/ADT/StringExtras.h"
47#include "llvm/ADT/VectorExtras.h"
48#include "llvm/Support/CallSite.h"
49#include "llvm/Support/Debug.h"
50#include "llvm/Support/Dwarf.h"
51#include "llvm/Support/ErrorHandling.h"
52#include "llvm/Support/MathExtras.h"
53#include "llvm/Support/raw_ostream.h"
54#include "llvm/Target/TargetOptions.h"
55using namespace llvm;
56using namespace dwarf;
57
58STATISTIC(NumTailCalls, "Number of tail calls");
59
60// Forward declarations.
61static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
62                       SDValue V2);
63
64static SDValue Insert128BitVector(SDValue Result,
65                                  SDValue Vec,
66                                  SDValue Idx,
67                                  SelectionDAG &DAG,
68                                  DebugLoc dl);
69
70static SDValue Extract128BitVector(SDValue Vec,
71                                   SDValue Idx,
72                                   SelectionDAG &DAG,
73                                   DebugLoc dl);
74
75/// Generate a DAG to grab 128-bits from a vector > 128 bits.  This
76/// sets things up to match to an AVX VEXTRACTF128 instruction or a
77/// simple subregister reference.  Idx is an index in the 128 bits we
78/// want.  It need not be aligned to a 128-bit bounday.  That makes
79/// lowering EXTRACT_VECTOR_ELT operations easier.
80static SDValue Extract128BitVector(SDValue Vec,
81                                   SDValue Idx,
82                                   SelectionDAG &DAG,
83                                   DebugLoc dl) {
84  EVT VT = Vec.getValueType();
85  assert(VT.getSizeInBits() == 256 && "Unexpected vector size!");
86  EVT ElVT = VT.getVectorElementType();
87  int Factor = VT.getSizeInBits()/128;
88  EVT ResultVT = EVT::getVectorVT(*DAG.getContext(), ElVT,
89                                  VT.getVectorNumElements()/Factor);
90
91  // Extract from UNDEF is UNDEF.
92  if (Vec.getOpcode() == ISD::UNDEF)
93    return DAG.getNode(ISD::UNDEF, dl, ResultVT);
94
95  if (isa<ConstantSDNode>(Idx)) {
96    unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
97
98    // Extract the relevant 128 bits.  Generate an EXTRACT_SUBVECTOR
99    // we can match to VEXTRACTF128.
100    unsigned ElemsPerChunk = 128 / ElVT.getSizeInBits();
101
102    // This is the index of the first element of the 128-bit chunk
103    // we want.
104    unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits()) / 128)
105                                 * ElemsPerChunk);
106
107    SDValue VecIdx = DAG.getConstant(NormalizedIdxVal, MVT::i32);
108    SDValue Result = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, ResultVT, Vec,
109                                 VecIdx);
110
111    return Result;
112  }
113
114  return SDValue();
115}
116
117/// Generate a DAG to put 128-bits into a vector > 128 bits.  This
118/// sets things up to match to an AVX VINSERTF128 instruction or a
119/// simple superregister reference.  Idx is an index in the 128 bits
120/// we want.  It need not be aligned to a 128-bit bounday.  That makes
121/// lowering INSERT_VECTOR_ELT operations easier.
122static SDValue Insert128BitVector(SDValue Result,
123                                  SDValue Vec,
124                                  SDValue Idx,
125                                  SelectionDAG &DAG,
126                                  DebugLoc dl) {
127  if (isa<ConstantSDNode>(Idx)) {
128    EVT VT = Vec.getValueType();
129    assert(VT.getSizeInBits() == 128 && "Unexpected vector size!");
130
131    EVT ElVT = VT.getVectorElementType();
132    unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
133    EVT ResultVT = Result.getValueType();
134
135    // Insert the relevant 128 bits.
136    unsigned ElemsPerChunk = 128/ElVT.getSizeInBits();
137
138    // This is the index of the first element of the 128-bit chunk
139    // we want.
140    unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits())/128)
141                                 * ElemsPerChunk);
142
143    SDValue VecIdx = DAG.getConstant(NormalizedIdxVal, MVT::i32);
144    Result = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Result, Vec,
145                         VecIdx);
146    return Result;
147  }
148
149  return SDValue();
150}
151
152static TargetLoweringObjectFile *createTLOF(X86TargetMachine &TM) {
153  const X86Subtarget *Subtarget = &TM.getSubtarget<X86Subtarget>();
154  bool is64Bit = Subtarget->is64Bit();
155
156  if (Subtarget->isTargetEnvMacho()) {
157    if (is64Bit)
158      return new X8664_MachoTargetObjectFile();
159    return new TargetLoweringObjectFileMachO();
160  }
161
162  if (Subtarget->isTargetELF())
163    return new TargetLoweringObjectFileELF();
164  if (Subtarget->isTargetCOFF() && !Subtarget->isTargetEnvMacho())
165    return new TargetLoweringObjectFileCOFF();
166  llvm_unreachable("unknown subtarget type");
167}
168
169X86TargetLowering::X86TargetLowering(X86TargetMachine &TM)
170  : TargetLowering(TM, createTLOF(TM)) {
171  Subtarget = &TM.getSubtarget<X86Subtarget>();
172  X86ScalarSSEf64 = Subtarget->hasXMMInt();
173  X86ScalarSSEf32 = Subtarget->hasXMM();
174  X86StackPtr = Subtarget->is64Bit() ? X86::RSP : X86::ESP;
175
176  RegInfo = TM.getRegisterInfo();
177  TD = getTargetData();
178
179  // Set up the TargetLowering object.
180  static MVT IntVTs[] = { MVT::i8, MVT::i16, MVT::i32, MVT::i64 };
181
182  // X86 is weird, it always uses i8 for shift amounts and setcc results.
183  setBooleanContents(ZeroOrOneBooleanContent);
184  // X86-SSE is even stranger. It uses -1 or 0 for vector masks.
185  setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
186
187  // For 64-bit since we have so many registers use the ILP scheduler, for
188  // 32-bit code use the register pressure specific scheduling.
189  if (Subtarget->is64Bit())
190    setSchedulingPreference(Sched::ILP);
191  else
192    setSchedulingPreference(Sched::RegPressure);
193  setStackPointerRegisterToSaveRestore(X86StackPtr);
194
195  if (Subtarget->isTargetWindows() && !Subtarget->isTargetCygMing()) {
196    // Setup Windows compiler runtime calls.
197    setLibcallName(RTLIB::SDIV_I64, "_alldiv");
198    setLibcallName(RTLIB::UDIV_I64, "_aulldiv");
199    setLibcallName(RTLIB::SREM_I64, "_allrem");
200    setLibcallName(RTLIB::UREM_I64, "_aullrem");
201    setLibcallName(RTLIB::MUL_I64, "_allmul");
202    setLibcallName(RTLIB::FPTOUINT_F64_I64, "_ftol2");
203    setLibcallName(RTLIB::FPTOUINT_F32_I64, "_ftol2");
204    setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::X86_StdCall);
205    setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::X86_StdCall);
206    setLibcallCallingConv(RTLIB::SREM_I64, CallingConv::X86_StdCall);
207    setLibcallCallingConv(RTLIB::UREM_I64, CallingConv::X86_StdCall);
208    setLibcallCallingConv(RTLIB::MUL_I64, CallingConv::X86_StdCall);
209    setLibcallCallingConv(RTLIB::FPTOUINT_F64_I64, CallingConv::C);
210    setLibcallCallingConv(RTLIB::FPTOUINT_F32_I64, CallingConv::C);
211  }
212
213  if (Subtarget->isTargetDarwin()) {
214    // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
215    setUseUnderscoreSetJmp(false);
216    setUseUnderscoreLongJmp(false);
217  } else if (Subtarget->isTargetMingw()) {
218    // MS runtime is weird: it exports _setjmp, but longjmp!
219    setUseUnderscoreSetJmp(true);
220    setUseUnderscoreLongJmp(false);
221  } else {
222    setUseUnderscoreSetJmp(true);
223    setUseUnderscoreLongJmp(true);
224  }
225
226  // Set up the register classes.
227  addRegisterClass(MVT::i8, X86::GR8RegisterClass);
228  addRegisterClass(MVT::i16, X86::GR16RegisterClass);
229  addRegisterClass(MVT::i32, X86::GR32RegisterClass);
230  if (Subtarget->is64Bit())
231    addRegisterClass(MVT::i64, X86::GR64RegisterClass);
232
233  setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
234
235  // We don't accept any truncstore of integer registers.
236  setTruncStoreAction(MVT::i64, MVT::i32, Expand);
237  setTruncStoreAction(MVT::i64, MVT::i16, Expand);
238  setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
239  setTruncStoreAction(MVT::i32, MVT::i16, Expand);
240  setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
241  setTruncStoreAction(MVT::i16, MVT::i8,  Expand);
242
243  // SETOEQ and SETUNE require checking two conditions.
244  setCondCodeAction(ISD::SETOEQ, MVT::f32, Expand);
245  setCondCodeAction(ISD::SETOEQ, MVT::f64, Expand);
246  setCondCodeAction(ISD::SETOEQ, MVT::f80, Expand);
247  setCondCodeAction(ISD::SETUNE, MVT::f32, Expand);
248  setCondCodeAction(ISD::SETUNE, MVT::f64, Expand);
249  setCondCodeAction(ISD::SETUNE, MVT::f80, Expand);
250
251  // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
252  // operation.
253  setOperationAction(ISD::UINT_TO_FP       , MVT::i1   , Promote);
254  setOperationAction(ISD::UINT_TO_FP       , MVT::i8   , Promote);
255  setOperationAction(ISD::UINT_TO_FP       , MVT::i16  , Promote);
256
257  if (Subtarget->is64Bit()) {
258    setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Promote);
259    setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Expand);
260  } else if (!UseSoftFloat) {
261    // We have an algorithm for SSE2->double, and we turn this into a
262    // 64-bit FILD followed by conditional FADD for other targets.
263    setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Custom);
264    // We have an algorithm for SSE2, and we turn this into a 64-bit
265    // FILD for other targets.
266    setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Custom);
267  }
268
269  // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
270  // this operation.
271  setOperationAction(ISD::SINT_TO_FP       , MVT::i1   , Promote);
272  setOperationAction(ISD::SINT_TO_FP       , MVT::i8   , Promote);
273
274  if (!UseSoftFloat) {
275    // SSE has no i16 to fp conversion, only i32
276    if (X86ScalarSSEf32) {
277      setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
278      // f32 and f64 cases are Legal, f80 case is not
279      setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
280    } else {
281      setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Custom);
282      setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
283    }
284  } else {
285    setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
286    setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Promote);
287  }
288
289  // In 32-bit mode these are custom lowered.  In 64-bit mode F32 and F64
290  // are Legal, f80 is custom lowered.
291  setOperationAction(ISD::FP_TO_SINT     , MVT::i64  , Custom);
292  setOperationAction(ISD::SINT_TO_FP     , MVT::i64  , Custom);
293
294  // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
295  // this operation.
296  setOperationAction(ISD::FP_TO_SINT       , MVT::i1   , Promote);
297  setOperationAction(ISD::FP_TO_SINT       , MVT::i8   , Promote);
298
299  if (X86ScalarSSEf32) {
300    setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Promote);
301    // f32 and f64 cases are Legal, f80 case is not
302    setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
303  } else {
304    setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Custom);
305    setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
306  }
307
308  // Handle FP_TO_UINT by promoting the destination to a larger signed
309  // conversion.
310  setOperationAction(ISD::FP_TO_UINT       , MVT::i1   , Promote);
311  setOperationAction(ISD::FP_TO_UINT       , MVT::i8   , Promote);
312  setOperationAction(ISD::FP_TO_UINT       , MVT::i16  , Promote);
313
314  if (Subtarget->is64Bit()) {
315    setOperationAction(ISD::FP_TO_UINT     , MVT::i64  , Expand);
316    setOperationAction(ISD::FP_TO_UINT     , MVT::i32  , Promote);
317  } else if (!UseSoftFloat) {
318    // Since AVX is a superset of SSE3, only check for SSE here.
319    if (Subtarget->hasSSE1() && !Subtarget->hasSSE3())
320      // Expand FP_TO_UINT into a select.
321      // FIXME: We would like to use a Custom expander here eventually to do
322      // the optimal thing for SSE vs. the default expansion in the legalizer.
323      setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Expand);
324    else
325      // With SSE3 we can use fisttpll to convert to a signed i64; without
326      // SSE, we're stuck with a fistpll.
327      setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Custom);
328  }
329
330  // TODO: when we have SSE, these could be more efficient, by using movd/movq.
331  if (!X86ScalarSSEf64) {
332    setOperationAction(ISD::BITCAST        , MVT::f32  , Expand);
333    setOperationAction(ISD::BITCAST        , MVT::i32  , Expand);
334    if (Subtarget->is64Bit()) {
335      setOperationAction(ISD::BITCAST      , MVT::f64  , Expand);
336      // Without SSE, i64->f64 goes through memory.
337      setOperationAction(ISD::BITCAST      , MVT::i64  , Expand);
338    }
339  }
340
341  // Scalar integer divide and remainder are lowered to use operations that
342  // produce two results, to match the available instructions. This exposes
343  // the two-result form to trivial CSE, which is able to combine x/y and x%y
344  // into a single instruction.
345  //
346  // Scalar integer multiply-high is also lowered to use two-result
347  // operations, to match the available instructions. However, plain multiply
348  // (low) operations are left as Legal, as there are single-result
349  // instructions for this in x86. Using the two-result multiply instructions
350  // when both high and low results are needed must be arranged by dagcombine.
351  for (unsigned i = 0, e = 4; i != e; ++i) {
352    MVT VT = IntVTs[i];
353    setOperationAction(ISD::MULHS, VT, Expand);
354    setOperationAction(ISD::MULHU, VT, Expand);
355    setOperationAction(ISD::SDIV, VT, Expand);
356    setOperationAction(ISD::UDIV, VT, Expand);
357    setOperationAction(ISD::SREM, VT, Expand);
358    setOperationAction(ISD::UREM, VT, Expand);
359
360    // Add/Sub overflow ops with MVT::Glues are lowered to EFLAGS dependences.
361    setOperationAction(ISD::ADDC, VT, Custom);
362    setOperationAction(ISD::ADDE, VT, Custom);
363    setOperationAction(ISD::SUBC, VT, Custom);
364    setOperationAction(ISD::SUBE, VT, Custom);
365  }
366
367  setOperationAction(ISD::BR_JT            , MVT::Other, Expand);
368  setOperationAction(ISD::BRCOND           , MVT::Other, Custom);
369  setOperationAction(ISD::BR_CC            , MVT::Other, Expand);
370  setOperationAction(ISD::SELECT_CC        , MVT::Other, Expand);
371  if (Subtarget->is64Bit())
372    setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
373  setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16  , Legal);
374  setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8   , Legal);
375  setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1   , Expand);
376  setOperationAction(ISD::FP_ROUND_INREG   , MVT::f32  , Expand);
377  setOperationAction(ISD::FREM             , MVT::f32  , Expand);
378  setOperationAction(ISD::FREM             , MVT::f64  , Expand);
379  setOperationAction(ISD::FREM             , MVT::f80  , Expand);
380  setOperationAction(ISD::FLT_ROUNDS_      , MVT::i32  , Custom);
381
382  if (Subtarget->hasBMI()) {
383    setOperationAction(ISD::CTTZ           , MVT::i8   , Promote);
384  } else {
385    setOperationAction(ISD::CTTZ           , MVT::i8   , Custom);
386    setOperationAction(ISD::CTTZ           , MVT::i16  , Custom);
387    setOperationAction(ISD::CTTZ           , MVT::i32  , Custom);
388    if (Subtarget->is64Bit())
389      setOperationAction(ISD::CTTZ         , MVT::i64  , Custom);
390  }
391
392  if (Subtarget->hasLZCNT()) {
393    setOperationAction(ISD::CTLZ           , MVT::i8   , Promote);
394  } else {
395    setOperationAction(ISD::CTLZ           , MVT::i8   , Custom);
396    setOperationAction(ISD::CTLZ           , MVT::i16  , Custom);
397    setOperationAction(ISD::CTLZ           , MVT::i32  , Custom);
398    if (Subtarget->is64Bit())
399      setOperationAction(ISD::CTLZ         , MVT::i64  , Custom);
400  }
401
402  if (Subtarget->hasPOPCNT()) {
403    setOperationAction(ISD::CTPOP          , MVT::i8   , Promote);
404  } else {
405    setOperationAction(ISD::CTPOP          , MVT::i8   , Expand);
406    setOperationAction(ISD::CTPOP          , MVT::i16  , Expand);
407    setOperationAction(ISD::CTPOP          , MVT::i32  , Expand);
408    if (Subtarget->is64Bit())
409      setOperationAction(ISD::CTPOP        , MVT::i64  , Expand);
410  }
411
412  setOperationAction(ISD::READCYCLECOUNTER , MVT::i64  , Custom);
413  setOperationAction(ISD::BSWAP            , MVT::i16  , Expand);
414
415  // These should be promoted to a larger select which is supported.
416  setOperationAction(ISD::SELECT          , MVT::i1   , Promote);
417  // X86 wants to expand cmov itself.
418  setOperationAction(ISD::SELECT          , MVT::i8   , Custom);
419  setOperationAction(ISD::SELECT          , MVT::i16  , Custom);
420  setOperationAction(ISD::SELECT          , MVT::i32  , Custom);
421  setOperationAction(ISD::SELECT          , MVT::f32  , Custom);
422  setOperationAction(ISD::SELECT          , MVT::f64  , Custom);
423  setOperationAction(ISD::SELECT          , MVT::f80  , Custom);
424  setOperationAction(ISD::SETCC           , MVT::i8   , Custom);
425  setOperationAction(ISD::SETCC           , MVT::i16  , Custom);
426  setOperationAction(ISD::SETCC           , MVT::i32  , Custom);
427  setOperationAction(ISD::SETCC           , MVT::f32  , Custom);
428  setOperationAction(ISD::SETCC           , MVT::f64  , Custom);
429  setOperationAction(ISD::SETCC           , MVT::f80  , Custom);
430  if (Subtarget->is64Bit()) {
431    setOperationAction(ISD::SELECT        , MVT::i64  , Custom);
432    setOperationAction(ISD::SETCC         , MVT::i64  , Custom);
433  }
434  setOperationAction(ISD::EH_RETURN       , MVT::Other, Custom);
435
436  // Darwin ABI issue.
437  setOperationAction(ISD::ConstantPool    , MVT::i32  , Custom);
438  setOperationAction(ISD::JumpTable       , MVT::i32  , Custom);
439  setOperationAction(ISD::GlobalAddress   , MVT::i32  , Custom);
440  setOperationAction(ISD::GlobalTLSAddress, MVT::i32  , Custom);
441  if (Subtarget->is64Bit())
442    setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
443  setOperationAction(ISD::ExternalSymbol  , MVT::i32  , Custom);
444  setOperationAction(ISD::BlockAddress    , MVT::i32  , Custom);
445  if (Subtarget->is64Bit()) {
446    setOperationAction(ISD::ConstantPool  , MVT::i64  , Custom);
447    setOperationAction(ISD::JumpTable     , MVT::i64  , Custom);
448    setOperationAction(ISD::GlobalAddress , MVT::i64  , Custom);
449    setOperationAction(ISD::ExternalSymbol, MVT::i64  , Custom);
450    setOperationAction(ISD::BlockAddress  , MVT::i64  , Custom);
451  }
452  // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
453  setOperationAction(ISD::SHL_PARTS       , MVT::i32  , Custom);
454  setOperationAction(ISD::SRA_PARTS       , MVT::i32  , Custom);
455  setOperationAction(ISD::SRL_PARTS       , MVT::i32  , Custom);
456  if (Subtarget->is64Bit()) {
457    setOperationAction(ISD::SHL_PARTS     , MVT::i64  , Custom);
458    setOperationAction(ISD::SRA_PARTS     , MVT::i64  , Custom);
459    setOperationAction(ISD::SRL_PARTS     , MVT::i64  , Custom);
460  }
461
462  if (Subtarget->hasXMM())
463    setOperationAction(ISD::PREFETCH      , MVT::Other, Legal);
464
465  setOperationAction(ISD::MEMBARRIER    , MVT::Other, Custom);
466  setOperationAction(ISD::ATOMIC_FENCE  , MVT::Other, Custom);
467
468  // On X86 and X86-64, atomic operations are lowered to locked instructions.
469  // Locked instructions, in turn, have implicit fence semantics (all memory
470  // operations are flushed before issuing the locked instruction, and they
471  // are not buffered), so we can fold away the common pattern of
472  // fence-atomic-fence.
473  setShouldFoldAtomicFences(true);
474
475  // Expand certain atomics
476  for (unsigned i = 0, e = 4; i != e; ++i) {
477    MVT VT = IntVTs[i];
478    setOperationAction(ISD::ATOMIC_CMP_SWAP, VT, Custom);
479    setOperationAction(ISD::ATOMIC_LOAD_SUB, VT, Custom);
480    setOperationAction(ISD::ATOMIC_STORE, VT, Custom);
481  }
482
483  if (!Subtarget->is64Bit()) {
484    setOperationAction(ISD::ATOMIC_LOAD, MVT::i64, Custom);
485    setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i64, Custom);
486    setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
487    setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i64, Custom);
488    setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i64, Custom);
489    setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i64, Custom);
490    setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i64, Custom);
491    setOperationAction(ISD::ATOMIC_SWAP, MVT::i64, Custom);
492  }
493
494  if (Subtarget->hasCmpxchg16b()) {
495    setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i128, Custom);
496  }
497
498  // FIXME - use subtarget debug flags
499  if (!Subtarget->isTargetDarwin() &&
500      !Subtarget->isTargetELF() &&
501      !Subtarget->isTargetCygMing()) {
502    setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
503  }
504
505  setOperationAction(ISD::EXCEPTIONADDR, MVT::i64, Expand);
506  setOperationAction(ISD::EHSELECTION,   MVT::i64, Expand);
507  setOperationAction(ISD::EXCEPTIONADDR, MVT::i32, Expand);
508  setOperationAction(ISD::EHSELECTION,   MVT::i32, Expand);
509  if (Subtarget->is64Bit()) {
510    setExceptionPointerRegister(X86::RAX);
511    setExceptionSelectorRegister(X86::RDX);
512  } else {
513    setExceptionPointerRegister(X86::EAX);
514    setExceptionSelectorRegister(X86::EDX);
515  }
516  setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
517  setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
518
519  setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
520  setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
521
522  setOperationAction(ISD::TRAP, MVT::Other, Legal);
523
524  // VASTART needs to be custom lowered to use the VarArgsFrameIndex
525  setOperationAction(ISD::VASTART           , MVT::Other, Custom);
526  setOperationAction(ISD::VAEND             , MVT::Other, Expand);
527  if (Subtarget->is64Bit()) {
528    setOperationAction(ISD::VAARG           , MVT::Other, Custom);
529    setOperationAction(ISD::VACOPY          , MVT::Other, Custom);
530  } else {
531    setOperationAction(ISD::VAARG           , MVT::Other, Expand);
532    setOperationAction(ISD::VACOPY          , MVT::Other, Expand);
533  }
534
535  setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
536  setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
537
538  if (Subtarget->isTargetCOFF() && !Subtarget->isTargetEnvMacho())
539    setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
540                       MVT::i64 : MVT::i32, Custom);
541  else if (EnableSegmentedStacks)
542    setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
543                       MVT::i64 : MVT::i32, Custom);
544  else
545    setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
546                       MVT::i64 : MVT::i32, Expand);
547
548  if (!UseSoftFloat && X86ScalarSSEf64) {
549    // f32 and f64 use SSE.
550    // Set up the FP register classes.
551    addRegisterClass(MVT::f32, X86::FR32RegisterClass);
552    addRegisterClass(MVT::f64, X86::FR64RegisterClass);
553
554    // Use ANDPD to simulate FABS.
555    setOperationAction(ISD::FABS , MVT::f64, Custom);
556    setOperationAction(ISD::FABS , MVT::f32, Custom);
557
558    // Use XORP to simulate FNEG.
559    setOperationAction(ISD::FNEG , MVT::f64, Custom);
560    setOperationAction(ISD::FNEG , MVT::f32, Custom);
561
562    // Use ANDPD and ORPD to simulate FCOPYSIGN.
563    setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
564    setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
565
566    // Lower this to FGETSIGNx86 plus an AND.
567    setOperationAction(ISD::FGETSIGN, MVT::i64, Custom);
568    setOperationAction(ISD::FGETSIGN, MVT::i32, Custom);
569
570    // We don't support sin/cos/fmod
571    setOperationAction(ISD::FSIN , MVT::f64, Expand);
572    setOperationAction(ISD::FCOS , MVT::f64, Expand);
573    setOperationAction(ISD::FSIN , MVT::f32, Expand);
574    setOperationAction(ISD::FCOS , MVT::f32, Expand);
575
576    // Expand FP immediates into loads from the stack, except for the special
577    // cases we handle.
578    addLegalFPImmediate(APFloat(+0.0)); // xorpd
579    addLegalFPImmediate(APFloat(+0.0f)); // xorps
580  } else if (!UseSoftFloat && X86ScalarSSEf32) {
581    // Use SSE for f32, x87 for f64.
582    // Set up the FP register classes.
583    addRegisterClass(MVT::f32, X86::FR32RegisterClass);
584    addRegisterClass(MVT::f64, X86::RFP64RegisterClass);
585
586    // Use ANDPS to simulate FABS.
587    setOperationAction(ISD::FABS , MVT::f32, Custom);
588
589    // Use XORP to simulate FNEG.
590    setOperationAction(ISD::FNEG , MVT::f32, Custom);
591
592    setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
593
594    // Use ANDPS and ORPS to simulate FCOPYSIGN.
595    setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
596    setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
597
598    // We don't support sin/cos/fmod
599    setOperationAction(ISD::FSIN , MVT::f32, Expand);
600    setOperationAction(ISD::FCOS , MVT::f32, Expand);
601
602    // Special cases we handle for FP constants.
603    addLegalFPImmediate(APFloat(+0.0f)); // xorps
604    addLegalFPImmediate(APFloat(+0.0)); // FLD0
605    addLegalFPImmediate(APFloat(+1.0)); // FLD1
606    addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
607    addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
608
609    if (!UnsafeFPMath) {
610      setOperationAction(ISD::FSIN           , MVT::f64  , Expand);
611      setOperationAction(ISD::FCOS           , MVT::f64  , Expand);
612    }
613  } else if (!UseSoftFloat) {
614    // f32 and f64 in x87.
615    // Set up the FP register classes.
616    addRegisterClass(MVT::f64, X86::RFP64RegisterClass);
617    addRegisterClass(MVT::f32, X86::RFP32RegisterClass);
618
619    setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
620    setOperationAction(ISD::UNDEF,     MVT::f32, Expand);
621    setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
622    setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
623
624    if (!UnsafeFPMath) {
625      setOperationAction(ISD::FSIN           , MVT::f64  , Expand);
626      setOperationAction(ISD::FCOS           , MVT::f64  , Expand);
627    }
628    addLegalFPImmediate(APFloat(+0.0)); // FLD0
629    addLegalFPImmediate(APFloat(+1.0)); // FLD1
630    addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
631    addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
632    addLegalFPImmediate(APFloat(+0.0f)); // FLD0
633    addLegalFPImmediate(APFloat(+1.0f)); // FLD1
634    addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
635    addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
636  }
637
638  // We don't support FMA.
639  setOperationAction(ISD::FMA, MVT::f64, Expand);
640  setOperationAction(ISD::FMA, MVT::f32, Expand);
641
642  // Long double always uses X87.
643  if (!UseSoftFloat) {
644    addRegisterClass(MVT::f80, X86::RFP80RegisterClass);
645    setOperationAction(ISD::UNDEF,     MVT::f80, Expand);
646    setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
647    {
648      APFloat TmpFlt = APFloat::getZero(APFloat::x87DoubleExtended);
649      addLegalFPImmediate(TmpFlt);  // FLD0
650      TmpFlt.changeSign();
651      addLegalFPImmediate(TmpFlt);  // FLD0/FCHS
652
653      bool ignored;
654      APFloat TmpFlt2(+1.0);
655      TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
656                      &ignored);
657      addLegalFPImmediate(TmpFlt2);  // FLD1
658      TmpFlt2.changeSign();
659      addLegalFPImmediate(TmpFlt2);  // FLD1/FCHS
660    }
661
662    if (!UnsafeFPMath) {
663      setOperationAction(ISD::FSIN           , MVT::f80  , Expand);
664      setOperationAction(ISD::FCOS           , MVT::f80  , Expand);
665    }
666
667    setOperationAction(ISD::FMA, MVT::f80, Expand);
668  }
669
670  // Always use a library call for pow.
671  setOperationAction(ISD::FPOW             , MVT::f32  , Expand);
672  setOperationAction(ISD::FPOW             , MVT::f64  , Expand);
673  setOperationAction(ISD::FPOW             , MVT::f80  , Expand);
674
675  setOperationAction(ISD::FLOG, MVT::f80, Expand);
676  setOperationAction(ISD::FLOG2, MVT::f80, Expand);
677  setOperationAction(ISD::FLOG10, MVT::f80, Expand);
678  setOperationAction(ISD::FEXP, MVT::f80, Expand);
679  setOperationAction(ISD::FEXP2, MVT::f80, Expand);
680
681  // First set operation action for all vector types to either promote
682  // (for widening) or expand (for scalarization). Then we will selectively
683  // turn on ones that can be effectively codegen'd.
684  for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
685       VT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++VT) {
686    setOperationAction(ISD::ADD , (MVT::SimpleValueType)VT, Expand);
687    setOperationAction(ISD::SUB , (MVT::SimpleValueType)VT, Expand);
688    setOperationAction(ISD::FADD, (MVT::SimpleValueType)VT, Expand);
689    setOperationAction(ISD::FNEG, (MVT::SimpleValueType)VT, Expand);
690    setOperationAction(ISD::FSUB, (MVT::SimpleValueType)VT, Expand);
691    setOperationAction(ISD::MUL , (MVT::SimpleValueType)VT, Expand);
692    setOperationAction(ISD::FMUL, (MVT::SimpleValueType)VT, Expand);
693    setOperationAction(ISD::SDIV, (MVT::SimpleValueType)VT, Expand);
694    setOperationAction(ISD::UDIV, (MVT::SimpleValueType)VT, Expand);
695    setOperationAction(ISD::FDIV, (MVT::SimpleValueType)VT, Expand);
696    setOperationAction(ISD::SREM, (MVT::SimpleValueType)VT, Expand);
697    setOperationAction(ISD::UREM, (MVT::SimpleValueType)VT, Expand);
698    setOperationAction(ISD::LOAD, (MVT::SimpleValueType)VT, Expand);
699    setOperationAction(ISD::VECTOR_SHUFFLE, (MVT::SimpleValueType)VT, Expand);
700    setOperationAction(ISD::EXTRACT_VECTOR_ELT,(MVT::SimpleValueType)VT,Expand);
701    setOperationAction(ISD::INSERT_VECTOR_ELT,(MVT::SimpleValueType)VT, Expand);
702    setOperationAction(ISD::EXTRACT_SUBVECTOR,(MVT::SimpleValueType)VT,Expand);
703    setOperationAction(ISD::INSERT_SUBVECTOR,(MVT::SimpleValueType)VT,Expand);
704    setOperationAction(ISD::FABS, (MVT::SimpleValueType)VT, Expand);
705    setOperationAction(ISD::FSIN, (MVT::SimpleValueType)VT, Expand);
706    setOperationAction(ISD::FCOS, (MVT::SimpleValueType)VT, Expand);
707    setOperationAction(ISD::FREM, (MVT::SimpleValueType)VT, Expand);
708    setOperationAction(ISD::FPOWI, (MVT::SimpleValueType)VT, Expand);
709    setOperationAction(ISD::FSQRT, (MVT::SimpleValueType)VT, Expand);
710    setOperationAction(ISD::FCOPYSIGN, (MVT::SimpleValueType)VT, Expand);
711    setOperationAction(ISD::SMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
712    setOperationAction(ISD::UMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
713    setOperationAction(ISD::SDIVREM, (MVT::SimpleValueType)VT, Expand);
714    setOperationAction(ISD::UDIVREM, (MVT::SimpleValueType)VT, Expand);
715    setOperationAction(ISD::FPOW, (MVT::SimpleValueType)VT, Expand);
716    setOperationAction(ISD::CTPOP, (MVT::SimpleValueType)VT, Expand);
717    setOperationAction(ISD::CTTZ, (MVT::SimpleValueType)VT, Expand);
718    setOperationAction(ISD::CTLZ, (MVT::SimpleValueType)VT, Expand);
719    setOperationAction(ISD::SHL, (MVT::SimpleValueType)VT, Expand);
720    setOperationAction(ISD::SRA, (MVT::SimpleValueType)VT, Expand);
721    setOperationAction(ISD::SRL, (MVT::SimpleValueType)VT, Expand);
722    setOperationAction(ISD::ROTL, (MVT::SimpleValueType)VT, Expand);
723    setOperationAction(ISD::ROTR, (MVT::SimpleValueType)VT, Expand);
724    setOperationAction(ISD::BSWAP, (MVT::SimpleValueType)VT, Expand);
725    setOperationAction(ISD::SETCC, (MVT::SimpleValueType)VT, Expand);
726    setOperationAction(ISD::FLOG, (MVT::SimpleValueType)VT, Expand);
727    setOperationAction(ISD::FLOG2, (MVT::SimpleValueType)VT, Expand);
728    setOperationAction(ISD::FLOG10, (MVT::SimpleValueType)VT, Expand);
729    setOperationAction(ISD::FEXP, (MVT::SimpleValueType)VT, Expand);
730    setOperationAction(ISD::FEXP2, (MVT::SimpleValueType)VT, Expand);
731    setOperationAction(ISD::FP_TO_UINT, (MVT::SimpleValueType)VT, Expand);
732    setOperationAction(ISD::FP_TO_SINT, (MVT::SimpleValueType)VT, Expand);
733    setOperationAction(ISD::UINT_TO_FP, (MVT::SimpleValueType)VT, Expand);
734    setOperationAction(ISD::SINT_TO_FP, (MVT::SimpleValueType)VT, Expand);
735    setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,Expand);
736    setOperationAction(ISD::TRUNCATE,  (MVT::SimpleValueType)VT, Expand);
737    setOperationAction(ISD::SIGN_EXTEND,  (MVT::SimpleValueType)VT, Expand);
738    setOperationAction(ISD::ZERO_EXTEND,  (MVT::SimpleValueType)VT, Expand);
739    setOperationAction(ISD::ANY_EXTEND,  (MVT::SimpleValueType)VT, Expand);
740    setOperationAction(ISD::VSELECT,  (MVT::SimpleValueType)VT, Expand);
741    for (unsigned InnerVT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
742         InnerVT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
743      setTruncStoreAction((MVT::SimpleValueType)VT,
744                          (MVT::SimpleValueType)InnerVT, Expand);
745    setLoadExtAction(ISD::SEXTLOAD, (MVT::SimpleValueType)VT, Expand);
746    setLoadExtAction(ISD::ZEXTLOAD, (MVT::SimpleValueType)VT, Expand);
747    setLoadExtAction(ISD::EXTLOAD, (MVT::SimpleValueType)VT, Expand);
748  }
749
750  // FIXME: In order to prevent SSE instructions being expanded to MMX ones
751  // with -msoft-float, disable use of MMX as well.
752  if (!UseSoftFloat && Subtarget->hasMMX()) {
753    addRegisterClass(MVT::x86mmx, X86::VR64RegisterClass);
754    // No operations on x86mmx supported, everything uses intrinsics.
755  }
756
757  // MMX-sized vectors (other than x86mmx) are expected to be expanded
758  // into smaller operations.
759  setOperationAction(ISD::MULHS,              MVT::v8i8,  Expand);
760  setOperationAction(ISD::MULHS,              MVT::v4i16, Expand);
761  setOperationAction(ISD::MULHS,              MVT::v2i32, Expand);
762  setOperationAction(ISD::MULHS,              MVT::v1i64, Expand);
763  setOperationAction(ISD::AND,                MVT::v8i8,  Expand);
764  setOperationAction(ISD::AND,                MVT::v4i16, Expand);
765  setOperationAction(ISD::AND,                MVT::v2i32, Expand);
766  setOperationAction(ISD::AND,                MVT::v1i64, Expand);
767  setOperationAction(ISD::OR,                 MVT::v8i8,  Expand);
768  setOperationAction(ISD::OR,                 MVT::v4i16, Expand);
769  setOperationAction(ISD::OR,                 MVT::v2i32, Expand);
770  setOperationAction(ISD::OR,                 MVT::v1i64, Expand);
771  setOperationAction(ISD::XOR,                MVT::v8i8,  Expand);
772  setOperationAction(ISD::XOR,                MVT::v4i16, Expand);
773  setOperationAction(ISD::XOR,                MVT::v2i32, Expand);
774  setOperationAction(ISD::XOR,                MVT::v1i64, Expand);
775  setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i8,  Expand);
776  setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v4i16, Expand);
777  setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v2i32, Expand);
778  setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v1i64, Expand);
779  setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v1i64, Expand);
780  setOperationAction(ISD::SELECT,             MVT::v8i8,  Expand);
781  setOperationAction(ISD::SELECT,             MVT::v4i16, Expand);
782  setOperationAction(ISD::SELECT,             MVT::v2i32, Expand);
783  setOperationAction(ISD::SELECT,             MVT::v1i64, Expand);
784  setOperationAction(ISD::BITCAST,            MVT::v8i8,  Expand);
785  setOperationAction(ISD::BITCAST,            MVT::v4i16, Expand);
786  setOperationAction(ISD::BITCAST,            MVT::v2i32, Expand);
787  setOperationAction(ISD::BITCAST,            MVT::v1i64, Expand);
788
789  if (!UseSoftFloat && Subtarget->hasXMM()) {
790    addRegisterClass(MVT::v4f32, X86::VR128RegisterClass);
791
792    setOperationAction(ISD::FADD,               MVT::v4f32, Legal);
793    setOperationAction(ISD::FSUB,               MVT::v4f32, Legal);
794    setOperationAction(ISD::FMUL,               MVT::v4f32, Legal);
795    setOperationAction(ISD::FDIV,               MVT::v4f32, Legal);
796    setOperationAction(ISD::FSQRT,              MVT::v4f32, Legal);
797    setOperationAction(ISD::FNEG,               MVT::v4f32, Custom);
798    setOperationAction(ISD::LOAD,               MVT::v4f32, Legal);
799    setOperationAction(ISD::BUILD_VECTOR,       MVT::v4f32, Custom);
800    setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4f32, Custom);
801    setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
802    setOperationAction(ISD::SELECT,             MVT::v4f32, Custom);
803    setOperationAction(ISD::SETCC,              MVT::v4f32, Custom);
804  }
805
806  if (!UseSoftFloat && Subtarget->hasXMMInt()) {
807    addRegisterClass(MVT::v2f64, X86::VR128RegisterClass);
808
809    // FIXME: Unfortunately -soft-float and -no-implicit-float means XMM
810    // registers cannot be used even for integer operations.
811    addRegisterClass(MVT::v16i8, X86::VR128RegisterClass);
812    addRegisterClass(MVT::v8i16, X86::VR128RegisterClass);
813    addRegisterClass(MVT::v4i32, X86::VR128RegisterClass);
814    addRegisterClass(MVT::v2i64, X86::VR128RegisterClass);
815
816    setOperationAction(ISD::ADD,                MVT::v16i8, Legal);
817    setOperationAction(ISD::ADD,                MVT::v8i16, Legal);
818    setOperationAction(ISD::ADD,                MVT::v4i32, Legal);
819    setOperationAction(ISD::ADD,                MVT::v2i64, Legal);
820    setOperationAction(ISD::MUL,                MVT::v2i64, Custom);
821    setOperationAction(ISD::SUB,                MVT::v16i8, Legal);
822    setOperationAction(ISD::SUB,                MVT::v8i16, Legal);
823    setOperationAction(ISD::SUB,                MVT::v4i32, Legal);
824    setOperationAction(ISD::SUB,                MVT::v2i64, Legal);
825    setOperationAction(ISD::MUL,                MVT::v8i16, Legal);
826    setOperationAction(ISD::FADD,               MVT::v2f64, Legal);
827    setOperationAction(ISD::FSUB,               MVT::v2f64, Legal);
828    setOperationAction(ISD::FMUL,               MVT::v2f64, Legal);
829    setOperationAction(ISD::FDIV,               MVT::v2f64, Legal);
830    setOperationAction(ISD::FSQRT,              MVT::v2f64, Legal);
831    setOperationAction(ISD::FNEG,               MVT::v2f64, Custom);
832
833    setOperationAction(ISD::SETCC,              MVT::v2i64, Custom);
834    setOperationAction(ISD::SETCC,              MVT::v16i8, Custom);
835    setOperationAction(ISD::SETCC,              MVT::v8i16, Custom);
836    setOperationAction(ISD::SETCC,              MVT::v4i32, Custom);
837
838    setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v16i8, Custom);
839    setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i16, Custom);
840    setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
841    setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
842    setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
843
844    setOperationAction(ISD::CONCAT_VECTORS,     MVT::v2f64, Custom);
845    setOperationAction(ISD::CONCAT_VECTORS,     MVT::v2i64, Custom);
846    setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i8, Custom);
847    setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i16, Custom);
848    setOperationAction(ISD::CONCAT_VECTORS,     MVT::v4i32, Custom);
849
850    // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
851    for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v2i64; ++i) {
852      EVT VT = (MVT::SimpleValueType)i;
853      // Do not attempt to custom lower non-power-of-2 vectors
854      if (!isPowerOf2_32(VT.getVectorNumElements()))
855        continue;
856      // Do not attempt to custom lower non-128-bit vectors
857      if (!VT.is128BitVector())
858        continue;
859      setOperationAction(ISD::BUILD_VECTOR,
860                         VT.getSimpleVT().SimpleTy, Custom);
861      setOperationAction(ISD::VECTOR_SHUFFLE,
862                         VT.getSimpleVT().SimpleTy, Custom);
863      setOperationAction(ISD::EXTRACT_VECTOR_ELT,
864                         VT.getSimpleVT().SimpleTy, Custom);
865    }
866
867    setOperationAction(ISD::BUILD_VECTOR,       MVT::v2f64, Custom);
868    setOperationAction(ISD::BUILD_VECTOR,       MVT::v2i64, Custom);
869    setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2f64, Custom);
870    setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2i64, Custom);
871    setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2f64, Custom);
872    setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
873
874    if (Subtarget->is64Bit()) {
875      setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
876      setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
877    }
878
879    // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
880    for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v2i64; i++) {
881      MVT::SimpleValueType SVT = (MVT::SimpleValueType)i;
882      EVT VT = SVT;
883
884      // Do not attempt to promote non-128-bit vectors
885      if (!VT.is128BitVector())
886        continue;
887
888      setOperationAction(ISD::AND,    SVT, Promote);
889      AddPromotedToType (ISD::AND,    SVT, MVT::v2i64);
890      setOperationAction(ISD::OR,     SVT, Promote);
891      AddPromotedToType (ISD::OR,     SVT, MVT::v2i64);
892      setOperationAction(ISD::XOR,    SVT, Promote);
893      AddPromotedToType (ISD::XOR,    SVT, MVT::v2i64);
894      setOperationAction(ISD::LOAD,   SVT, Promote);
895      AddPromotedToType (ISD::LOAD,   SVT, MVT::v2i64);
896      setOperationAction(ISD::SELECT, SVT, Promote);
897      AddPromotedToType (ISD::SELECT, SVT, MVT::v2i64);
898    }
899
900    setTruncStoreAction(MVT::f64, MVT::f32, Expand);
901
902    // Custom lower v2i64 and v2f64 selects.
903    setOperationAction(ISD::LOAD,               MVT::v2f64, Legal);
904    setOperationAction(ISD::LOAD,               MVT::v2i64, Legal);
905    setOperationAction(ISD::SELECT,             MVT::v2f64, Custom);
906    setOperationAction(ISD::SELECT,             MVT::v2i64, Custom);
907
908    setOperationAction(ISD::FP_TO_SINT,         MVT::v4i32, Legal);
909    setOperationAction(ISD::SINT_TO_FP,         MVT::v4i32, Legal);
910  }
911
912  if (Subtarget->hasSSE41() || Subtarget->hasAVX()) {
913    setOperationAction(ISD::FFLOOR,             MVT::f32,   Legal);
914    setOperationAction(ISD::FCEIL,              MVT::f32,   Legal);
915    setOperationAction(ISD::FTRUNC,             MVT::f32,   Legal);
916    setOperationAction(ISD::FRINT,              MVT::f32,   Legal);
917    setOperationAction(ISD::FNEARBYINT,         MVT::f32,   Legal);
918    setOperationAction(ISD::FFLOOR,             MVT::f64,   Legal);
919    setOperationAction(ISD::FCEIL,              MVT::f64,   Legal);
920    setOperationAction(ISD::FTRUNC,             MVT::f64,   Legal);
921    setOperationAction(ISD::FRINT,              MVT::f64,   Legal);
922    setOperationAction(ISD::FNEARBYINT,         MVT::f64,   Legal);
923
924    // FIXME: Do we need to handle scalar-to-vector here?
925    setOperationAction(ISD::MUL,                MVT::v4i32, Legal);
926
927    // Can turn SHL into an integer multiply.
928    setOperationAction(ISD::SHL,                MVT::v4i32, Custom);
929    setOperationAction(ISD::SHL,                MVT::v16i8, Custom);
930
931    setOperationAction(ISD::VSELECT,            MVT::v2f64, Legal);
932    setOperationAction(ISD::VSELECT,            MVT::v2i64, Legal);
933    setOperationAction(ISD::VSELECT,            MVT::v16i8, Legal);
934    setOperationAction(ISD::VSELECT,            MVT::v4i32, Legal);
935    setOperationAction(ISD::VSELECT,            MVT::v4f32, Legal);
936
937    // i8 and i16 vectors are custom , because the source register and source
938    // source memory operand types are not the same width.  f32 vectors are
939    // custom since the immediate controlling the insert encodes additional
940    // information.
941    setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i8, Custom);
942    setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
943    setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
944    setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
945
946    setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
947    setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
948    setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
949    setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
950
951    if (Subtarget->is64Bit()) {
952      setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Legal);
953      setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Legal);
954    }
955  }
956
957  if (Subtarget->hasXMMInt()) {
958    setOperationAction(ISD::SRL,               MVT::v2i64, Custom);
959    setOperationAction(ISD::SRL,               MVT::v4i32, Custom);
960    setOperationAction(ISD::SRL,               MVT::v16i8, Custom);
961    setOperationAction(ISD::SRL,               MVT::v8i16, Custom);
962
963    setOperationAction(ISD::SHL,               MVT::v2i64, Custom);
964    setOperationAction(ISD::SHL,               MVT::v4i32, Custom);
965    setOperationAction(ISD::SHL,               MVT::v8i16, Custom);
966
967    setOperationAction(ISD::SRA,               MVT::v4i32, Custom);
968    setOperationAction(ISD::SRA,               MVT::v8i16, Custom);
969  }
970
971  if (Subtarget->hasSSE42() || Subtarget->hasAVX())
972    setOperationAction(ISD::SETCC,             MVT::v2i64, Custom);
973
974  if (!UseSoftFloat && Subtarget->hasAVX()) {
975    addRegisterClass(MVT::v32i8,  X86::VR256RegisterClass);
976    addRegisterClass(MVT::v16i16, X86::VR256RegisterClass);
977    addRegisterClass(MVT::v8i32,  X86::VR256RegisterClass);
978    addRegisterClass(MVT::v8f32,  X86::VR256RegisterClass);
979    addRegisterClass(MVT::v4i64,  X86::VR256RegisterClass);
980    addRegisterClass(MVT::v4f64,  X86::VR256RegisterClass);
981
982    setOperationAction(ISD::LOAD,               MVT::v8f32, Legal);
983    setOperationAction(ISD::LOAD,               MVT::v4f64, Legal);
984    setOperationAction(ISD::LOAD,               MVT::v4i64, Legal);
985
986    setOperationAction(ISD::FADD,               MVT::v8f32, Legal);
987    setOperationAction(ISD::FSUB,               MVT::v8f32, Legal);
988    setOperationAction(ISD::FMUL,               MVT::v8f32, Legal);
989    setOperationAction(ISD::FDIV,               MVT::v8f32, Legal);
990    setOperationAction(ISD::FSQRT,              MVT::v8f32, Legal);
991    setOperationAction(ISD::FNEG,               MVT::v8f32, Custom);
992
993    setOperationAction(ISD::FADD,               MVT::v4f64, Legal);
994    setOperationAction(ISD::FSUB,               MVT::v4f64, Legal);
995    setOperationAction(ISD::FMUL,               MVT::v4f64, Legal);
996    setOperationAction(ISD::FDIV,               MVT::v4f64, Legal);
997    setOperationAction(ISD::FSQRT,              MVT::v4f64, Legal);
998    setOperationAction(ISD::FNEG,               MVT::v4f64, Custom);
999
1000    setOperationAction(ISD::FP_TO_SINT,         MVT::v8i32, Legal);
1001    setOperationAction(ISD::SINT_TO_FP,         MVT::v8i32, Legal);
1002    setOperationAction(ISD::FP_ROUND,           MVT::v4f32, Legal);
1003
1004    setOperationAction(ISD::CONCAT_VECTORS,     MVT::v4f64,  Custom);
1005    setOperationAction(ISD::CONCAT_VECTORS,     MVT::v4i64,  Custom);
1006    setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8f32,  Custom);
1007    setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i32,  Custom);
1008    setOperationAction(ISD::CONCAT_VECTORS,     MVT::v32i8,  Custom);
1009    setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i16, Custom);
1010
1011    setOperationAction(ISD::SRL,               MVT::v4i64, Custom);
1012    setOperationAction(ISD::SRL,               MVT::v8i32, Custom);
1013    setOperationAction(ISD::SRL,               MVT::v16i16, Custom);
1014    setOperationAction(ISD::SRL,               MVT::v32i8, Custom);
1015
1016    setOperationAction(ISD::SHL,               MVT::v4i64, Custom);
1017    setOperationAction(ISD::SHL,               MVT::v8i32, Custom);
1018    setOperationAction(ISD::SHL,               MVT::v16i16, Custom);
1019    setOperationAction(ISD::SHL,               MVT::v32i8, Custom);
1020
1021    setOperationAction(ISD::SRA,               MVT::v8i32, Custom);
1022    setOperationAction(ISD::SRA,               MVT::v16i16, Custom);
1023
1024    setOperationAction(ISD::SETCC,             MVT::v32i8, Custom);
1025    setOperationAction(ISD::SETCC,             MVT::v16i16, Custom);
1026    setOperationAction(ISD::SETCC,             MVT::v8i32, Custom);
1027    setOperationAction(ISD::SETCC,             MVT::v4i64, Custom);
1028
1029    setOperationAction(ISD::SELECT,            MVT::v4f64, Custom);
1030    setOperationAction(ISD::SELECT,            MVT::v4i64, Custom);
1031    setOperationAction(ISD::SELECT,            MVT::v8f32, Custom);
1032
1033    setOperationAction(ISD::VSELECT,            MVT::v4f64, Legal);
1034    setOperationAction(ISD::VSELECT,            MVT::v4i64, Legal);
1035    setOperationAction(ISD::VSELECT,            MVT::v8i32, Legal);
1036    setOperationAction(ISD::VSELECT,            MVT::v8f32, Legal);
1037
1038    setOperationAction(ISD::ADD,               MVT::v4i64, Custom);
1039    setOperationAction(ISD::ADD,               MVT::v8i32, Custom);
1040    setOperationAction(ISD::ADD,               MVT::v16i16, Custom);
1041    setOperationAction(ISD::ADD,               MVT::v32i8, Custom);
1042
1043    setOperationAction(ISD::SUB,               MVT::v4i64, Custom);
1044    setOperationAction(ISD::SUB,               MVT::v8i32, Custom);
1045    setOperationAction(ISD::SUB,               MVT::v16i16, Custom);
1046    setOperationAction(ISD::SUB,               MVT::v32i8, Custom);
1047
1048    setOperationAction(ISD::MUL,               MVT::v4i64, Custom);
1049    setOperationAction(ISD::MUL,               MVT::v8i32, Custom);
1050    setOperationAction(ISD::MUL,               MVT::v16i16, Custom);
1051    // Don't lower v32i8 because there is no 128-bit byte mul
1052
1053    // Custom lower several nodes for 256-bit types.
1054    for (unsigned i = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
1055                  i <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++i) {
1056      MVT::SimpleValueType SVT = (MVT::SimpleValueType)i;
1057      EVT VT = SVT;
1058
1059      // Extract subvector is special because the value type
1060      // (result) is 128-bit but the source is 256-bit wide.
1061      if (VT.is128BitVector())
1062        setOperationAction(ISD::EXTRACT_SUBVECTOR, SVT, Custom);
1063
1064      // Do not attempt to custom lower other non-256-bit vectors
1065      if (!VT.is256BitVector())
1066        continue;
1067
1068      setOperationAction(ISD::BUILD_VECTOR,       SVT, Custom);
1069      setOperationAction(ISD::VECTOR_SHUFFLE,     SVT, Custom);
1070      setOperationAction(ISD::INSERT_VECTOR_ELT,  SVT, Custom);
1071      setOperationAction(ISD::EXTRACT_VECTOR_ELT, SVT, Custom);
1072      setOperationAction(ISD::SCALAR_TO_VECTOR,   SVT, Custom);
1073      setOperationAction(ISD::INSERT_SUBVECTOR,   SVT, Custom);
1074    }
1075
1076    // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
1077    for (unsigned i = (unsigned)MVT::v32i8; i != (unsigned)MVT::v4i64; ++i) {
1078      MVT::SimpleValueType SVT = (MVT::SimpleValueType)i;
1079      EVT VT = SVT;
1080
1081      // Do not attempt to promote non-256-bit vectors
1082      if (!VT.is256BitVector())
1083        continue;
1084
1085      setOperationAction(ISD::AND,    SVT, Promote);
1086      AddPromotedToType (ISD::AND,    SVT, MVT::v4i64);
1087      setOperationAction(ISD::OR,     SVT, Promote);
1088      AddPromotedToType (ISD::OR,     SVT, MVT::v4i64);
1089      setOperationAction(ISD::XOR,    SVT, Promote);
1090      AddPromotedToType (ISD::XOR,    SVT, MVT::v4i64);
1091      setOperationAction(ISD::LOAD,   SVT, Promote);
1092      AddPromotedToType (ISD::LOAD,   SVT, MVT::v4i64);
1093      setOperationAction(ISD::SELECT, SVT, Promote);
1094      AddPromotedToType (ISD::SELECT, SVT, MVT::v4i64);
1095    }
1096  }
1097
1098  // SIGN_EXTEND_INREGs are evaluated by the extend type. Handle the expansion
1099  // of this type with custom code.
1100  for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
1101         VT != (unsigned)MVT::LAST_VECTOR_VALUETYPE; VT++) {
1102    setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT, Custom);
1103  }
1104
1105  // We want to custom lower some of our intrinsics.
1106  setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1107
1108
1109  // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1110  // handle type legalization for these operations here.
1111  //
1112  // FIXME: We really should do custom legalization for addition and
1113  // subtraction on x86-32 once PR3203 is fixed.  We really can't do much better
1114  // than generic legalization for 64-bit multiplication-with-overflow, though.
1115  for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) {
1116    // Add/Sub/Mul with overflow operations are custom lowered.
1117    MVT VT = IntVTs[i];
1118    setOperationAction(ISD::SADDO, VT, Custom);
1119    setOperationAction(ISD::UADDO, VT, Custom);
1120    setOperationAction(ISD::SSUBO, VT, Custom);
1121    setOperationAction(ISD::USUBO, VT, Custom);
1122    setOperationAction(ISD::SMULO, VT, Custom);
1123    setOperationAction(ISD::UMULO, VT, Custom);
1124  }
1125
1126  // There are no 8-bit 3-address imul/mul instructions
1127  setOperationAction(ISD::SMULO, MVT::i8, Expand);
1128  setOperationAction(ISD::UMULO, MVT::i8, Expand);
1129
1130  if (!Subtarget->is64Bit()) {
1131    // These libcalls are not available in 32-bit.
1132    setLibcallName(RTLIB::SHL_I128, 0);
1133    setLibcallName(RTLIB::SRL_I128, 0);
1134    setLibcallName(RTLIB::SRA_I128, 0);
1135  }
1136
1137  // We have target-specific dag combine patterns for the following nodes:
1138  setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1139  setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1140  setTargetDAGCombine(ISD::BITCAST);
1141  setTargetDAGCombine(ISD::BUILD_VECTOR);
1142  setTargetDAGCombine(ISD::VSELECT);
1143  setTargetDAGCombine(ISD::SELECT);
1144  setTargetDAGCombine(ISD::SHL);
1145  setTargetDAGCombine(ISD::SRA);
1146  setTargetDAGCombine(ISD::SRL);
1147  setTargetDAGCombine(ISD::OR);
1148  setTargetDAGCombine(ISD::AND);
1149  setTargetDAGCombine(ISD::ADD);
1150  setTargetDAGCombine(ISD::FADD);
1151  setTargetDAGCombine(ISD::FSUB);
1152  setTargetDAGCombine(ISD::SUB);
1153  setTargetDAGCombine(ISD::LOAD);
1154  setTargetDAGCombine(ISD::STORE);
1155  setTargetDAGCombine(ISD::ZERO_EXTEND);
1156  setTargetDAGCombine(ISD::SINT_TO_FP);
1157  if (Subtarget->is64Bit())
1158    setTargetDAGCombine(ISD::MUL);
1159
1160  computeRegisterProperties();
1161
1162  // On Darwin, -Os means optimize for size without hurting performance,
1163  // do not reduce the limit.
1164  maxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1165  maxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 16 : 8;
1166  maxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1167  maxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1168  maxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1169  maxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1170  setPrefLoopAlignment(16);
1171  benefitFromCodePlacementOpt = true;
1172
1173  setPrefFunctionAlignment(4);
1174}
1175
1176
1177EVT X86TargetLowering::getSetCCResultType(EVT VT) const {
1178  if (!VT.isVector()) return MVT::i8;
1179  return VT.changeVectorElementTypeToInteger();
1180}
1181
1182
1183/// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1184/// the desired ByVal argument alignment.
1185static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
1186  if (MaxAlign == 16)
1187    return;
1188  if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1189    if (VTy->getBitWidth() == 128)
1190      MaxAlign = 16;
1191  } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1192    unsigned EltAlign = 0;
1193    getMaxByValAlign(ATy->getElementType(), EltAlign);
1194    if (EltAlign > MaxAlign)
1195      MaxAlign = EltAlign;
1196  } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1197    for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1198      unsigned EltAlign = 0;
1199      getMaxByValAlign(STy->getElementType(i), EltAlign);
1200      if (EltAlign > MaxAlign)
1201        MaxAlign = EltAlign;
1202      if (MaxAlign == 16)
1203        break;
1204    }
1205  }
1206  return;
1207}
1208
1209/// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1210/// function arguments in the caller parameter area. For X86, aggregates
1211/// that contain SSE vectors are placed at 16-byte boundaries while the rest
1212/// are at 4-byte boundaries.
1213unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty) const {
1214  if (Subtarget->is64Bit()) {
1215    // Max of 8 and alignment of type.
1216    unsigned TyAlign = TD->getABITypeAlignment(Ty);
1217    if (TyAlign > 8)
1218      return TyAlign;
1219    return 8;
1220  }
1221
1222  unsigned Align = 4;
1223  if (Subtarget->hasXMM())
1224    getMaxByValAlign(Ty, Align);
1225  return Align;
1226}
1227
1228/// getOptimalMemOpType - Returns the target specific optimal type for load
1229/// and store operations as a result of memset, memcpy, and memmove
1230/// lowering. If DstAlign is zero that means it's safe to destination
1231/// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1232/// means there isn't a need to check it against alignment requirement,
1233/// probably because the source does not need to be loaded. If
1234/// 'NonScalarIntSafe' is true, that means it's safe to return a
1235/// non-scalar-integer type, e.g. empty string source, constant, or loaded
1236/// from memory. 'MemcpyStrSrc' indicates whether the memcpy source is
1237/// constant so it does not need to be loaded.
1238/// It returns EVT::Other if the type should be determined using generic
1239/// target-independent logic.
1240EVT
1241X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1242                                       unsigned DstAlign, unsigned SrcAlign,
1243                                       bool NonScalarIntSafe,
1244                                       bool MemcpyStrSrc,
1245                                       MachineFunction &MF) const {
1246  // FIXME: This turns off use of xmm stores for memset/memcpy on targets like
1247  // linux.  This is because the stack realignment code can't handle certain
1248  // cases like PR2962.  This should be removed when PR2962 is fixed.
1249  const Function *F = MF.getFunction();
1250  if (NonScalarIntSafe &&
1251      !F->hasFnAttr(Attribute::NoImplicitFloat)) {
1252    if (Size >= 16 &&
1253        (Subtarget->isUnalignedMemAccessFast() ||
1254         ((DstAlign == 0 || DstAlign >= 16) &&
1255          (SrcAlign == 0 || SrcAlign >= 16))) &&
1256        Subtarget->getStackAlignment() >= 16) {
1257      if (Subtarget->hasAVX() &&
1258          Subtarget->getStackAlignment() >= 32)
1259        return MVT::v8f32;
1260      if (Subtarget->hasXMMInt())
1261        return MVT::v4i32;
1262      if (Subtarget->hasXMM())
1263        return MVT::v4f32;
1264    } else if (!MemcpyStrSrc && Size >= 8 &&
1265               !Subtarget->is64Bit() &&
1266               Subtarget->getStackAlignment() >= 8 &&
1267               Subtarget->hasXMMInt()) {
1268      // Do not use f64 to lower memcpy if source is string constant. It's
1269      // better to use i32 to avoid the loads.
1270      return MVT::f64;
1271    }
1272  }
1273  if (Subtarget->is64Bit() && Size >= 8)
1274    return MVT::i64;
1275  return MVT::i32;
1276}
1277
1278/// getJumpTableEncoding - Return the entry encoding for a jump table in the
1279/// current function.  The returned value is a member of the
1280/// MachineJumpTableInfo::JTEntryKind enum.
1281unsigned X86TargetLowering::getJumpTableEncoding() const {
1282  // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1283  // symbol.
1284  if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1285      Subtarget->isPICStyleGOT())
1286    return MachineJumpTableInfo::EK_Custom32;
1287
1288  // Otherwise, use the normal jump table encoding heuristics.
1289  return TargetLowering::getJumpTableEncoding();
1290}
1291
1292const MCExpr *
1293X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1294                                             const MachineBasicBlock *MBB,
1295                                             unsigned uid,MCContext &Ctx) const{
1296  assert(getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1297         Subtarget->isPICStyleGOT());
1298  // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1299  // entries.
1300  return MCSymbolRefExpr::Create(MBB->getSymbol(),
1301                                 MCSymbolRefExpr::VK_GOTOFF, Ctx);
1302}
1303
1304/// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
1305/// jumptable.
1306SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1307                                                    SelectionDAG &DAG) const {
1308  if (!Subtarget->is64Bit())
1309    // This doesn't have DebugLoc associated with it, but is not really the
1310    // same as a Register.
1311    return DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), getPointerTy());
1312  return Table;
1313}
1314
1315/// getPICJumpTableRelocBaseExpr - This returns the relocation base for the
1316/// given PIC jumptable, the same as getPICJumpTableRelocBase, but as an
1317/// MCExpr.
1318const MCExpr *X86TargetLowering::
1319getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1320                             MCContext &Ctx) const {
1321  // X86-64 uses RIP relative addressing based on the jump table label.
1322  if (Subtarget->isPICStyleRIPRel())
1323    return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1324
1325  // Otherwise, the reference is relative to the PIC base.
1326  return MCSymbolRefExpr::Create(MF->getPICBaseSymbol(), Ctx);
1327}
1328
1329// FIXME: Why this routine is here? Move to RegInfo!
1330std::pair<const TargetRegisterClass*, uint8_t>
1331X86TargetLowering::findRepresentativeClass(EVT VT) const{
1332  const TargetRegisterClass *RRC = 0;
1333  uint8_t Cost = 1;
1334  switch (VT.getSimpleVT().SimpleTy) {
1335  default:
1336    return TargetLowering::findRepresentativeClass(VT);
1337  case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1338    RRC = (Subtarget->is64Bit()
1339           ? X86::GR64RegisterClass : X86::GR32RegisterClass);
1340    break;
1341  case MVT::x86mmx:
1342    RRC = X86::VR64RegisterClass;
1343    break;
1344  case MVT::f32: case MVT::f64:
1345  case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1346  case MVT::v4f32: case MVT::v2f64:
1347  case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
1348  case MVT::v4f64:
1349    RRC = X86::VR128RegisterClass;
1350    break;
1351  }
1352  return std::make_pair(RRC, Cost);
1353}
1354
1355bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
1356                                               unsigned &Offset) const {
1357  if (!Subtarget->isTargetLinux())
1358    return false;
1359
1360  if (Subtarget->is64Bit()) {
1361    // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
1362    Offset = 0x28;
1363    if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
1364      AddressSpace = 256;
1365    else
1366      AddressSpace = 257;
1367  } else {
1368    // %gs:0x14 on i386
1369    Offset = 0x14;
1370    AddressSpace = 256;
1371  }
1372  return true;
1373}
1374
1375
1376//===----------------------------------------------------------------------===//
1377//               Return Value Calling Convention Implementation
1378//===----------------------------------------------------------------------===//
1379
1380#include "X86GenCallingConv.inc"
1381
1382bool
1383X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv,
1384				  MachineFunction &MF, bool isVarArg,
1385                        const SmallVectorImpl<ISD::OutputArg> &Outs,
1386                        LLVMContext &Context) const {
1387  SmallVector<CCValAssign, 16> RVLocs;
1388  CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1389                 RVLocs, Context);
1390  return CCInfo.CheckReturn(Outs, RetCC_X86);
1391}
1392
1393SDValue
1394X86TargetLowering::LowerReturn(SDValue Chain,
1395                               CallingConv::ID CallConv, bool isVarArg,
1396                               const SmallVectorImpl<ISD::OutputArg> &Outs,
1397                               const SmallVectorImpl<SDValue> &OutVals,
1398                               DebugLoc dl, SelectionDAG &DAG) const {
1399  MachineFunction &MF = DAG.getMachineFunction();
1400  X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1401
1402  SmallVector<CCValAssign, 16> RVLocs;
1403  CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1404                 RVLocs, *DAG.getContext());
1405  CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1406
1407  // Add the regs to the liveout set for the function.
1408  MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
1409  for (unsigned i = 0; i != RVLocs.size(); ++i)
1410    if (RVLocs[i].isRegLoc() && !MRI.isLiveOut(RVLocs[i].getLocReg()))
1411      MRI.addLiveOut(RVLocs[i].getLocReg());
1412
1413  SDValue Flag;
1414
1415  SmallVector<SDValue, 6> RetOps;
1416  RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1417  // Operand #1 = Bytes To Pop
1418  RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(),
1419                   MVT::i16));
1420
1421  // Copy the result values into the output registers.
1422  for (unsigned i = 0; i != RVLocs.size(); ++i) {
1423    CCValAssign &VA = RVLocs[i];
1424    assert(VA.isRegLoc() && "Can only return in registers!");
1425    SDValue ValToCopy = OutVals[i];
1426    EVT ValVT = ValToCopy.getValueType();
1427
1428    // If this is x86-64, and we disabled SSE, we can't return FP values,
1429    // or SSE or MMX vectors.
1430    if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
1431         VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
1432          (Subtarget->is64Bit() && !Subtarget->hasXMM())) {
1433      report_fatal_error("SSE register return with SSE disabled");
1434    }
1435    // Likewise we can't return F64 values with SSE1 only.  gcc does so, but
1436    // llvm-gcc has never done it right and no one has noticed, so this
1437    // should be OK for now.
1438    if (ValVT == MVT::f64 &&
1439        (Subtarget->is64Bit() && !Subtarget->hasXMMInt()))
1440      report_fatal_error("SSE2 register return with SSE2 disabled");
1441
1442    // Returns in ST0/ST1 are handled specially: these are pushed as operands to
1443    // the RET instruction and handled by the FP Stackifier.
1444    if (VA.getLocReg() == X86::ST0 ||
1445        VA.getLocReg() == X86::ST1) {
1446      // If this is a copy from an xmm register to ST(0), use an FPExtend to
1447      // change the value to the FP stack register class.
1448      if (isScalarFPTypeInSSEReg(VA.getValVT()))
1449        ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
1450      RetOps.push_back(ValToCopy);
1451      // Don't emit a copytoreg.
1452      continue;
1453    }
1454
1455    // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
1456    // which is returned in RAX / RDX.
1457    if (Subtarget->is64Bit()) {
1458      if (ValVT == MVT::x86mmx) {
1459        if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1460          ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ValToCopy);
1461          ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
1462                                  ValToCopy);
1463          // If we don't have SSE2 available, convert to v4f32 so the generated
1464          // register is legal.
1465          if (!Subtarget->hasXMMInt())
1466            ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32,ValToCopy);
1467        }
1468      }
1469    }
1470
1471    Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
1472    Flag = Chain.getValue(1);
1473  }
1474
1475  // The x86-64 ABI for returning structs by value requires that we copy
1476  // the sret argument into %rax for the return. We saved the argument into
1477  // a virtual register in the entry block, so now we copy the value out
1478  // and into %rax.
1479  if (Subtarget->is64Bit() &&
1480      DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
1481    MachineFunction &MF = DAG.getMachineFunction();
1482    X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1483    unsigned Reg = FuncInfo->getSRetReturnReg();
1484    assert(Reg &&
1485           "SRetReturnReg should have been set in LowerFormalArguments().");
1486    SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
1487
1488    Chain = DAG.getCopyToReg(Chain, dl, X86::RAX, Val, Flag);
1489    Flag = Chain.getValue(1);
1490
1491    // RAX now acts like a return value.
1492    MRI.addLiveOut(X86::RAX);
1493  }
1494
1495  RetOps[0] = Chain;  // Update chain.
1496
1497  // Add the flag if we have it.
1498  if (Flag.getNode())
1499    RetOps.push_back(Flag);
1500
1501  return DAG.getNode(X86ISD::RET_FLAG, dl,
1502                     MVT::Other, &RetOps[0], RetOps.size());
1503}
1504
1505bool X86TargetLowering::isUsedByReturnOnly(SDNode *N) const {
1506  if (N->getNumValues() != 1)
1507    return false;
1508  if (!N->hasNUsesOfValue(1, 0))
1509    return false;
1510
1511  SDNode *Copy = *N->use_begin();
1512  if (Copy->getOpcode() != ISD::CopyToReg &&
1513      Copy->getOpcode() != ISD::FP_EXTEND)
1514    return false;
1515
1516  bool HasRet = false;
1517  for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
1518       UI != UE; ++UI) {
1519    if (UI->getOpcode() != X86ISD::RET_FLAG)
1520      return false;
1521    HasRet = true;
1522  }
1523
1524  return HasRet;
1525}
1526
1527EVT
1528X86TargetLowering::getTypeForExtArgOrReturn(LLVMContext &Context, EVT VT,
1529                                            ISD::NodeType ExtendKind) const {
1530  MVT ReturnMVT;
1531  // TODO: Is this also valid on 32-bit?
1532  if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
1533    ReturnMVT = MVT::i8;
1534  else
1535    ReturnMVT = MVT::i32;
1536
1537  EVT MinVT = getRegisterType(Context, ReturnMVT);
1538  return VT.bitsLT(MinVT) ? MinVT : VT;
1539}
1540
1541/// LowerCallResult - Lower the result values of a call into the
1542/// appropriate copies out of appropriate physical registers.
1543///
1544SDValue
1545X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1546                                   CallingConv::ID CallConv, bool isVarArg,
1547                                   const SmallVectorImpl<ISD::InputArg> &Ins,
1548                                   DebugLoc dl, SelectionDAG &DAG,
1549                                   SmallVectorImpl<SDValue> &InVals) const {
1550
1551  // Assign locations to each value returned by this call.
1552  SmallVector<CCValAssign, 16> RVLocs;
1553  bool Is64Bit = Subtarget->is64Bit();
1554  CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1555		 getTargetMachine(), RVLocs, *DAG.getContext());
1556  CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
1557
1558  // Copy all of the result registers out of their specified physreg.
1559  for (unsigned i = 0; i != RVLocs.size(); ++i) {
1560    CCValAssign &VA = RVLocs[i];
1561    EVT CopyVT = VA.getValVT();
1562
1563    // If this is x86-64, and we disabled SSE, we can't return FP values
1564    if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
1565        ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasXMM())) {
1566      report_fatal_error("SSE register return with SSE disabled");
1567    }
1568
1569    SDValue Val;
1570
1571    // If this is a call to a function that returns an fp value on the floating
1572    // point stack, we must guarantee the the value is popped from the stack, so
1573    // a CopyFromReg is not good enough - the copy instruction may be eliminated
1574    // if the return value is not used. We use the FpPOP_RETVAL instruction
1575    // instead.
1576    if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1) {
1577      // If we prefer to use the value in xmm registers, copy it out as f80 and
1578      // use a truncate to move it from fp stack reg to xmm reg.
1579      if (isScalarFPTypeInSSEReg(VA.getValVT())) CopyVT = MVT::f80;
1580      SDValue Ops[] = { Chain, InFlag };
1581      Chain = SDValue(DAG.getMachineNode(X86::FpPOP_RETVAL, dl, CopyVT,
1582                                         MVT::Other, MVT::Glue, Ops, 2), 1);
1583      Val = Chain.getValue(0);
1584
1585      // Round the f80 to the right size, which also moves it to the appropriate
1586      // xmm register.
1587      if (CopyVT != VA.getValVT())
1588        Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
1589                          // This truncation won't change the value.
1590                          DAG.getIntPtrConstant(1));
1591    } else {
1592      Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1593                                 CopyVT, InFlag).getValue(1);
1594      Val = Chain.getValue(0);
1595    }
1596    InFlag = Chain.getValue(2);
1597    InVals.push_back(Val);
1598  }
1599
1600  return Chain;
1601}
1602
1603
1604//===----------------------------------------------------------------------===//
1605//                C & StdCall & Fast Calling Convention implementation
1606//===----------------------------------------------------------------------===//
1607//  StdCall calling convention seems to be standard for many Windows' API
1608//  routines and around. It differs from C calling convention just a little:
1609//  callee should clean up the stack, not caller. Symbols should be also
1610//  decorated in some fancy way :) It doesn't support any vector arguments.
1611//  For info on fast calling convention see Fast Calling Convention (tail call)
1612//  implementation LowerX86_32FastCCCallTo.
1613
1614/// CallIsStructReturn - Determines whether a call uses struct return
1615/// semantics.
1616static bool CallIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
1617  if (Outs.empty())
1618    return false;
1619
1620  return Outs[0].Flags.isSRet();
1621}
1622
1623/// ArgsAreStructReturn - Determines whether a function uses struct
1624/// return semantics.
1625static bool
1626ArgsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
1627  if (Ins.empty())
1628    return false;
1629
1630  return Ins[0].Flags.isSRet();
1631}
1632
1633/// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
1634/// by "Src" to address "Dst" with size and alignment information specified by
1635/// the specific parameter attribute. The copy will be passed as a byval
1636/// function parameter.
1637static SDValue
1638CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
1639                          ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
1640                          DebugLoc dl) {
1641  SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
1642
1643  return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
1644                       /*isVolatile*/false, /*AlwaysInline=*/true,
1645                       MachinePointerInfo(), MachinePointerInfo());
1646}
1647
1648/// IsTailCallConvention - Return true if the calling convention is one that
1649/// supports tail call optimization.
1650static bool IsTailCallConvention(CallingConv::ID CC) {
1651  return (CC == CallingConv::Fast || CC == CallingConv::GHC);
1652}
1653
1654bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
1655  if (!CI->isTailCall())
1656    return false;
1657
1658  CallSite CS(CI);
1659  CallingConv::ID CalleeCC = CS.getCallingConv();
1660  if (!IsTailCallConvention(CalleeCC) && CalleeCC != CallingConv::C)
1661    return false;
1662
1663  return true;
1664}
1665
1666/// FuncIsMadeTailCallSafe - Return true if the function is being made into
1667/// a tailcall target by changing its ABI.
1668static bool FuncIsMadeTailCallSafe(CallingConv::ID CC) {
1669  return GuaranteedTailCallOpt && IsTailCallConvention(CC);
1670}
1671
1672SDValue
1673X86TargetLowering::LowerMemArgument(SDValue Chain,
1674                                    CallingConv::ID CallConv,
1675                                    const SmallVectorImpl<ISD::InputArg> &Ins,
1676                                    DebugLoc dl, SelectionDAG &DAG,
1677                                    const CCValAssign &VA,
1678                                    MachineFrameInfo *MFI,
1679                                    unsigned i) const {
1680  // Create the nodes corresponding to a load from this parameter slot.
1681  ISD::ArgFlagsTy Flags = Ins[i].Flags;
1682  bool AlwaysUseMutable = FuncIsMadeTailCallSafe(CallConv);
1683  bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
1684  EVT ValVT;
1685
1686  // If value is passed by pointer we have address passed instead of the value
1687  // itself.
1688  if (VA.getLocInfo() == CCValAssign::Indirect)
1689    ValVT = VA.getLocVT();
1690  else
1691    ValVT = VA.getValVT();
1692
1693  // FIXME: For now, all byval parameter objects are marked mutable. This can be
1694  // changed with more analysis.
1695  // In case of tail call optimization mark all arguments mutable. Since they
1696  // could be overwritten by lowering of arguments in case of a tail call.
1697  if (Flags.isByVal()) {
1698    unsigned Bytes = Flags.getByValSize();
1699    if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
1700    int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
1701    return DAG.getFrameIndex(FI, getPointerTy());
1702  } else {
1703    int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
1704                                    VA.getLocMemOffset(), isImmutable);
1705    SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
1706    return DAG.getLoad(ValVT, dl, Chain, FIN,
1707                       MachinePointerInfo::getFixedStack(FI),
1708                       false, false, 0);
1709  }
1710}
1711
1712SDValue
1713X86TargetLowering::LowerFormalArguments(SDValue Chain,
1714                                        CallingConv::ID CallConv,
1715                                        bool isVarArg,
1716                                      const SmallVectorImpl<ISD::InputArg> &Ins,
1717                                        DebugLoc dl,
1718                                        SelectionDAG &DAG,
1719                                        SmallVectorImpl<SDValue> &InVals)
1720                                          const {
1721  MachineFunction &MF = DAG.getMachineFunction();
1722  X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1723
1724  const Function* Fn = MF.getFunction();
1725  if (Fn->hasExternalLinkage() &&
1726      Subtarget->isTargetCygMing() &&
1727      Fn->getName() == "main")
1728    FuncInfo->setForceFramePointer(true);
1729
1730  MachineFrameInfo *MFI = MF.getFrameInfo();
1731  bool Is64Bit = Subtarget->is64Bit();
1732  bool IsWin64 = Subtarget->isTargetWin64();
1733
1734  assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
1735         "Var args not supported with calling convention fastcc or ghc");
1736
1737  // Assign locations to all of the incoming arguments.
1738  SmallVector<CCValAssign, 16> ArgLocs;
1739  CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1740                 ArgLocs, *DAG.getContext());
1741
1742  // Allocate shadow area for Win64
1743  if (IsWin64) {
1744    CCInfo.AllocateStack(32, 8);
1745  }
1746
1747  CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
1748
1749  unsigned LastVal = ~0U;
1750  SDValue ArgValue;
1751  for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1752    CCValAssign &VA = ArgLocs[i];
1753    // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
1754    // places.
1755    assert(VA.getValNo() != LastVal &&
1756           "Don't support value assigned to multiple locs yet");
1757    (void)LastVal;
1758    LastVal = VA.getValNo();
1759
1760    if (VA.isRegLoc()) {
1761      EVT RegVT = VA.getLocVT();
1762      TargetRegisterClass *RC = NULL;
1763      if (RegVT == MVT::i32)
1764        RC = X86::GR32RegisterClass;
1765      else if (Is64Bit && RegVT == MVT::i64)
1766        RC = X86::GR64RegisterClass;
1767      else if (RegVT == MVT::f32)
1768        RC = X86::FR32RegisterClass;
1769      else if (RegVT == MVT::f64)
1770        RC = X86::FR64RegisterClass;
1771      else if (RegVT.isVector() && RegVT.getSizeInBits() == 256)
1772        RC = X86::VR256RegisterClass;
1773      else if (RegVT.isVector() && RegVT.getSizeInBits() == 128)
1774        RC = X86::VR128RegisterClass;
1775      else if (RegVT == MVT::x86mmx)
1776        RC = X86::VR64RegisterClass;
1777      else
1778        llvm_unreachable("Unknown argument type!");
1779
1780      unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
1781      ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
1782
1783      // If this is an 8 or 16-bit value, it is really passed promoted to 32
1784      // bits.  Insert an assert[sz]ext to capture this, then truncate to the
1785      // right size.
1786      if (VA.getLocInfo() == CCValAssign::SExt)
1787        ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
1788                               DAG.getValueType(VA.getValVT()));
1789      else if (VA.getLocInfo() == CCValAssign::ZExt)
1790        ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
1791                               DAG.getValueType(VA.getValVT()));
1792      else if (VA.getLocInfo() == CCValAssign::BCvt)
1793        ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
1794
1795      if (VA.isExtInLoc()) {
1796        // Handle MMX values passed in XMM regs.
1797        if (RegVT.isVector()) {
1798          ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(),
1799                                 ArgValue);
1800        } else
1801          ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
1802      }
1803    } else {
1804      assert(VA.isMemLoc());
1805      ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
1806    }
1807
1808    // If value is passed via pointer - do a load.
1809    if (VA.getLocInfo() == CCValAssign::Indirect)
1810      ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
1811                             MachinePointerInfo(), false, false, 0);
1812
1813    InVals.push_back(ArgValue);
1814  }
1815
1816  // The x86-64 ABI for returning structs by value requires that we copy
1817  // the sret argument into %rax for the return. Save the argument into
1818  // a virtual register so that we can access it from the return points.
1819  if (Is64Bit && MF.getFunction()->hasStructRetAttr()) {
1820    X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1821    unsigned Reg = FuncInfo->getSRetReturnReg();
1822    if (!Reg) {
1823      Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(MVT::i64));
1824      FuncInfo->setSRetReturnReg(Reg);
1825    }
1826    SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[0]);
1827    Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
1828  }
1829
1830  unsigned StackSize = CCInfo.getNextStackOffset();
1831  // Align stack specially for tail calls.
1832  if (FuncIsMadeTailCallSafe(CallConv))
1833    StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
1834
1835  // If the function takes variable number of arguments, make a frame index for
1836  // the start of the first vararg value... for expansion of llvm.va_start.
1837  if (isVarArg) {
1838    if (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
1839                    CallConv != CallingConv::X86_ThisCall)) {
1840      FuncInfo->setVarArgsFrameIndex(MFI->CreateFixedObject(1, StackSize,true));
1841    }
1842    if (Is64Bit) {
1843      unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
1844
1845      // FIXME: We should really autogenerate these arrays
1846      static const unsigned GPR64ArgRegsWin64[] = {
1847        X86::RCX, X86::RDX, X86::R8,  X86::R9
1848      };
1849      static const unsigned GPR64ArgRegs64Bit[] = {
1850        X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
1851      };
1852      static const unsigned XMMArgRegs64Bit[] = {
1853        X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
1854        X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
1855      };
1856      const unsigned *GPR64ArgRegs;
1857      unsigned NumXMMRegs = 0;
1858
1859      if (IsWin64) {
1860        // The XMM registers which might contain var arg parameters are shadowed
1861        // in their paired GPR.  So we only need to save the GPR to their home
1862        // slots.
1863        TotalNumIntRegs = 4;
1864        GPR64ArgRegs = GPR64ArgRegsWin64;
1865      } else {
1866        TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
1867        GPR64ArgRegs = GPR64ArgRegs64Bit;
1868
1869        NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs64Bit, TotalNumXMMRegs);
1870      }
1871      unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
1872                                                       TotalNumIntRegs);
1873
1874      bool NoImplicitFloatOps = Fn->hasFnAttr(Attribute::NoImplicitFloat);
1875      assert(!(NumXMMRegs && !Subtarget->hasXMM()) &&
1876             "SSE register cannot be used when SSE is disabled!");
1877      assert(!(NumXMMRegs && UseSoftFloat && NoImplicitFloatOps) &&
1878             "SSE register cannot be used when SSE is disabled!");
1879      if (UseSoftFloat || NoImplicitFloatOps || !Subtarget->hasXMM())
1880        // Kernel mode asks for SSE to be disabled, so don't push them
1881        // on the stack.
1882        TotalNumXMMRegs = 0;
1883
1884      if (IsWin64) {
1885        const TargetFrameLowering &TFI = *getTargetMachine().getFrameLowering();
1886        // Get to the caller-allocated home save location.  Add 8 to account
1887        // for the return address.
1888        int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
1889        FuncInfo->setRegSaveFrameIndex(
1890          MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
1891        // Fixup to set vararg frame on shadow area (4 x i64).
1892        if (NumIntRegs < 4)
1893          FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
1894      } else {
1895        // For X86-64, if there are vararg parameters that are passed via
1896        // registers, then we must store them to their spots on the stack so they
1897        // may be loaded by deferencing the result of va_next.
1898        FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
1899        FuncInfo->setVarArgsFPOffset(TotalNumIntRegs * 8 + NumXMMRegs * 16);
1900        FuncInfo->setRegSaveFrameIndex(
1901          MFI->CreateStackObject(TotalNumIntRegs * 8 + TotalNumXMMRegs * 16, 16,
1902                               false));
1903      }
1904
1905      // Store the integer parameter registers.
1906      SmallVector<SDValue, 8> MemOps;
1907      SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
1908                                        getPointerTy());
1909      unsigned Offset = FuncInfo->getVarArgsGPOffset();
1910      for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
1911        SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
1912                                  DAG.getIntPtrConstant(Offset));
1913        unsigned VReg = MF.addLiveIn(GPR64ArgRegs[NumIntRegs],
1914                                     X86::GR64RegisterClass);
1915        SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
1916        SDValue Store =
1917          DAG.getStore(Val.getValue(1), dl, Val, FIN,
1918                       MachinePointerInfo::getFixedStack(
1919                         FuncInfo->getRegSaveFrameIndex(), Offset),
1920                       false, false, 0);
1921        MemOps.push_back(Store);
1922        Offset += 8;
1923      }
1924
1925      if (TotalNumXMMRegs != 0 && NumXMMRegs != TotalNumXMMRegs) {
1926        // Now store the XMM (fp + vector) parameter registers.
1927        SmallVector<SDValue, 11> SaveXMMOps;
1928        SaveXMMOps.push_back(Chain);
1929
1930        unsigned AL = MF.addLiveIn(X86::AL, X86::GR8RegisterClass);
1931        SDValue ALVal = DAG.getCopyFromReg(DAG.getEntryNode(), dl, AL, MVT::i8);
1932        SaveXMMOps.push_back(ALVal);
1933
1934        SaveXMMOps.push_back(DAG.getIntPtrConstant(
1935                               FuncInfo->getRegSaveFrameIndex()));
1936        SaveXMMOps.push_back(DAG.getIntPtrConstant(
1937                               FuncInfo->getVarArgsFPOffset()));
1938
1939        for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
1940          unsigned VReg = MF.addLiveIn(XMMArgRegs64Bit[NumXMMRegs],
1941                                       X86::VR128RegisterClass);
1942          SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::v4f32);
1943          SaveXMMOps.push_back(Val);
1944        }
1945        MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
1946                                     MVT::Other,
1947                                     &SaveXMMOps[0], SaveXMMOps.size()));
1948      }
1949
1950      if (!MemOps.empty())
1951        Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1952                            &MemOps[0], MemOps.size());
1953    }
1954  }
1955
1956  // Some CCs need callee pop.
1957  if (X86::isCalleePop(CallConv, Is64Bit, isVarArg, GuaranteedTailCallOpt)) {
1958    FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
1959  } else {
1960    FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
1961    // If this is an sret function, the return should pop the hidden pointer.
1962    if (!Is64Bit && !IsTailCallConvention(CallConv) && ArgsAreStructReturn(Ins))
1963      FuncInfo->setBytesToPopOnReturn(4);
1964  }
1965
1966  if (!Is64Bit) {
1967    // RegSaveFrameIndex is X86-64 only.
1968    FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
1969    if (CallConv == CallingConv::X86_FastCall ||
1970        CallConv == CallingConv::X86_ThisCall)
1971      // fastcc functions can't have varargs.
1972      FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
1973  }
1974
1975  FuncInfo->setArgumentStackSize(StackSize);
1976
1977  return Chain;
1978}
1979
1980SDValue
1981X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
1982                                    SDValue StackPtr, SDValue Arg,
1983                                    DebugLoc dl, SelectionDAG &DAG,
1984                                    const CCValAssign &VA,
1985                                    ISD::ArgFlagsTy Flags) const {
1986  unsigned LocMemOffset = VA.getLocMemOffset();
1987  SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
1988  PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
1989  if (Flags.isByVal())
1990    return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
1991
1992  return DAG.getStore(Chain, dl, Arg, PtrOff,
1993                      MachinePointerInfo::getStack(LocMemOffset),
1994                      false, false, 0);
1995}
1996
1997/// EmitTailCallLoadRetAddr - Emit a load of return address if tail call
1998/// optimization is performed and it is required.
1999SDValue
2000X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
2001                                           SDValue &OutRetAddr, SDValue Chain,
2002                                           bool IsTailCall, bool Is64Bit,
2003                                           int FPDiff, DebugLoc dl) const {
2004  // Adjust the Return address stack slot.
2005  EVT VT = getPointerTy();
2006  OutRetAddr = getReturnAddressFrameIndex(DAG);
2007
2008  // Load the "old" Return address.
2009  OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
2010                           false, false, 0);
2011  return SDValue(OutRetAddr.getNode(), 1);
2012}
2013
2014/// EmitTailCallStoreRetAddr - Emit a store of the return address if tail call
2015/// optimization is performed and it is required (FPDiff!=0).
2016static SDValue
2017EmitTailCallStoreRetAddr(SelectionDAG & DAG, MachineFunction &MF,
2018                         SDValue Chain, SDValue RetAddrFrIdx,
2019                         bool Is64Bit, int FPDiff, DebugLoc dl) {
2020  // Store the return address to the appropriate stack slot.
2021  if (!FPDiff) return Chain;
2022  // Calculate the new stack slot for the return address.
2023  int SlotSize = Is64Bit ? 8 : 4;
2024  int NewReturnAddrFI =
2025    MF.getFrameInfo()->CreateFixedObject(SlotSize, FPDiff-SlotSize, false);
2026  EVT VT = Is64Bit ? MVT::i64 : MVT::i32;
2027  SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, VT);
2028  Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
2029                       MachinePointerInfo::getFixedStack(NewReturnAddrFI),
2030                       false, false, 0);
2031  return Chain;
2032}
2033
2034SDValue
2035X86TargetLowering::LowerCall(SDValue Chain, SDValue Callee,
2036                             CallingConv::ID CallConv, bool isVarArg,
2037                             bool &isTailCall,
2038                             const SmallVectorImpl<ISD::OutputArg> &Outs,
2039                             const SmallVectorImpl<SDValue> &OutVals,
2040                             const SmallVectorImpl<ISD::InputArg> &Ins,
2041                             DebugLoc dl, SelectionDAG &DAG,
2042                             SmallVectorImpl<SDValue> &InVals) const {
2043  MachineFunction &MF = DAG.getMachineFunction();
2044  bool Is64Bit        = Subtarget->is64Bit();
2045  bool IsWin64        = Subtarget->isTargetWin64();
2046  bool IsStructRet    = CallIsStructReturn(Outs);
2047  bool IsSibcall      = false;
2048
2049  if (isTailCall) {
2050    // Check if it's really possible to do a tail call.
2051    isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
2052                    isVarArg, IsStructRet, MF.getFunction()->hasStructRetAttr(),
2053                                                   Outs, OutVals, Ins, DAG);
2054
2055    // Sibcalls are automatically detected tailcalls which do not require
2056    // ABI changes.
2057    if (!GuaranteedTailCallOpt && isTailCall)
2058      IsSibcall = true;
2059
2060    if (isTailCall)
2061      ++NumTailCalls;
2062  }
2063
2064  assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2065         "Var args not supported with calling convention fastcc or ghc");
2066
2067  // Analyze operands of the call, assigning locations to each operand.
2068  SmallVector<CCValAssign, 16> ArgLocs;
2069  CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
2070                 ArgLocs, *DAG.getContext());
2071
2072  // Allocate shadow area for Win64
2073  if (IsWin64) {
2074    CCInfo.AllocateStack(32, 8);
2075  }
2076
2077  CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2078
2079  // Get a count of how many bytes are to be pushed on the stack.
2080  unsigned NumBytes = CCInfo.getNextStackOffset();
2081  if (IsSibcall)
2082    // This is a sibcall. The memory operands are available in caller's
2083    // own caller's stack.
2084    NumBytes = 0;
2085  else if (GuaranteedTailCallOpt && IsTailCallConvention(CallConv))
2086    NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
2087
2088  int FPDiff = 0;
2089  if (isTailCall && !IsSibcall) {
2090    // Lower arguments at fp - stackoffset + fpdiff.
2091    unsigned NumBytesCallerPushed =
2092      MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn();
2093    FPDiff = NumBytesCallerPushed - NumBytes;
2094
2095    // Set the delta of movement of the returnaddr stackslot.
2096    // But only set if delta is greater than previous delta.
2097    if (FPDiff < (MF.getInfo<X86MachineFunctionInfo>()->getTCReturnAddrDelta()))
2098      MF.getInfo<X86MachineFunctionInfo>()->setTCReturnAddrDelta(FPDiff);
2099  }
2100
2101  if (!IsSibcall)
2102    Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true));
2103
2104  SDValue RetAddrFrIdx;
2105  // Load return address for tail calls.
2106  if (isTailCall && FPDiff)
2107    Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
2108                                    Is64Bit, FPDiff, dl);
2109
2110  SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2111  SmallVector<SDValue, 8> MemOpChains;
2112  SDValue StackPtr;
2113
2114  // Walk the register/memloc assignments, inserting copies/loads.  In the case
2115  // of tail call optimization arguments are handle later.
2116  for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2117    CCValAssign &VA = ArgLocs[i];
2118    EVT RegVT = VA.getLocVT();
2119    SDValue Arg = OutVals[i];
2120    ISD::ArgFlagsTy Flags = Outs[i].Flags;
2121    bool isByVal = Flags.isByVal();
2122
2123    // Promote the value if needed.
2124    switch (VA.getLocInfo()) {
2125    default: llvm_unreachable("Unknown loc info!");
2126    case CCValAssign::Full: break;
2127    case CCValAssign::SExt:
2128      Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
2129      break;
2130    case CCValAssign::ZExt:
2131      Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
2132      break;
2133    case CCValAssign::AExt:
2134      if (RegVT.isVector() && RegVT.getSizeInBits() == 128) {
2135        // Special case: passing MMX values in XMM registers.
2136        Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
2137        Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
2138        Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
2139      } else
2140        Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
2141      break;
2142    case CCValAssign::BCvt:
2143      Arg = DAG.getNode(ISD::BITCAST, dl, RegVT, Arg);
2144      break;
2145    case CCValAssign::Indirect: {
2146      // Store the argument.
2147      SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
2148      int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
2149      Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
2150                           MachinePointerInfo::getFixedStack(FI),
2151                           false, false, 0);
2152      Arg = SpillSlot;
2153      break;
2154    }
2155    }
2156
2157    if (VA.isRegLoc()) {
2158      RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2159      if (isVarArg && IsWin64) {
2160        // Win64 ABI requires argument XMM reg to be copied to the corresponding
2161        // shadow reg if callee is a varargs function.
2162        unsigned ShadowReg = 0;
2163        switch (VA.getLocReg()) {
2164        case X86::XMM0: ShadowReg = X86::RCX; break;
2165        case X86::XMM1: ShadowReg = X86::RDX; break;
2166        case X86::XMM2: ShadowReg = X86::R8; break;
2167        case X86::XMM3: ShadowReg = X86::R9; break;
2168        }
2169        if (ShadowReg)
2170          RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
2171      }
2172    } else if (!IsSibcall && (!isTailCall || isByVal)) {
2173      assert(VA.isMemLoc());
2174      if (StackPtr.getNode() == 0)
2175        StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr, getPointerTy());
2176      MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
2177                                             dl, DAG, VA, Flags));
2178    }
2179  }
2180
2181  if (!MemOpChains.empty())
2182    Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2183                        &MemOpChains[0], MemOpChains.size());
2184
2185  // Build a sequence of copy-to-reg nodes chained together with token chain
2186  // and flag operands which copy the outgoing args into registers.
2187  SDValue InFlag;
2188  // Tail call byval lowering might overwrite argument registers so in case of
2189  // tail call optimization the copies to registers are lowered later.
2190  if (!isTailCall)
2191    for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2192      Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2193                               RegsToPass[i].second, InFlag);
2194      InFlag = Chain.getValue(1);
2195    }
2196
2197  if (Subtarget->isPICStyleGOT()) {
2198    // ELF / PIC requires GOT in the EBX register before function calls via PLT
2199    // GOT pointer.
2200    if (!isTailCall) {
2201      Chain = DAG.getCopyToReg(Chain, dl, X86::EBX,
2202                               DAG.getNode(X86ISD::GlobalBaseReg,
2203                                           DebugLoc(), getPointerTy()),
2204                               InFlag);
2205      InFlag = Chain.getValue(1);
2206    } else {
2207      // If we are tail calling and generating PIC/GOT style code load the
2208      // address of the callee into ECX. The value in ecx is used as target of
2209      // the tail jump. This is done to circumvent the ebx/callee-saved problem
2210      // for tail calls on PIC/GOT architectures. Normally we would just put the
2211      // address of GOT into ebx and then call target@PLT. But for tail calls
2212      // ebx would be restored (since ebx is callee saved) before jumping to the
2213      // target@PLT.
2214
2215      // Note: The actual moving to ECX is done further down.
2216      GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2217      if (G && !G->getGlobal()->hasHiddenVisibility() &&
2218          !G->getGlobal()->hasProtectedVisibility())
2219        Callee = LowerGlobalAddress(Callee, DAG);
2220      else if (isa<ExternalSymbolSDNode>(Callee))
2221        Callee = LowerExternalSymbol(Callee, DAG);
2222    }
2223  }
2224
2225  if (Is64Bit && isVarArg && !IsWin64) {
2226    // From AMD64 ABI document:
2227    // For calls that may call functions that use varargs or stdargs
2228    // (prototype-less calls or calls to functions containing ellipsis (...) in
2229    // the declaration) %al is used as hidden argument to specify the number
2230    // of SSE registers used. The contents of %al do not need to match exactly
2231    // the number of registers, but must be an ubound on the number of SSE
2232    // registers used and is in the range 0 - 8 inclusive.
2233
2234    // Count the number of XMM registers allocated.
2235    static const unsigned XMMArgRegs[] = {
2236      X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2237      X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2238    };
2239    unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
2240    assert((Subtarget->hasXMM() || !NumXMMRegs)
2241           && "SSE registers cannot be used when SSE is disabled");
2242
2243    Chain = DAG.getCopyToReg(Chain, dl, X86::AL,
2244                             DAG.getConstant(NumXMMRegs, MVT::i8), InFlag);
2245    InFlag = Chain.getValue(1);
2246  }
2247
2248
2249  // For tail calls lower the arguments to the 'real' stack slot.
2250  if (isTailCall) {
2251    // Force all the incoming stack arguments to be loaded from the stack
2252    // before any new outgoing arguments are stored to the stack, because the
2253    // outgoing stack slots may alias the incoming argument stack slots, and
2254    // the alias isn't otherwise explicit. This is slightly more conservative
2255    // than necessary, because it means that each store effectively depends
2256    // on every argument instead of just those arguments it would clobber.
2257    SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
2258
2259    SmallVector<SDValue, 8> MemOpChains2;
2260    SDValue FIN;
2261    int FI = 0;
2262    // Do not flag preceding copytoreg stuff together with the following stuff.
2263    InFlag = SDValue();
2264    if (GuaranteedTailCallOpt) {
2265      for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2266        CCValAssign &VA = ArgLocs[i];
2267        if (VA.isRegLoc())
2268          continue;
2269        assert(VA.isMemLoc());
2270        SDValue Arg = OutVals[i];
2271        ISD::ArgFlagsTy Flags = Outs[i].Flags;
2272        // Create frame index.
2273        int32_t Offset = VA.getLocMemOffset()+FPDiff;
2274        uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
2275        FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
2276        FIN = DAG.getFrameIndex(FI, getPointerTy());
2277
2278        if (Flags.isByVal()) {
2279          // Copy relative to framepointer.
2280          SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
2281          if (StackPtr.getNode() == 0)
2282            StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr,
2283                                          getPointerTy());
2284          Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
2285
2286          MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
2287                                                           ArgChain,
2288                                                           Flags, DAG, dl));
2289        } else {
2290          // Store relative to framepointer.
2291          MemOpChains2.push_back(
2292            DAG.getStore(ArgChain, dl, Arg, FIN,
2293                         MachinePointerInfo::getFixedStack(FI),
2294                         false, false, 0));
2295        }
2296      }
2297    }
2298
2299    if (!MemOpChains2.empty())
2300      Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2301                          &MemOpChains2[0], MemOpChains2.size());
2302
2303    // Copy arguments to their registers.
2304    for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2305      Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2306                               RegsToPass[i].second, InFlag);
2307      InFlag = Chain.getValue(1);
2308    }
2309    InFlag =SDValue();
2310
2311    // Store the return address to the appropriate stack slot.
2312    Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx, Is64Bit,
2313                                     FPDiff, dl);
2314  }
2315
2316  if (getTargetMachine().getCodeModel() == CodeModel::Large) {
2317    assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
2318    // In the 64-bit large code model, we have to make all calls
2319    // through a register, since the call instruction's 32-bit
2320    // pc-relative offset may not be large enough to hold the whole
2321    // address.
2322  } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2323    // If the callee is a GlobalAddress node (quite common, every direct call
2324    // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
2325    // it.
2326
2327    // We should use extra load for direct calls to dllimported functions in
2328    // non-JIT mode.
2329    const GlobalValue *GV = G->getGlobal();
2330    if (!GV->hasDLLImportLinkage()) {
2331      unsigned char OpFlags = 0;
2332      bool ExtraLoad = false;
2333      unsigned WrapperKind = ISD::DELETED_NODE;
2334
2335      // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
2336      // external symbols most go through the PLT in PIC mode.  If the symbol
2337      // has hidden or protected visibility, or if it is static or local, then
2338      // we don't need to use the PLT - we can directly call it.
2339      if (Subtarget->isTargetELF() &&
2340          getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
2341          GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
2342        OpFlags = X86II::MO_PLT;
2343      } else if (Subtarget->isPICStyleStubAny() &&
2344                 (GV->isDeclaration() || GV->isWeakForLinker()) &&
2345                 (!Subtarget->getTargetTriple().isMacOSX() ||
2346                  Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2347        // PC-relative references to external symbols should go through $stub,
2348        // unless we're building with the leopard linker or later, which
2349        // automatically synthesizes these stubs.
2350        OpFlags = X86II::MO_DARWIN_STUB;
2351      } else if (Subtarget->isPICStyleRIPRel() &&
2352                 isa<Function>(GV) &&
2353                 cast<Function>(GV)->hasFnAttr(Attribute::NonLazyBind)) {
2354        // If the function is marked as non-lazy, generate an indirect call
2355        // which loads from the GOT directly. This avoids runtime overhead
2356        // at the cost of eager binding (and one extra byte of encoding).
2357        OpFlags = X86II::MO_GOTPCREL;
2358        WrapperKind = X86ISD::WrapperRIP;
2359        ExtraLoad = true;
2360      }
2361
2362      Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
2363                                          G->getOffset(), OpFlags);
2364
2365      // Add a wrapper if needed.
2366      if (WrapperKind != ISD::DELETED_NODE)
2367        Callee = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Callee);
2368      // Add extra indirection if needed.
2369      if (ExtraLoad)
2370        Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Callee,
2371                             MachinePointerInfo::getGOT(),
2372                             false, false, 0);
2373    }
2374  } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2375    unsigned char OpFlags = 0;
2376
2377    // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
2378    // external symbols should go through the PLT.
2379    if (Subtarget->isTargetELF() &&
2380        getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2381      OpFlags = X86II::MO_PLT;
2382    } else if (Subtarget->isPICStyleStubAny() &&
2383               (!Subtarget->getTargetTriple().isMacOSX() ||
2384                Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2385      // PC-relative references to external symbols should go through $stub,
2386      // unless we're building with the leopard linker or later, which
2387      // automatically synthesizes these stubs.
2388      OpFlags = X86II::MO_DARWIN_STUB;
2389    }
2390
2391    Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
2392                                         OpFlags);
2393  }
2394
2395  // Returns a chain & a flag for retval copy to use.
2396  SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2397  SmallVector<SDValue, 8> Ops;
2398
2399  if (!IsSibcall && isTailCall) {
2400    Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
2401                           DAG.getIntPtrConstant(0, true), InFlag);
2402    InFlag = Chain.getValue(1);
2403  }
2404
2405  Ops.push_back(Chain);
2406  Ops.push_back(Callee);
2407
2408  if (isTailCall)
2409    Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
2410
2411  // Add argument registers to the end of the list so that they are known live
2412  // into the call.
2413  for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2414    Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2415                                  RegsToPass[i].second.getValueType()));
2416
2417  // Add an implicit use GOT pointer in EBX.
2418  if (!isTailCall && Subtarget->isPICStyleGOT())
2419    Ops.push_back(DAG.getRegister(X86::EBX, getPointerTy()));
2420
2421  // Add an implicit use of AL for non-Windows x86 64-bit vararg functions.
2422  if (Is64Bit && isVarArg && !IsWin64)
2423    Ops.push_back(DAG.getRegister(X86::AL, MVT::i8));
2424
2425  if (InFlag.getNode())
2426    Ops.push_back(InFlag);
2427
2428  if (isTailCall) {
2429    // We used to do:
2430    //// If this is the first return lowered for this function, add the regs
2431    //// to the liveout set for the function.
2432    // This isn't right, although it's probably harmless on x86; liveouts
2433    // should be computed from returns not tail calls.  Consider a void
2434    // function making a tail call to a function returning int.
2435    return DAG.getNode(X86ISD::TC_RETURN, dl,
2436                       NodeTys, &Ops[0], Ops.size());
2437  }
2438
2439  Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, &Ops[0], Ops.size());
2440  InFlag = Chain.getValue(1);
2441
2442  // Create the CALLSEQ_END node.
2443  unsigned NumBytesForCalleeToPush;
2444  if (X86::isCalleePop(CallConv, Is64Bit, isVarArg, GuaranteedTailCallOpt))
2445    NumBytesForCalleeToPush = NumBytes;    // Callee pops everything
2446  else if (!Is64Bit && !IsTailCallConvention(CallConv) && IsStructRet)
2447    // If this is a call to a struct-return function, the callee
2448    // pops the hidden struct pointer, so we have to push it back.
2449    // This is common for Darwin/X86, Linux & Mingw32 targets.
2450    NumBytesForCalleeToPush = 4;
2451  else
2452    NumBytesForCalleeToPush = 0;  // Callee pops nothing.
2453
2454  // Returns a flag for retval copy to use.
2455  if (!IsSibcall) {
2456    Chain = DAG.getCALLSEQ_END(Chain,
2457                               DAG.getIntPtrConstant(NumBytes, true),
2458                               DAG.getIntPtrConstant(NumBytesForCalleeToPush,
2459                                                     true),
2460                               InFlag);
2461    InFlag = Chain.getValue(1);
2462  }
2463
2464  // Handle result values, copying them out of physregs into vregs that we
2465  // return.
2466  return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
2467                         Ins, dl, DAG, InVals);
2468}
2469
2470
2471//===----------------------------------------------------------------------===//
2472//                Fast Calling Convention (tail call) implementation
2473//===----------------------------------------------------------------------===//
2474
2475//  Like std call, callee cleans arguments, convention except that ECX is
2476//  reserved for storing the tail called function address. Only 2 registers are
2477//  free for argument passing (inreg). Tail call optimization is performed
2478//  provided:
2479//                * tailcallopt is enabled
2480//                * caller/callee are fastcc
2481//  On X86_64 architecture with GOT-style position independent code only local
2482//  (within module) calls are supported at the moment.
2483//  To keep the stack aligned according to platform abi the function
2484//  GetAlignedArgumentStackSize ensures that argument delta is always multiples
2485//  of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
2486//  If a tail called function callee has more arguments than the caller the
2487//  caller needs to make sure that there is room to move the RETADDR to. This is
2488//  achieved by reserving an area the size of the argument delta right after the
2489//  original REtADDR, but before the saved framepointer or the spilled registers
2490//  e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
2491//  stack layout:
2492//    arg1
2493//    arg2
2494//    RETADDR
2495//    [ new RETADDR
2496//      move area ]
2497//    (possible EBP)
2498//    ESI
2499//    EDI
2500//    local1 ..
2501
2502/// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
2503/// for a 16 byte align requirement.
2504unsigned
2505X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
2506                                               SelectionDAG& DAG) const {
2507  MachineFunction &MF = DAG.getMachineFunction();
2508  const TargetMachine &TM = MF.getTarget();
2509  const TargetFrameLowering &TFI = *TM.getFrameLowering();
2510  unsigned StackAlignment = TFI.getStackAlignment();
2511  uint64_t AlignMask = StackAlignment - 1;
2512  int64_t Offset = StackSize;
2513  uint64_t SlotSize = TD->getPointerSize();
2514  if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
2515    // Number smaller than 12 so just add the difference.
2516    Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
2517  } else {
2518    // Mask out lower bits, add stackalignment once plus the 12 bytes.
2519    Offset = ((~AlignMask) & Offset) + StackAlignment +
2520      (StackAlignment-SlotSize);
2521  }
2522  return Offset;
2523}
2524
2525/// MatchingStackOffset - Return true if the given stack call argument is
2526/// already available in the same position (relatively) of the caller's
2527/// incoming argument stack.
2528static
2529bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
2530                         MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
2531                         const X86InstrInfo *TII) {
2532  unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
2533  int FI = INT_MAX;
2534  if (Arg.getOpcode() == ISD::CopyFromReg) {
2535    unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
2536    if (!TargetRegisterInfo::isVirtualRegister(VR))
2537      return false;
2538    MachineInstr *Def = MRI->getVRegDef(VR);
2539    if (!Def)
2540      return false;
2541    if (!Flags.isByVal()) {
2542      if (!TII->isLoadFromStackSlot(Def, FI))
2543        return false;
2544    } else {
2545      unsigned Opcode = Def->getOpcode();
2546      if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r) &&
2547          Def->getOperand(1).isFI()) {
2548        FI = Def->getOperand(1).getIndex();
2549        Bytes = Flags.getByValSize();
2550      } else
2551        return false;
2552    }
2553  } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
2554    if (Flags.isByVal())
2555      // ByVal argument is passed in as a pointer but it's now being
2556      // dereferenced. e.g.
2557      // define @foo(%struct.X* %A) {
2558      //   tail call @bar(%struct.X* byval %A)
2559      // }
2560      return false;
2561    SDValue Ptr = Ld->getBasePtr();
2562    FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
2563    if (!FINode)
2564      return false;
2565    FI = FINode->getIndex();
2566  } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
2567    FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
2568    FI = FINode->getIndex();
2569    Bytes = Flags.getByValSize();
2570  } else
2571    return false;
2572
2573  assert(FI != INT_MAX);
2574  if (!MFI->isFixedObjectIndex(FI))
2575    return false;
2576  return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
2577}
2578
2579/// IsEligibleForTailCallOptimization - Check whether the call is eligible
2580/// for tail call optimization. Targets which want to do tail call
2581/// optimization should implement this function.
2582bool
2583X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
2584                                                     CallingConv::ID CalleeCC,
2585                                                     bool isVarArg,
2586                                                     bool isCalleeStructRet,
2587                                                     bool isCallerStructRet,
2588                                    const SmallVectorImpl<ISD::OutputArg> &Outs,
2589                                    const SmallVectorImpl<SDValue> &OutVals,
2590                                    const SmallVectorImpl<ISD::InputArg> &Ins,
2591                                                     SelectionDAG& DAG) const {
2592  if (!IsTailCallConvention(CalleeCC) &&
2593      CalleeCC != CallingConv::C)
2594    return false;
2595
2596  // If -tailcallopt is specified, make fastcc functions tail-callable.
2597  const MachineFunction &MF = DAG.getMachineFunction();
2598  const Function *CallerF = DAG.getMachineFunction().getFunction();
2599  CallingConv::ID CallerCC = CallerF->getCallingConv();
2600  bool CCMatch = CallerCC == CalleeCC;
2601
2602  if (GuaranteedTailCallOpt) {
2603    if (IsTailCallConvention(CalleeCC) && CCMatch)
2604      return true;
2605    return false;
2606  }
2607
2608  // Look for obvious safe cases to perform tail call optimization that do not
2609  // require ABI changes. This is what gcc calls sibcall.
2610
2611  // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
2612  // emit a special epilogue.
2613  if (RegInfo->needsStackRealignment(MF))
2614    return false;
2615
2616  // Also avoid sibcall optimization if either caller or callee uses struct
2617  // return semantics.
2618  if (isCalleeStructRet || isCallerStructRet)
2619    return false;
2620
2621  // An stdcall caller is expected to clean up its arguments; the callee
2622  // isn't going to do that.
2623  if (!CCMatch && CallerCC==CallingConv::X86_StdCall)
2624    return false;
2625
2626  // Do not sibcall optimize vararg calls unless all arguments are passed via
2627  // registers.
2628  if (isVarArg && !Outs.empty()) {
2629
2630    // Optimizing for varargs on Win64 is unlikely to be safe without
2631    // additional testing.
2632    if (Subtarget->isTargetWin64())
2633      return false;
2634
2635    SmallVector<CCValAssign, 16> ArgLocs;
2636    CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
2637		   getTargetMachine(), ArgLocs, *DAG.getContext());
2638
2639    CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2640    for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
2641      if (!ArgLocs[i].isRegLoc())
2642        return false;
2643  }
2644
2645  // If the call result is in ST0 / ST1, it needs to be popped off the x87 stack.
2646  // Therefore if it's not used by the call it is not safe to optimize this into
2647  // a sibcall.
2648  bool Unused = false;
2649  for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
2650    if (!Ins[i].Used) {
2651      Unused = true;
2652      break;
2653    }
2654  }
2655  if (Unused) {
2656    SmallVector<CCValAssign, 16> RVLocs;
2657    CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(),
2658		   getTargetMachine(), RVLocs, *DAG.getContext());
2659    CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2660    for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2661      CCValAssign &VA = RVLocs[i];
2662      if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1)
2663        return false;
2664    }
2665  }
2666
2667  // If the calling conventions do not match, then we'd better make sure the
2668  // results are returned in the same way as what the caller expects.
2669  if (!CCMatch) {
2670    SmallVector<CCValAssign, 16> RVLocs1;
2671    CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(),
2672		    getTargetMachine(), RVLocs1, *DAG.getContext());
2673    CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
2674
2675    SmallVector<CCValAssign, 16> RVLocs2;
2676    CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(),
2677		    getTargetMachine(), RVLocs2, *DAG.getContext());
2678    CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
2679
2680    if (RVLocs1.size() != RVLocs2.size())
2681      return false;
2682    for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
2683      if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
2684        return false;
2685      if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
2686        return false;
2687      if (RVLocs1[i].isRegLoc()) {
2688        if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
2689          return false;
2690      } else {
2691        if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
2692          return false;
2693      }
2694    }
2695  }
2696
2697  // If the callee takes no arguments then go on to check the results of the
2698  // call.
2699  if (!Outs.empty()) {
2700    // Check if stack adjustment is needed. For now, do not do this if any
2701    // argument is passed on the stack.
2702    SmallVector<CCValAssign, 16> ArgLocs;
2703    CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
2704		   getTargetMachine(), ArgLocs, *DAG.getContext());
2705
2706    // Allocate shadow area for Win64
2707    if (Subtarget->isTargetWin64()) {
2708      CCInfo.AllocateStack(32, 8);
2709    }
2710
2711    CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2712    if (CCInfo.getNextStackOffset()) {
2713      MachineFunction &MF = DAG.getMachineFunction();
2714      if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
2715        return false;
2716
2717      // Check if the arguments are already laid out in the right way as
2718      // the caller's fixed stack objects.
2719      MachineFrameInfo *MFI = MF.getFrameInfo();
2720      const MachineRegisterInfo *MRI = &MF.getRegInfo();
2721      const X86InstrInfo *TII =
2722        ((X86TargetMachine&)getTargetMachine()).getInstrInfo();
2723      for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2724        CCValAssign &VA = ArgLocs[i];
2725        SDValue Arg = OutVals[i];
2726        ISD::ArgFlagsTy Flags = Outs[i].Flags;
2727        if (VA.getLocInfo() == CCValAssign::Indirect)
2728          return false;
2729        if (!VA.isRegLoc()) {
2730          if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2731                                   MFI, MRI, TII))
2732            return false;
2733        }
2734      }
2735    }
2736
2737    // If the tailcall address may be in a register, then make sure it's
2738    // possible to register allocate for it. In 32-bit, the call address can
2739    // only target EAX, EDX, or ECX since the tail call must be scheduled after
2740    // callee-saved registers are restored. These happen to be the same
2741    // registers used to pass 'inreg' arguments so watch out for those.
2742    if (!Subtarget->is64Bit() &&
2743        !isa<GlobalAddressSDNode>(Callee) &&
2744        !isa<ExternalSymbolSDNode>(Callee)) {
2745      unsigned NumInRegs = 0;
2746      for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2747        CCValAssign &VA = ArgLocs[i];
2748        if (!VA.isRegLoc())
2749          continue;
2750        unsigned Reg = VA.getLocReg();
2751        switch (Reg) {
2752        default: break;
2753        case X86::EAX: case X86::EDX: case X86::ECX:
2754          if (++NumInRegs == 3)
2755            return false;
2756          break;
2757        }
2758      }
2759    }
2760  }
2761
2762  return true;
2763}
2764
2765FastISel *
2766X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo) const {
2767  return X86::createFastISel(funcInfo);
2768}
2769
2770
2771//===----------------------------------------------------------------------===//
2772//                           Other Lowering Hooks
2773//===----------------------------------------------------------------------===//
2774
2775static bool MayFoldLoad(SDValue Op) {
2776  return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
2777}
2778
2779static bool MayFoldIntoStore(SDValue Op) {
2780  return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
2781}
2782
2783static bool isTargetShuffle(unsigned Opcode) {
2784  switch(Opcode) {
2785  default: return false;
2786  case X86ISD::PSHUFD:
2787  case X86ISD::PSHUFHW:
2788  case X86ISD::PSHUFLW:
2789  case X86ISD::SHUFPD:
2790  case X86ISD::PALIGN:
2791  case X86ISD::SHUFPS:
2792  case X86ISD::MOVLHPS:
2793  case X86ISD::MOVLHPD:
2794  case X86ISD::MOVHLPS:
2795  case X86ISD::MOVLPS:
2796  case X86ISD::MOVLPD:
2797  case X86ISD::MOVSHDUP:
2798  case X86ISD::MOVSLDUP:
2799  case X86ISD::MOVDDUP:
2800  case X86ISD::MOVSS:
2801  case X86ISD::MOVSD:
2802  case X86ISD::UNPCKLPS:
2803  case X86ISD::UNPCKLPD:
2804  case X86ISD::VUNPCKLPSY:
2805  case X86ISD::VUNPCKLPDY:
2806  case X86ISD::PUNPCKLWD:
2807  case X86ISD::PUNPCKLBW:
2808  case X86ISD::PUNPCKLDQ:
2809  case X86ISD::PUNPCKLQDQ:
2810  case X86ISD::UNPCKHPS:
2811  case X86ISD::UNPCKHPD:
2812  case X86ISD::VUNPCKHPSY:
2813  case X86ISD::VUNPCKHPDY:
2814  case X86ISD::PUNPCKHWD:
2815  case X86ISD::PUNPCKHBW:
2816  case X86ISD::PUNPCKHDQ:
2817  case X86ISD::PUNPCKHQDQ:
2818  case X86ISD::VPERMILPS:
2819  case X86ISD::VPERMILPSY:
2820  case X86ISD::VPERMILPD:
2821  case X86ISD::VPERMILPDY:
2822  case X86ISD::VPERM2F128:
2823    return true;
2824  }
2825  return false;
2826}
2827
2828static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2829                                               SDValue V1, SelectionDAG &DAG) {
2830  switch(Opc) {
2831  default: llvm_unreachable("Unknown x86 shuffle node");
2832  case X86ISD::MOVSHDUP:
2833  case X86ISD::MOVSLDUP:
2834  case X86ISD::MOVDDUP:
2835    return DAG.getNode(Opc, dl, VT, V1);
2836  }
2837
2838  return SDValue();
2839}
2840
2841static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2842                          SDValue V1, unsigned TargetMask, SelectionDAG &DAG) {
2843  switch(Opc) {
2844  default: llvm_unreachable("Unknown x86 shuffle node");
2845  case X86ISD::PSHUFD:
2846  case X86ISD::PSHUFHW:
2847  case X86ISD::PSHUFLW:
2848  case X86ISD::VPERMILPS:
2849  case X86ISD::VPERMILPSY:
2850  case X86ISD::VPERMILPD:
2851  case X86ISD::VPERMILPDY:
2852    return DAG.getNode(Opc, dl, VT, V1, DAG.getConstant(TargetMask, MVT::i8));
2853  }
2854
2855  return SDValue();
2856}
2857
2858static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2859               SDValue V1, SDValue V2, unsigned TargetMask, SelectionDAG &DAG) {
2860  switch(Opc) {
2861  default: llvm_unreachable("Unknown x86 shuffle node");
2862  case X86ISD::PALIGN:
2863  case X86ISD::SHUFPD:
2864  case X86ISD::SHUFPS:
2865  case X86ISD::VPERM2F128:
2866    return DAG.getNode(Opc, dl, VT, V1, V2,
2867                       DAG.getConstant(TargetMask, MVT::i8));
2868  }
2869  return SDValue();
2870}
2871
2872static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2873                                    SDValue V1, SDValue V2, SelectionDAG &DAG) {
2874  switch(Opc) {
2875  default: llvm_unreachable("Unknown x86 shuffle node");
2876  case X86ISD::MOVLHPS:
2877  case X86ISD::MOVLHPD:
2878  case X86ISD::MOVHLPS:
2879  case X86ISD::MOVLPS:
2880  case X86ISD::MOVLPD:
2881  case X86ISD::MOVSS:
2882  case X86ISD::MOVSD:
2883  case X86ISD::UNPCKLPS:
2884  case X86ISD::UNPCKLPD:
2885  case X86ISD::VUNPCKLPSY:
2886  case X86ISD::VUNPCKLPDY:
2887  case X86ISD::PUNPCKLWD:
2888  case X86ISD::PUNPCKLBW:
2889  case X86ISD::PUNPCKLDQ:
2890  case X86ISD::PUNPCKLQDQ:
2891  case X86ISD::UNPCKHPS:
2892  case X86ISD::UNPCKHPD:
2893  case X86ISD::VUNPCKHPSY:
2894  case X86ISD::VUNPCKHPDY:
2895  case X86ISD::PUNPCKHWD:
2896  case X86ISD::PUNPCKHBW:
2897  case X86ISD::PUNPCKHDQ:
2898  case X86ISD::PUNPCKHQDQ:
2899    return DAG.getNode(Opc, dl, VT, V1, V2);
2900  }
2901  return SDValue();
2902}
2903
2904SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
2905  MachineFunction &MF = DAG.getMachineFunction();
2906  X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2907  int ReturnAddrIndex = FuncInfo->getRAIndex();
2908
2909  if (ReturnAddrIndex == 0) {
2910    // Set up a frame object for the return address.
2911    uint64_t SlotSize = TD->getPointerSize();
2912    ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize, -SlotSize,
2913                                                           false);
2914    FuncInfo->setRAIndex(ReturnAddrIndex);
2915  }
2916
2917  return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
2918}
2919
2920
2921bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
2922                                       bool hasSymbolicDisplacement) {
2923  // Offset should fit into 32 bit immediate field.
2924  if (!isInt<32>(Offset))
2925    return false;
2926
2927  // If we don't have a symbolic displacement - we don't have any extra
2928  // restrictions.
2929  if (!hasSymbolicDisplacement)
2930    return true;
2931
2932  // FIXME: Some tweaks might be needed for medium code model.
2933  if (M != CodeModel::Small && M != CodeModel::Kernel)
2934    return false;
2935
2936  // For small code model we assume that latest object is 16MB before end of 31
2937  // bits boundary. We may also accept pretty large negative constants knowing
2938  // that all objects are in the positive half of address space.
2939  if (M == CodeModel::Small && Offset < 16*1024*1024)
2940    return true;
2941
2942  // For kernel code model we know that all object resist in the negative half
2943  // of 32bits address space. We may not accept negative offsets, since they may
2944  // be just off and we may accept pretty large positive ones.
2945  if (M == CodeModel::Kernel && Offset > 0)
2946    return true;
2947
2948  return false;
2949}
2950
2951/// isCalleePop - Determines whether the callee is required to pop its
2952/// own arguments. Callee pop is necessary to support tail calls.
2953bool X86::isCalleePop(CallingConv::ID CallingConv,
2954                      bool is64Bit, bool IsVarArg, bool TailCallOpt) {
2955  if (IsVarArg)
2956    return false;
2957
2958  switch (CallingConv) {
2959  default:
2960    return false;
2961  case CallingConv::X86_StdCall:
2962    return !is64Bit;
2963  case CallingConv::X86_FastCall:
2964    return !is64Bit;
2965  case CallingConv::X86_ThisCall:
2966    return !is64Bit;
2967  case CallingConv::Fast:
2968    return TailCallOpt;
2969  case CallingConv::GHC:
2970    return TailCallOpt;
2971  }
2972}
2973
2974/// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
2975/// specific condition code, returning the condition code and the LHS/RHS of the
2976/// comparison to make.
2977static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
2978                               SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
2979  if (!isFP) {
2980    if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
2981      if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
2982        // X > -1   -> X == 0, jump !sign.
2983        RHS = DAG.getConstant(0, RHS.getValueType());
2984        return X86::COND_NS;
2985      } else if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
2986        // X < 0   -> X == 0, jump on sign.
2987        return X86::COND_S;
2988      } else if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
2989        // X < 1   -> X <= 0
2990        RHS = DAG.getConstant(0, RHS.getValueType());
2991        return X86::COND_LE;
2992      }
2993    }
2994
2995    switch (SetCCOpcode) {
2996    default: llvm_unreachable("Invalid integer condition!");
2997    case ISD::SETEQ:  return X86::COND_E;
2998    case ISD::SETGT:  return X86::COND_G;
2999    case ISD::SETGE:  return X86::COND_GE;
3000    case ISD::SETLT:  return X86::COND_L;
3001    case ISD::SETLE:  return X86::COND_LE;
3002    case ISD::SETNE:  return X86::COND_NE;
3003    case ISD::SETULT: return X86::COND_B;
3004    case ISD::SETUGT: return X86::COND_A;
3005    case ISD::SETULE: return X86::COND_BE;
3006    case ISD::SETUGE: return X86::COND_AE;
3007    }
3008  }
3009
3010  // First determine if it is required or is profitable to flip the operands.
3011
3012  // If LHS is a foldable load, but RHS is not, flip the condition.
3013  if (ISD::isNON_EXTLoad(LHS.getNode()) &&
3014      !ISD::isNON_EXTLoad(RHS.getNode())) {
3015    SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
3016    std::swap(LHS, RHS);
3017  }
3018
3019  switch (SetCCOpcode) {
3020  default: break;
3021  case ISD::SETOLT:
3022  case ISD::SETOLE:
3023  case ISD::SETUGT:
3024  case ISD::SETUGE:
3025    std::swap(LHS, RHS);
3026    break;
3027  }
3028
3029  // On a floating point condition, the flags are set as follows:
3030  // ZF  PF  CF   op
3031  //  0 | 0 | 0 | X > Y
3032  //  0 | 0 | 1 | X < Y
3033  //  1 | 0 | 0 | X == Y
3034  //  1 | 1 | 1 | unordered
3035  switch (SetCCOpcode) {
3036  default: llvm_unreachable("Condcode should be pre-legalized away");
3037  case ISD::SETUEQ:
3038  case ISD::SETEQ:   return X86::COND_E;
3039  case ISD::SETOLT:              // flipped
3040  case ISD::SETOGT:
3041  case ISD::SETGT:   return X86::COND_A;
3042  case ISD::SETOLE:              // flipped
3043  case ISD::SETOGE:
3044  case ISD::SETGE:   return X86::COND_AE;
3045  case ISD::SETUGT:              // flipped
3046  case ISD::SETULT:
3047  case ISD::SETLT:   return X86::COND_B;
3048  case ISD::SETUGE:              // flipped
3049  case ISD::SETULE:
3050  case ISD::SETLE:   return X86::COND_BE;
3051  case ISD::SETONE:
3052  case ISD::SETNE:   return X86::COND_NE;
3053  case ISD::SETUO:   return X86::COND_P;
3054  case ISD::SETO:    return X86::COND_NP;
3055  case ISD::SETOEQ:
3056  case ISD::SETUNE:  return X86::COND_INVALID;
3057  }
3058}
3059
3060/// hasFPCMov - is there a floating point cmov for the specific X86 condition
3061/// code. Current x86 isa includes the following FP cmov instructions:
3062/// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
3063static bool hasFPCMov(unsigned X86CC) {
3064  switch (X86CC) {
3065  default:
3066    return false;
3067  case X86::COND_B:
3068  case X86::COND_BE:
3069  case X86::COND_E:
3070  case X86::COND_P:
3071  case X86::COND_A:
3072  case X86::COND_AE:
3073  case X86::COND_NE:
3074  case X86::COND_NP:
3075    return true;
3076  }
3077}
3078
3079/// isFPImmLegal - Returns true if the target can instruction select the
3080/// specified FP immediate natively. If false, the legalizer will
3081/// materialize the FP immediate as a load from a constant pool.
3082bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3083  for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
3084    if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
3085      return true;
3086  }
3087  return false;
3088}
3089
3090/// isUndefOrInRange - Return true if Val is undef or if its value falls within
3091/// the specified range (L, H].
3092static bool isUndefOrInRange(int Val, int Low, int Hi) {
3093  return (Val < 0) || (Val >= Low && Val < Hi);
3094}
3095
3096/// isUndefOrInRange - Return true if every element in Mask, begining
3097/// from position Pos and ending in Pos+Size, falls within the specified
3098/// range (L, L+Pos]. or is undef.
3099static bool isUndefOrInRange(const SmallVectorImpl<int> &Mask,
3100                             int Pos, int Size, int Low, int Hi) {
3101  for (int i = Pos, e = Pos+Size; i != e; ++i)
3102    if (!isUndefOrInRange(Mask[i], Low, Hi))
3103      return false;
3104  return true;
3105}
3106
3107/// isUndefOrEqual - Val is either less than zero (undef) or equal to the
3108/// specified value.
3109static bool isUndefOrEqual(int Val, int CmpVal) {
3110  if (Val < 0 || Val == CmpVal)
3111    return true;
3112  return false;
3113}
3114
3115/// isSequentialOrUndefInRange - Return true if every element in Mask, begining
3116/// from position Pos and ending in Pos+Size, falls within the specified
3117/// sequential range (L, L+Pos]. or is undef.
3118static bool isSequentialOrUndefInRange(const SmallVectorImpl<int> &Mask,
3119                                       int Pos, int Size, int Low) {
3120  for (int i = Pos, e = Pos+Size; i != e; ++i, ++Low)
3121    if (!isUndefOrEqual(Mask[i], Low))
3122      return false;
3123  return true;
3124}
3125
3126/// isPSHUFDMask - Return true if the node specifies a shuffle of elements that
3127/// is suitable for input to PSHUFD or PSHUFW.  That is, it doesn't reference
3128/// the second operand.
3129static bool isPSHUFDMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3130  if (VT == MVT::v4f32 || VT == MVT::v4i32 )
3131    return (Mask[0] < 4 && Mask[1] < 4 && Mask[2] < 4 && Mask[3] < 4);
3132  if (VT == MVT::v2f64 || VT == MVT::v2i64)
3133    return (Mask[0] < 2 && Mask[1] < 2);
3134  return false;
3135}
3136
3137bool X86::isPSHUFDMask(ShuffleVectorSDNode *N) {
3138  SmallVector<int, 8> M;
3139  N->getMask(M);
3140  return ::isPSHUFDMask(M, N->getValueType(0));
3141}
3142
3143/// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that
3144/// is suitable for input to PSHUFHW.
3145static bool isPSHUFHWMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3146  if (VT != MVT::v8i16)
3147    return false;
3148
3149  // Lower quadword copied in order or undef.
3150  for (int i = 0; i != 4; ++i)
3151    if (Mask[i] >= 0 && Mask[i] != i)
3152      return false;
3153
3154  // Upper quadword shuffled.
3155  for (int i = 4; i != 8; ++i)
3156    if (Mask[i] >= 0 && (Mask[i] < 4 || Mask[i] > 7))
3157      return false;
3158
3159  return true;
3160}
3161
3162bool X86::isPSHUFHWMask(ShuffleVectorSDNode *N) {
3163  SmallVector<int, 8> M;
3164  N->getMask(M);
3165  return ::isPSHUFHWMask(M, N->getValueType(0));
3166}
3167
3168/// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that
3169/// is suitable for input to PSHUFLW.
3170static bool isPSHUFLWMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3171  if (VT != MVT::v8i16)
3172    return false;
3173
3174  // Upper quadword copied in order.
3175  for (int i = 4; i != 8; ++i)
3176    if (Mask[i] >= 0 && Mask[i] != i)
3177      return false;
3178
3179  // Lower quadword shuffled.
3180  for (int i = 0; i != 4; ++i)
3181    if (Mask[i] >= 4)
3182      return false;
3183
3184  return true;
3185}
3186
3187bool X86::isPSHUFLWMask(ShuffleVectorSDNode *N) {
3188  SmallVector<int, 8> M;
3189  N->getMask(M);
3190  return ::isPSHUFLWMask(M, N->getValueType(0));
3191}
3192
3193/// isPALIGNRMask - Return true if the node specifies a shuffle of elements that
3194/// is suitable for input to PALIGNR.
3195static bool isPALIGNRMask(const SmallVectorImpl<int> &Mask, EVT VT,
3196                          bool hasSSSE3OrAVX) {
3197  int i, e = VT.getVectorNumElements();
3198  if (VT.getSizeInBits() != 128 && VT.getSizeInBits() != 64)
3199    return false;
3200
3201  // Do not handle v2i64 / v2f64 shuffles with palignr.
3202  if (e < 4 || !hasSSSE3OrAVX)
3203    return false;
3204
3205  for (i = 0; i != e; ++i)
3206    if (Mask[i] >= 0)
3207      break;
3208
3209  // All undef, not a palignr.
3210  if (i == e)
3211    return false;
3212
3213  // Make sure we're shifting in the right direction.
3214  if (Mask[i] <= i)
3215    return false;
3216
3217  int s = Mask[i] - i;
3218
3219  // Check the rest of the elements to see if they are consecutive.
3220  for (++i; i != e; ++i) {
3221    int m = Mask[i];
3222    if (m >= 0 && m != s+i)
3223      return false;
3224  }
3225  return true;
3226}
3227
3228/// isVSHUFPSYMask - Return true if the specified VECTOR_SHUFFLE operand
3229/// specifies a shuffle of elements that is suitable for input to 256-bit
3230/// VSHUFPSY.
3231static bool isVSHUFPSYMask(const SmallVectorImpl<int> &Mask, EVT VT,
3232                          const X86Subtarget *Subtarget) {
3233  int NumElems = VT.getVectorNumElements();
3234
3235  if (!Subtarget->hasAVX() || VT.getSizeInBits() != 256)
3236    return false;
3237
3238  if (NumElems != 8)
3239    return false;
3240
3241  // VSHUFPSY divides the resulting vector into 4 chunks.
3242  // The sources are also splitted into 4 chunks, and each destination
3243  // chunk must come from a different source chunk.
3244  //
3245  //  SRC1 =>   X7    X6    X5    X4    X3    X2    X1    X0
3246  //  SRC2 =>   Y7    Y6    Y5    Y4    Y3    Y2    Y1    Y9
3247  //
3248  //  DST  =>  Y7..Y4,   Y7..Y4,   X7..X4,   X7..X4,
3249  //           Y3..Y0,   Y3..Y0,   X3..X0,   X3..X0
3250  //
3251  int QuarterSize = NumElems/4;
3252  int HalfSize = QuarterSize*2;
3253  for (int i = 0; i < QuarterSize; ++i)
3254    if (!isUndefOrInRange(Mask[i], 0, HalfSize))
3255      return false;
3256  for (int i = QuarterSize; i < QuarterSize*2; ++i)
3257    if (!isUndefOrInRange(Mask[i], NumElems, NumElems+HalfSize))
3258      return false;
3259
3260  // The mask of the second half must be the same as the first but with
3261  // the appropriate offsets. This works in the same way as VPERMILPS
3262  // works with masks.
3263  for (int i = QuarterSize*2; i < QuarterSize*3; ++i) {
3264    if (!isUndefOrInRange(Mask[i], HalfSize, NumElems))
3265      return false;
3266    int FstHalfIdx = i-HalfSize;
3267    if (Mask[FstHalfIdx] < 0)
3268      continue;
3269    if (!isUndefOrEqual(Mask[i], Mask[FstHalfIdx]+HalfSize))
3270      return false;
3271  }
3272  for (int i = QuarterSize*3; i < NumElems; ++i) {
3273    if (!isUndefOrInRange(Mask[i], NumElems+HalfSize, NumElems*2))
3274      return false;
3275    int FstHalfIdx = i-HalfSize;
3276    if (Mask[FstHalfIdx] < 0)
3277      continue;
3278    if (!isUndefOrEqual(Mask[i], Mask[FstHalfIdx]+HalfSize))
3279      return false;
3280
3281  }
3282
3283  return true;
3284}
3285
3286/// getShuffleVSHUFPSYImmediate - Return the appropriate immediate to shuffle
3287/// the specified VECTOR_MASK mask with VSHUFPSY instruction.
3288static unsigned getShuffleVSHUFPSYImmediate(SDNode *N) {
3289  ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3290  EVT VT = SVOp->getValueType(0);
3291  int NumElems = VT.getVectorNumElements();
3292
3293  assert(NumElems == 8 && VT.getSizeInBits() == 256 &&
3294         "Only supports v8i32 and v8f32 types");
3295
3296  int HalfSize = NumElems/2;
3297  unsigned Mask = 0;
3298  for (int i = 0; i != NumElems ; ++i) {
3299    if (SVOp->getMaskElt(i) < 0)
3300      continue;
3301    // The mask of the first half must be equal to the second one.
3302    unsigned Shamt = (i%HalfSize)*2;
3303    unsigned Elt = SVOp->getMaskElt(i) % HalfSize;
3304    Mask |= Elt << Shamt;
3305  }
3306
3307  return Mask;
3308}
3309
3310/// isVSHUFPDYMask - Return true if the specified VECTOR_SHUFFLE operand
3311/// specifies a shuffle of elements that is suitable for input to 256-bit
3312/// VSHUFPDY. This shuffle doesn't have the same restriction as the PS
3313/// version and the mask of the second half isn't binded with the first
3314/// one.
3315static bool isVSHUFPDYMask(const SmallVectorImpl<int> &Mask, EVT VT,
3316                           const X86Subtarget *Subtarget) {
3317  int NumElems = VT.getVectorNumElements();
3318
3319  if (!Subtarget->hasAVX() || VT.getSizeInBits() != 256)
3320    return false;
3321
3322  if (NumElems != 4)
3323    return false;
3324
3325  // VSHUFPSY divides the resulting vector into 4 chunks.
3326  // The sources are also splitted into 4 chunks, and each destination
3327  // chunk must come from a different source chunk.
3328  //
3329  //  SRC1 =>      X3       X2       X1       X0
3330  //  SRC2 =>      Y3       Y2       Y1       Y0
3331  //
3332  //  DST  =>  Y2..Y3,  X2..X3,  Y1..Y0,  X1..X0
3333  //
3334  int QuarterSize = NumElems/4;
3335  int HalfSize = QuarterSize*2;
3336  for (int i = 0; i < QuarterSize; ++i)
3337    if (!isUndefOrInRange(Mask[i], 0, HalfSize))
3338      return false;
3339  for (int i = QuarterSize; i < QuarterSize*2; ++i)
3340    if (!isUndefOrInRange(Mask[i], NumElems, NumElems+HalfSize))
3341      return false;
3342  for (int i = QuarterSize*2; i < QuarterSize*3; ++i)
3343    if (!isUndefOrInRange(Mask[i], HalfSize, NumElems))
3344      return false;
3345  for (int i = QuarterSize*3; i < NumElems; ++i)
3346    if (!isUndefOrInRange(Mask[i], NumElems+HalfSize, NumElems*2))
3347      return false;
3348
3349  return true;
3350}
3351
3352/// getShuffleVSHUFPDYImmediate - Return the appropriate immediate to shuffle
3353/// the specified VECTOR_MASK mask with VSHUFPDY instruction.
3354static unsigned getShuffleVSHUFPDYImmediate(SDNode *N) {
3355  ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3356  EVT VT = SVOp->getValueType(0);
3357  int NumElems = VT.getVectorNumElements();
3358
3359  assert(NumElems == 4 && VT.getSizeInBits() == 256 &&
3360         "Only supports v4i64 and v4f64 types");
3361
3362  int HalfSize = NumElems/2;
3363  unsigned Mask = 0;
3364  for (int i = 0; i != NumElems ; ++i) {
3365    if (SVOp->getMaskElt(i) < 0)
3366      continue;
3367    int Elt = SVOp->getMaskElt(i) % HalfSize;
3368    Mask |= Elt << i;
3369  }
3370
3371  return Mask;
3372}
3373
3374/// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
3375/// specifies a shuffle of elements that is suitable for input to 128-bit
3376/// SHUFPS and SHUFPD.
3377static bool isSHUFPMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3378  int NumElems = VT.getVectorNumElements();
3379
3380  if (VT.getSizeInBits() != 128)
3381    return false;
3382
3383  if (NumElems != 2 && NumElems != 4)
3384    return false;
3385
3386  int Half = NumElems / 2;
3387  for (int i = 0; i < Half; ++i)
3388    if (!isUndefOrInRange(Mask[i], 0, NumElems))
3389      return false;
3390  for (int i = Half; i < NumElems; ++i)
3391    if (!isUndefOrInRange(Mask[i], NumElems, NumElems*2))
3392      return false;
3393
3394  return true;
3395}
3396
3397bool X86::isSHUFPMask(ShuffleVectorSDNode *N) {
3398  SmallVector<int, 8> M;
3399  N->getMask(M);
3400  return ::isSHUFPMask(M, N->getValueType(0));
3401}
3402
3403/// isCommutedSHUFP - Returns true if the shuffle mask is exactly
3404/// the reverse of what x86 shuffles want. x86 shuffles requires the lower
3405/// half elements to come from vector 1 (which would equal the dest.) and
3406/// the upper half to come from vector 2.
3407static bool isCommutedSHUFPMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3408  int NumElems = VT.getVectorNumElements();
3409
3410  if (NumElems != 2 && NumElems != 4)
3411    return false;
3412
3413  int Half = NumElems / 2;
3414  for (int i = 0; i < Half; ++i)
3415    if (!isUndefOrInRange(Mask[i], NumElems, NumElems*2))
3416      return false;
3417  for (int i = Half; i < NumElems; ++i)
3418    if (!isUndefOrInRange(Mask[i], 0, NumElems))
3419      return false;
3420  return true;
3421}
3422
3423static bool isCommutedSHUFP(ShuffleVectorSDNode *N) {
3424  SmallVector<int, 8> M;
3425  N->getMask(M);
3426  return isCommutedSHUFPMask(M, N->getValueType(0));
3427}
3428
3429/// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
3430/// specifies a shuffle of elements that is suitable for input to MOVHLPS.
3431bool X86::isMOVHLPSMask(ShuffleVectorSDNode *N) {
3432  EVT VT = N->getValueType(0);
3433  unsigned NumElems = VT.getVectorNumElements();
3434
3435  if (VT.getSizeInBits() != 128)
3436    return false;
3437
3438  if (NumElems != 4)
3439    return false;
3440
3441  // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
3442  return isUndefOrEqual(N->getMaskElt(0), 6) &&
3443         isUndefOrEqual(N->getMaskElt(1), 7) &&
3444         isUndefOrEqual(N->getMaskElt(2), 2) &&
3445         isUndefOrEqual(N->getMaskElt(3), 3);
3446}
3447
3448/// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
3449/// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
3450/// <2, 3, 2, 3>
3451bool X86::isMOVHLPS_v_undef_Mask(ShuffleVectorSDNode *N) {
3452  EVT VT = N->getValueType(0);
3453  unsigned NumElems = VT.getVectorNumElements();
3454
3455  if (VT.getSizeInBits() != 128)
3456    return false;
3457
3458  if (NumElems != 4)
3459    return false;
3460
3461  return isUndefOrEqual(N->getMaskElt(0), 2) &&
3462         isUndefOrEqual(N->getMaskElt(1), 3) &&
3463         isUndefOrEqual(N->getMaskElt(2), 2) &&
3464         isUndefOrEqual(N->getMaskElt(3), 3);
3465}
3466
3467/// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
3468/// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
3469bool X86::isMOVLPMask(ShuffleVectorSDNode *N) {
3470  unsigned NumElems = N->getValueType(0).getVectorNumElements();
3471
3472  if (NumElems != 2 && NumElems != 4)
3473    return false;
3474
3475  for (unsigned i = 0; i < NumElems/2; ++i)
3476    if (!isUndefOrEqual(N->getMaskElt(i), i + NumElems))
3477      return false;
3478
3479  for (unsigned i = NumElems/2; i < NumElems; ++i)
3480    if (!isUndefOrEqual(N->getMaskElt(i), i))
3481      return false;
3482
3483  return true;
3484}
3485
3486/// isMOVLHPSMask - Return true if the specified VECTOR_SHUFFLE operand
3487/// specifies a shuffle of elements that is suitable for input to MOVLHPS.
3488bool X86::isMOVLHPSMask(ShuffleVectorSDNode *N) {
3489  unsigned NumElems = N->getValueType(0).getVectorNumElements();
3490
3491  if ((NumElems != 2 && NumElems != 4)
3492      || N->getValueType(0).getSizeInBits() > 128)
3493    return false;
3494
3495  for (unsigned i = 0; i < NumElems/2; ++i)
3496    if (!isUndefOrEqual(N->getMaskElt(i), i))
3497      return false;
3498
3499  for (unsigned i = 0; i < NumElems/2; ++i)
3500    if (!isUndefOrEqual(N->getMaskElt(i + NumElems/2), i + NumElems))
3501      return false;
3502
3503  return true;
3504}
3505
3506/// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
3507/// specifies a shuffle of elements that is suitable for input to UNPCKL.
3508static bool isUNPCKLMask(const SmallVectorImpl<int> &Mask, EVT VT,
3509                         bool V2IsSplat = false) {
3510  int NumElts = VT.getVectorNumElements();
3511
3512  assert((VT.is128BitVector() || VT.is256BitVector()) &&
3513         "Unsupported vector type for unpckh");
3514
3515  if (VT.getSizeInBits() == 256 && NumElts != 4 && NumElts != 8)
3516    return false;
3517
3518  // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3519  // independently on 128-bit lanes.
3520  unsigned NumLanes = VT.getSizeInBits()/128;
3521  unsigned NumLaneElts = NumElts/NumLanes;
3522
3523  unsigned Start = 0;
3524  unsigned End = NumLaneElts;
3525  for (unsigned s = 0; s < NumLanes; ++s) {
3526    for (unsigned i = Start, j = s * NumLaneElts;
3527         i != End;
3528         i += 2, ++j) {
3529      int BitI  = Mask[i];
3530      int BitI1 = Mask[i+1];
3531      if (!isUndefOrEqual(BitI, j))
3532        return false;
3533      if (V2IsSplat) {
3534        if (!isUndefOrEqual(BitI1, NumElts))
3535          return false;
3536      } else {
3537        if (!isUndefOrEqual(BitI1, j + NumElts))
3538          return false;
3539      }
3540    }
3541    // Process the next 128 bits.
3542    Start += NumLaneElts;
3543    End += NumLaneElts;
3544  }
3545
3546  return true;
3547}
3548
3549bool X86::isUNPCKLMask(ShuffleVectorSDNode *N, bool V2IsSplat) {
3550  SmallVector<int, 8> M;
3551  N->getMask(M);
3552  return ::isUNPCKLMask(M, N->getValueType(0), V2IsSplat);
3553}
3554
3555/// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
3556/// specifies a shuffle of elements that is suitable for input to UNPCKH.
3557static bool isUNPCKHMask(const SmallVectorImpl<int> &Mask, EVT VT,
3558                         bool V2IsSplat = false) {
3559  int NumElts = VT.getVectorNumElements();
3560
3561  assert((VT.is128BitVector() || VT.is256BitVector()) &&
3562         "Unsupported vector type for unpckh");
3563
3564  if (VT.getSizeInBits() == 256 && NumElts != 4 && NumElts != 8)
3565    return false;
3566
3567  // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3568  // independently on 128-bit lanes.
3569  unsigned NumLanes = VT.getSizeInBits()/128;
3570  unsigned NumLaneElts = NumElts/NumLanes;
3571
3572  unsigned Start = 0;
3573  unsigned End = NumLaneElts;
3574  for (unsigned l = 0; l != NumLanes; ++l) {
3575    for (unsigned i = Start, j = (l*NumLaneElts)+NumLaneElts/2;
3576                             i != End; i += 2, ++j) {
3577      int BitI  = Mask[i];
3578      int BitI1 = Mask[i+1];
3579      if (!isUndefOrEqual(BitI, j))
3580        return false;
3581      if (V2IsSplat) {
3582        if (isUndefOrEqual(BitI1, NumElts))
3583          return false;
3584      } else {
3585        if (!isUndefOrEqual(BitI1, j+NumElts))
3586          return false;
3587      }
3588    }
3589    // Process the next 128 bits.
3590    Start += NumLaneElts;
3591    End += NumLaneElts;
3592  }
3593  return true;
3594}
3595
3596bool X86::isUNPCKHMask(ShuffleVectorSDNode *N, bool V2IsSplat) {
3597  SmallVector<int, 8> M;
3598  N->getMask(M);
3599  return ::isUNPCKHMask(M, N->getValueType(0), V2IsSplat);
3600}
3601
3602/// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
3603/// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
3604/// <0, 0, 1, 1>
3605static bool isUNPCKL_v_undef_Mask(const SmallVectorImpl<int> &Mask, EVT VT) {
3606  int NumElems = VT.getVectorNumElements();
3607  if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
3608    return false;
3609
3610  // For 256-bit i64/f64, use MOVDDUPY instead, so reject the matching pattern
3611  // FIXME: Need a better way to get rid of this, there's no latency difference
3612  // between UNPCKLPD and MOVDDUP, the later should always be checked first and
3613  // the former later. We should also remove the "_undef" special mask.
3614  if (NumElems == 4 && VT.getSizeInBits() == 256)
3615    return false;
3616
3617  // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3618  // independently on 128-bit lanes.
3619  unsigned NumLanes = VT.getSizeInBits() / 128;
3620  unsigned NumLaneElts = NumElems / NumLanes;
3621
3622  for (unsigned s = 0; s < NumLanes; ++s) {
3623    for (unsigned i = s * NumLaneElts, j = s * NumLaneElts;
3624         i != NumLaneElts * (s + 1);
3625         i += 2, ++j) {
3626      int BitI  = Mask[i];
3627      int BitI1 = Mask[i+1];
3628
3629      if (!isUndefOrEqual(BitI, j))
3630        return false;
3631      if (!isUndefOrEqual(BitI1, j))
3632        return false;
3633    }
3634  }
3635
3636  return true;
3637}
3638
3639bool X86::isUNPCKL_v_undef_Mask(ShuffleVectorSDNode *N) {
3640  SmallVector<int, 8> M;
3641  N->getMask(M);
3642  return ::isUNPCKL_v_undef_Mask(M, N->getValueType(0));
3643}
3644
3645/// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
3646/// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
3647/// <2, 2, 3, 3>
3648static bool isUNPCKH_v_undef_Mask(const SmallVectorImpl<int> &Mask, EVT VT) {
3649  int NumElems = VT.getVectorNumElements();
3650  if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
3651    return false;
3652
3653  for (int i = 0, j = NumElems / 2; i != NumElems; i += 2, ++j) {
3654    int BitI  = Mask[i];
3655    int BitI1 = Mask[i+1];
3656    if (!isUndefOrEqual(BitI, j))
3657      return false;
3658    if (!isUndefOrEqual(BitI1, j))
3659      return false;
3660  }
3661  return true;
3662}
3663
3664bool X86::isUNPCKH_v_undef_Mask(ShuffleVectorSDNode *N) {
3665  SmallVector<int, 8> M;
3666  N->getMask(M);
3667  return ::isUNPCKH_v_undef_Mask(M, N->getValueType(0));
3668}
3669
3670/// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
3671/// specifies a shuffle of elements that is suitable for input to MOVSS,
3672/// MOVSD, and MOVD, i.e. setting the lowest element.
3673static bool isMOVLMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3674  if (VT.getVectorElementType().getSizeInBits() < 32)
3675    return false;
3676
3677  int NumElts = VT.getVectorNumElements();
3678
3679  if (!isUndefOrEqual(Mask[0], NumElts))
3680    return false;
3681
3682  for (int i = 1; i < NumElts; ++i)
3683    if (!isUndefOrEqual(Mask[i], i))
3684      return false;
3685
3686  return true;
3687}
3688
3689bool X86::isMOVLMask(ShuffleVectorSDNode *N) {
3690  SmallVector<int, 8> M;
3691  N->getMask(M);
3692  return ::isMOVLMask(M, N->getValueType(0));
3693}
3694
3695/// isVPERM2F128Mask - Match 256-bit shuffles where the elements are considered
3696/// as permutations between 128-bit chunks or halves. As an example: this
3697/// shuffle bellow:
3698///   vector_shuffle <4, 5, 6, 7, 12, 13, 14, 15>
3699/// The first half comes from the second half of V1 and the second half from the
3700/// the second half of V2.
3701static bool isVPERM2F128Mask(const SmallVectorImpl<int> &Mask, EVT VT,
3702                             const X86Subtarget *Subtarget) {
3703  if (!Subtarget->hasAVX() || VT.getSizeInBits() != 256)
3704    return false;
3705
3706  // The shuffle result is divided into half A and half B. In total the two
3707  // sources have 4 halves, namely: C, D, E, F. The final values of A and
3708  // B must come from C, D, E or F.
3709  int HalfSize = VT.getVectorNumElements()/2;
3710  bool MatchA = false, MatchB = false;
3711
3712  // Check if A comes from one of C, D, E, F.
3713  for (int Half = 0; Half < 4; ++Half) {
3714    if (isSequentialOrUndefInRange(Mask, 0, HalfSize, Half*HalfSize)) {
3715      MatchA = true;
3716      break;
3717    }
3718  }
3719
3720  // Check if B comes from one of C, D, E, F.
3721  for (int Half = 0; Half < 4; ++Half) {
3722    if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, Half*HalfSize)) {
3723      MatchB = true;
3724      break;
3725    }
3726  }
3727
3728  return MatchA && MatchB;
3729}
3730
3731/// getShuffleVPERM2F128Immediate - Return the appropriate immediate to shuffle
3732/// the specified VECTOR_MASK mask with VPERM2F128 instructions.
3733static unsigned getShuffleVPERM2F128Immediate(SDNode *N) {
3734  ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3735  EVT VT = SVOp->getValueType(0);
3736
3737  int HalfSize = VT.getVectorNumElements()/2;
3738
3739  int FstHalf = 0, SndHalf = 0;
3740  for (int i = 0; i < HalfSize; ++i) {
3741    if (SVOp->getMaskElt(i) > 0) {
3742      FstHalf = SVOp->getMaskElt(i)/HalfSize;
3743      break;
3744    }
3745  }
3746  for (int i = HalfSize; i < HalfSize*2; ++i) {
3747    if (SVOp->getMaskElt(i) > 0) {
3748      SndHalf = SVOp->getMaskElt(i)/HalfSize;
3749      break;
3750    }
3751  }
3752
3753  return (FstHalf | (SndHalf << 4));
3754}
3755
3756/// isVPERMILPDMask - Return true if the specified VECTOR_SHUFFLE operand
3757/// specifies a shuffle of elements that is suitable for input to VPERMILPD*.
3758/// Note that VPERMIL mask matching is different depending whether theunderlying
3759/// type is 32 or 64. In the VPERMILPS the high half of the mask should point
3760/// to the same elements of the low, but to the higher half of the source.
3761/// In VPERMILPD the two lanes could be shuffled independently of each other
3762/// with the same restriction that lanes can't be crossed.
3763static bool isVPERMILPDMask(const SmallVectorImpl<int> &Mask, EVT VT,
3764                            const X86Subtarget *Subtarget) {
3765  int NumElts = VT.getVectorNumElements();
3766  int NumLanes = VT.getSizeInBits()/128;
3767
3768  if (!Subtarget->hasAVX())
3769    return false;
3770
3771  // Only match 256-bit with 64-bit types
3772  if (VT.getSizeInBits() != 256 || NumElts != 4)
3773    return false;
3774
3775  // The mask on the high lane is independent of the low. Both can match
3776  // any element in inside its own lane, but can't cross.
3777  int LaneSize = NumElts/NumLanes;
3778  for (int l = 0; l < NumLanes; ++l)
3779    for (int i = l*LaneSize; i < LaneSize*(l+1); ++i) {
3780      int LaneStart = l*LaneSize;
3781      if (!isUndefOrInRange(Mask[i], LaneStart, LaneStart+LaneSize))
3782        return false;
3783    }
3784
3785  return true;
3786}
3787
3788/// isVPERMILPSMask - Return true if the specified VECTOR_SHUFFLE operand
3789/// specifies a shuffle of elements that is suitable for input to VPERMILPS*.
3790/// Note that VPERMIL mask matching is different depending whether theunderlying
3791/// type is 32 or 64. In the VPERMILPS the high half of the mask should point
3792/// to the same elements of the low, but to the higher half of the source.
3793/// In VPERMILPD the two lanes could be shuffled independently of each other
3794/// with the same restriction that lanes can't be crossed.
3795static bool isVPERMILPSMask(const SmallVectorImpl<int> &Mask, EVT VT,
3796                            const X86Subtarget *Subtarget) {
3797  unsigned NumElts = VT.getVectorNumElements();
3798  unsigned NumLanes = VT.getSizeInBits()/128;
3799
3800  if (!Subtarget->hasAVX())
3801    return false;
3802
3803  // Only match 256-bit with 32-bit types
3804  if (VT.getSizeInBits() != 256 || NumElts != 8)
3805    return false;
3806
3807  // The mask on the high lane should be the same as the low. Actually,
3808  // they can differ if any of the corresponding index in a lane is undef
3809  // and the other stays in range.
3810  int LaneSize = NumElts/NumLanes;
3811  for (int i = 0; i < LaneSize; ++i) {
3812    int HighElt = i+LaneSize;
3813    bool HighValid = isUndefOrInRange(Mask[HighElt], LaneSize, NumElts);
3814    bool LowValid = isUndefOrInRange(Mask[i], 0, LaneSize);
3815
3816    if (!HighValid || !LowValid)
3817      return false;
3818    if (Mask[i] < 0 || Mask[HighElt] < 0)
3819      continue;
3820    if (Mask[HighElt]-Mask[i] != LaneSize)
3821      return false;
3822  }
3823
3824  return true;
3825}
3826
3827/// getShuffleVPERMILPSImmediate - Return the appropriate immediate to shuffle
3828/// the specified VECTOR_MASK mask with VPERMILPS* instructions.
3829static unsigned getShuffleVPERMILPSImmediate(SDNode *N) {
3830  ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3831  EVT VT = SVOp->getValueType(0);
3832
3833  int NumElts = VT.getVectorNumElements();
3834  int NumLanes = VT.getSizeInBits()/128;
3835  int LaneSize = NumElts/NumLanes;
3836
3837  // Although the mask is equal for both lanes do it twice to get the cases
3838  // where a mask will match because the same mask element is undef on the
3839  // first half but valid on the second. This would get pathological cases
3840  // such as: shuffle <u, 0, 1, 2, 4, 4, 5, 6>, which is completely valid.
3841  unsigned Mask = 0;
3842  for (int l = 0; l < NumLanes; ++l) {
3843    for (int i = 0; i < LaneSize; ++i) {
3844      int MaskElt = SVOp->getMaskElt(i+(l*LaneSize));
3845      if (MaskElt < 0)
3846        continue;
3847      if (MaskElt >= LaneSize)
3848        MaskElt -= LaneSize;
3849      Mask |= MaskElt << (i*2);
3850    }
3851  }
3852
3853  return Mask;
3854}
3855
3856/// getShuffleVPERMILPDImmediate - Return the appropriate immediate to shuffle
3857/// the specified VECTOR_MASK mask with VPERMILPD* instructions.
3858static unsigned getShuffleVPERMILPDImmediate(SDNode *N) {
3859  ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3860  EVT VT = SVOp->getValueType(0);
3861
3862  int NumElts = VT.getVectorNumElements();
3863  int NumLanes = VT.getSizeInBits()/128;
3864
3865  unsigned Mask = 0;
3866  int LaneSize = NumElts/NumLanes;
3867  for (int l = 0; l < NumLanes; ++l)
3868    for (int i = l*LaneSize; i < LaneSize*(l+1); ++i) {
3869      int MaskElt = SVOp->getMaskElt(i);
3870      if (MaskElt < 0)
3871        continue;
3872      Mask |= (MaskElt-l*LaneSize) << i;
3873    }
3874
3875  return Mask;
3876}
3877
3878/// isCommutedMOVL - Returns true if the shuffle mask is except the reverse
3879/// of what x86 movss want. X86 movs requires the lowest  element to be lowest
3880/// element of vector 2 and the other elements to come from vector 1 in order.
3881static bool isCommutedMOVLMask(const SmallVectorImpl<int> &Mask, EVT VT,
3882                               bool V2IsSplat = false, bool V2IsUndef = false) {
3883  int NumOps = VT.getVectorNumElements();
3884  if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
3885    return false;
3886
3887  if (!isUndefOrEqual(Mask[0], 0))
3888    return false;
3889
3890  for (int i = 1; i < NumOps; ++i)
3891    if (!(isUndefOrEqual(Mask[i], i+NumOps) ||
3892          (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) ||
3893          (V2IsSplat && isUndefOrEqual(Mask[i], NumOps))))
3894      return false;
3895
3896  return true;
3897}
3898
3899static bool isCommutedMOVL(ShuffleVectorSDNode *N, bool V2IsSplat = false,
3900                           bool V2IsUndef = false) {
3901  SmallVector<int, 8> M;
3902  N->getMask(M);
3903  return isCommutedMOVLMask(M, N->getValueType(0), V2IsSplat, V2IsUndef);
3904}
3905
3906/// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3907/// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
3908/// Masks to match: <1, 1, 3, 3> or <1, 1, 3, 3, 5, 5, 7, 7>
3909bool X86::isMOVSHDUPMask(ShuffleVectorSDNode *N,
3910                         const X86Subtarget *Subtarget) {
3911  if (!Subtarget->hasSSE3() && !Subtarget->hasAVX())
3912    return false;
3913
3914  // The second vector must be undef
3915  if (N->getOperand(1).getOpcode() != ISD::UNDEF)
3916    return false;
3917
3918  EVT VT = N->getValueType(0);
3919  unsigned NumElems = VT.getVectorNumElements();
3920
3921  if ((VT.getSizeInBits() == 128 && NumElems != 4) ||
3922      (VT.getSizeInBits() == 256 && NumElems != 8))
3923    return false;
3924
3925  // "i+1" is the value the indexed mask element must have
3926  for (unsigned i = 0; i < NumElems; i += 2)
3927    if (!isUndefOrEqual(N->getMaskElt(i), i+1) ||
3928        !isUndefOrEqual(N->getMaskElt(i+1), i+1))
3929      return false;
3930
3931  return true;
3932}
3933
3934/// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3935/// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
3936/// Masks to match: <0, 0, 2, 2> or <0, 0, 2, 2, 4, 4, 6, 6>
3937bool X86::isMOVSLDUPMask(ShuffleVectorSDNode *N,
3938                         const X86Subtarget *Subtarget) {
3939  if (!Subtarget->hasSSE3() && !Subtarget->hasAVX())
3940    return false;
3941
3942  // The second vector must be undef
3943  if (N->getOperand(1).getOpcode() != ISD::UNDEF)
3944    return false;
3945
3946  EVT VT = N->getValueType(0);
3947  unsigned NumElems = VT.getVectorNumElements();
3948
3949  if ((VT.getSizeInBits() == 128 && NumElems != 4) ||
3950      (VT.getSizeInBits() == 256 && NumElems != 8))
3951    return false;
3952
3953  // "i" is the value the indexed mask element must have
3954  for (unsigned i = 0; i < NumElems; i += 2)
3955    if (!isUndefOrEqual(N->getMaskElt(i), i) ||
3956        !isUndefOrEqual(N->getMaskElt(i+1), i))
3957      return false;
3958
3959  return true;
3960}
3961
3962/// isMOVDDUPYMask - Return true if the specified VECTOR_SHUFFLE operand
3963/// specifies a shuffle of elements that is suitable for input to 256-bit
3964/// version of MOVDDUP.
3965static bool isMOVDDUPYMask(ShuffleVectorSDNode *N,
3966                           const X86Subtarget *Subtarget) {
3967  EVT VT = N->getValueType(0);
3968  int NumElts = VT.getVectorNumElements();
3969  bool V2IsUndef = N->getOperand(1).getOpcode() == ISD::UNDEF;
3970
3971  if (!Subtarget->hasAVX() || VT.getSizeInBits() != 256 ||
3972      !V2IsUndef || NumElts != 4)
3973    return false;
3974
3975  for (int i = 0; i != NumElts/2; ++i)
3976    if (!isUndefOrEqual(N->getMaskElt(i), 0))
3977      return false;
3978  for (int i = NumElts/2; i != NumElts; ++i)
3979    if (!isUndefOrEqual(N->getMaskElt(i), NumElts/2))
3980      return false;
3981  return true;
3982}
3983
3984/// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3985/// specifies a shuffle of elements that is suitable for input to 128-bit
3986/// version of MOVDDUP.
3987bool X86::isMOVDDUPMask(ShuffleVectorSDNode *N) {
3988  EVT VT = N->getValueType(0);
3989
3990  if (VT.getSizeInBits() != 128)
3991    return false;
3992
3993  int e = VT.getVectorNumElements() / 2;
3994  for (int i = 0; i < e; ++i)
3995    if (!isUndefOrEqual(N->getMaskElt(i), i))
3996      return false;
3997  for (int i = 0; i < e; ++i)
3998    if (!isUndefOrEqual(N->getMaskElt(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.
4043unsigned X86::getShuffleSHUFImmediate(SDNode *N) {
4044  ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
4045  int NumOperands = SVOp->getValueType(0).getVectorNumElements();
4046
4047  unsigned Shift = (NumOperands == 4) ? 2 : 1;
4048  unsigned Mask = 0;
4049  for (int i = 0; i < NumOperands; ++i) {
4050    int Val = SVOp->getMaskElt(NumOperands-i-1);
4051    if (Val < 0) Val = 0;
4052    if (Val >= NumOperands) Val -= NumOperands;
4053    Mask |= Val;
4054    if (i != NumOperands - 1)
4055      Mask <<= Shift;
4056  }
4057  return Mask;
4058}
4059
4060/// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
4061/// the specified VECTOR_SHUFFLE mask with the PSHUFHW instruction.
4062unsigned X86::getShufflePSHUFHWImmediate(SDNode *N) {
4063  ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
4064  unsigned Mask = 0;
4065  // 8 nodes, but we only care about the last 4.
4066  for (unsigned i = 7; i >= 4; --i) {
4067    int Val = SVOp->getMaskElt(i);
4068    if (Val >= 0)
4069      Mask |= (Val - 4);
4070    if (i != 4)
4071      Mask <<= 2;
4072  }
4073  return Mask;
4074}
4075
4076/// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
4077/// the specified VECTOR_SHUFFLE mask with the PSHUFLW instruction.
4078unsigned X86::getShufflePSHUFLWImmediate(SDNode *N) {
4079  ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
4080  unsigned Mask = 0;
4081  // 8 nodes, but we only care about the first 4.
4082  for (int i = 3; i >= 0; --i) {
4083    int Val = SVOp->getMaskElt(i);
4084    if (Val >= 0)
4085      Mask |= Val;
4086    if (i != 0)
4087      Mask <<= 2;
4088  }
4089  return Mask;
4090}
4091
4092/// getShufflePALIGNRImmediate - Return the appropriate immediate to shuffle
4093/// the specified VECTOR_SHUFFLE mask with the PALIGNR instruction.
4094unsigned X86::getShufflePALIGNRImmediate(SDNode *N) {
4095  ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
4096  EVT VVT = N->getValueType(0);
4097  unsigned EltSize = VVT.getVectorElementType().getSizeInBits() >> 3;
4098  int Val = 0;
4099
4100  unsigned i, e;
4101  for (i = 0, e = VVT.getVectorNumElements(); i != e; ++i) {
4102    Val = SVOp->getMaskElt(i);
4103    if (Val >= 0)
4104      break;
4105  }
4106  assert(Val - i > 0 && "PALIGNR imm should be positive");
4107  return (Val - i) * EltSize;
4108}
4109
4110/// getExtractVEXTRACTF128Immediate - Return the appropriate immediate
4111/// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF128
4112/// instructions.
4113unsigned X86::getExtractVEXTRACTF128Immediate(SDNode *N) {
4114  if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4115    llvm_unreachable("Illegal extract subvector for VEXTRACTF128");
4116
4117  uint64_t Index =
4118    cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4119
4120  EVT VecVT = N->getOperand(0).getValueType();
4121  EVT ElVT = VecVT.getVectorElementType();
4122
4123  unsigned NumElemsPerChunk = 128 / ElVT.getSizeInBits();
4124  return Index / NumElemsPerChunk;
4125}
4126
4127/// getInsertVINSERTF128Immediate - Return the appropriate immediate
4128/// to insert at the specified INSERT_SUBVECTOR index with VINSERTF128
4129/// instructions.
4130unsigned X86::getInsertVINSERTF128Immediate(SDNode *N) {
4131  if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4132    llvm_unreachable("Illegal insert subvector for VINSERTF128");
4133
4134  uint64_t Index =
4135    cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4136
4137  EVT VecVT = N->getValueType(0);
4138  EVT ElVT = VecVT.getVectorElementType();
4139
4140  unsigned NumElemsPerChunk = 128 / ElVT.getSizeInBits();
4141  return Index / NumElemsPerChunk;
4142}
4143
4144/// isZeroNode - Returns true if Elt is a constant zero or a floating point
4145/// constant +0.0.
4146bool X86::isZeroNode(SDValue Elt) {
4147  return ((isa<ConstantSDNode>(Elt) &&
4148           cast<ConstantSDNode>(Elt)->isNullValue()) ||
4149          (isa<ConstantFPSDNode>(Elt) &&
4150           cast<ConstantFPSDNode>(Elt)->getValueAPF().isPosZero()));
4151}
4152
4153/// CommuteVectorShuffle - Swap vector_shuffle operands as well as values in
4154/// their permute mask.
4155static SDValue CommuteVectorShuffle(ShuffleVectorSDNode *SVOp,
4156                                    SelectionDAG &DAG) {
4157  EVT VT = SVOp->getValueType(0);
4158  unsigned NumElems = VT.getVectorNumElements();
4159  SmallVector<int, 8> MaskVec;
4160
4161  for (unsigned i = 0; i != NumElems; ++i) {
4162    int idx = SVOp->getMaskElt(i);
4163    if (idx < 0)
4164      MaskVec.push_back(idx);
4165    else if (idx < (int)NumElems)
4166      MaskVec.push_back(idx + NumElems);
4167    else
4168      MaskVec.push_back(idx - NumElems);
4169  }
4170  return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(1),
4171                              SVOp->getOperand(0), &MaskVec[0]);
4172}
4173
4174/// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
4175/// the two vector operands have swapped position.
4176static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask, EVT VT) {
4177  unsigned NumElems = VT.getVectorNumElements();
4178  for (unsigned i = 0; i != NumElems; ++i) {
4179    int idx = Mask[i];
4180    if (idx < 0)
4181      continue;
4182    else if (idx < (int)NumElems)
4183      Mask[i] = idx + NumElems;
4184    else
4185      Mask[i] = idx - NumElems;
4186  }
4187}
4188
4189/// ShouldXformToMOVHLPS - Return true if the node should be transformed to
4190/// match movhlps. The lower half elements should come from upper half of
4191/// V1 (and in order), and the upper half elements should come from the upper
4192/// half of V2 (and in order).
4193static bool ShouldXformToMOVHLPS(ShuffleVectorSDNode *Op) {
4194  EVT VT = Op->getValueType(0);
4195  if (VT.getSizeInBits() != 128)
4196    return false;
4197  if (VT.getVectorNumElements() != 4)
4198    return false;
4199  for (unsigned i = 0, e = 2; i != e; ++i)
4200    if (!isUndefOrEqual(Op->getMaskElt(i), i+2))
4201      return false;
4202  for (unsigned i = 2; i != 4; ++i)
4203    if (!isUndefOrEqual(Op->getMaskElt(i), i+4))
4204      return false;
4205  return true;
4206}
4207
4208/// isScalarLoadToVector - Returns true if the node is a scalar load that
4209/// is promoted to a vector. It also returns the LoadSDNode by reference if
4210/// required.
4211static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = NULL) {
4212  if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
4213    return false;
4214  N = N->getOperand(0).getNode();
4215  if (!ISD::isNON_EXTLoad(N))
4216    return false;
4217  if (LD)
4218    *LD = cast<LoadSDNode>(N);
4219  return true;
4220}
4221
4222/// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
4223/// match movlp{s|d}. The lower half elements should come from lower half of
4224/// V1 (and in order), and the upper half elements should come from the upper
4225/// half of V2 (and in order). And since V1 will become the source of the
4226/// MOVLP, it must be either a vector load or a scalar load to vector.
4227static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2,
4228                               ShuffleVectorSDNode *Op) {
4229  EVT VT = Op->getValueType(0);
4230  if (VT.getSizeInBits() != 128)
4231    return false;
4232
4233  if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
4234    return false;
4235  // Is V2 is a vector load, don't do this transformation. We will try to use
4236  // load folding shufps op.
4237  if (ISD::isNON_EXTLoad(V2))
4238    return false;
4239
4240  unsigned NumElems = VT.getVectorNumElements();
4241
4242  if (NumElems != 2 && NumElems != 4)
4243    return false;
4244  for (unsigned i = 0, e = NumElems/2; i != e; ++i)
4245    if (!isUndefOrEqual(Op->getMaskElt(i), i))
4246      return false;
4247  for (unsigned i = NumElems/2; i != NumElems; ++i)
4248    if (!isUndefOrEqual(Op->getMaskElt(i), i+NumElems))
4249      return false;
4250  return true;
4251}
4252
4253/// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
4254/// all the same.
4255static bool isSplatVector(SDNode *N) {
4256  if (N->getOpcode() != ISD::BUILD_VECTOR)
4257    return false;
4258
4259  SDValue SplatValue = N->getOperand(0);
4260  for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
4261    if (N->getOperand(i) != SplatValue)
4262      return false;
4263  return true;
4264}
4265
4266/// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
4267/// to an zero vector.
4268/// FIXME: move to dag combiner / method on ShuffleVectorSDNode
4269static bool isZeroShuffle(ShuffleVectorSDNode *N) {
4270  SDValue V1 = N->getOperand(0);
4271  SDValue V2 = N->getOperand(1);
4272  unsigned NumElems = N->getValueType(0).getVectorNumElements();
4273  for (unsigned i = 0; i != NumElems; ++i) {
4274    int Idx = N->getMaskElt(i);
4275    if (Idx >= (int)NumElems) {
4276      unsigned Opc = V2.getOpcode();
4277      if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
4278        continue;
4279      if (Opc != ISD::BUILD_VECTOR ||
4280          !X86::isZeroNode(V2.getOperand(Idx-NumElems)))
4281        return false;
4282    } else if (Idx >= 0) {
4283      unsigned Opc = V1.getOpcode();
4284      if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
4285        continue;
4286      if (Opc != ISD::BUILD_VECTOR ||
4287          !X86::isZeroNode(V1.getOperand(Idx)))
4288        return false;
4289    }
4290  }
4291  return true;
4292}
4293
4294/// getZeroVector - Returns a vector of specified type with all zero elements.
4295///
4296static SDValue getZeroVector(EVT VT, bool HasXMMInt, SelectionDAG &DAG,
4297                             DebugLoc dl) {
4298  assert(VT.isVector() && "Expected a vector type");
4299
4300  // Always build SSE zero vectors as <4 x i32> bitcasted
4301  // to their dest type. This ensures they get CSE'd.
4302  SDValue Vec;
4303  if (VT.getSizeInBits() == 128) {  // SSE
4304    if (HasXMMInt) {  // SSE2
4305      SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4306      Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4307    } else { // SSE1
4308      SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4309      Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
4310    }
4311  } else if (VT.getSizeInBits() == 256) { // AVX
4312    // 256-bit logic and arithmetic instructions in AVX are
4313    // all floating-point, no support for integer ops. Default
4314    // to emitting fp zeroed vectors then.
4315    SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4316    SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4317    Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops, 8);
4318  }
4319  return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4320}
4321
4322/// getOnesVector - Returns a vector of specified type with all bits set.
4323/// Always build ones vectors as <4 x i32>. For 256-bit types, use two
4324/// <4 x i32> inserted in a <8 x i32> appropriately. Then bitcast to their
4325/// original type, ensuring they get CSE'd.
4326static SDValue getOnesVector(EVT VT, SelectionDAG &DAG, DebugLoc dl) {
4327  assert(VT.isVector() && "Expected a vector type");
4328  assert((VT.is128BitVector() || VT.is256BitVector())
4329         && "Expected a 128-bit or 256-bit vector type");
4330
4331  SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
4332  SDValue Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32,
4333                            Cst, Cst, Cst, Cst);
4334
4335  if (VT.is256BitVector()) {
4336    SDValue InsV = Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, MVT::v8i32),
4337                              Vec, DAG.getConstant(0, MVT::i32), DAG, dl);
4338    Vec = Insert128BitVector(InsV, Vec,
4339                  DAG.getConstant(4 /* NumElems/2 */, MVT::i32), DAG, dl);
4340  }
4341
4342  return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4343}
4344
4345/// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
4346/// that point to V2 points to its first element.
4347static SDValue NormalizeMask(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
4348  EVT VT = SVOp->getValueType(0);
4349  unsigned NumElems = VT.getVectorNumElements();
4350
4351  bool Changed = false;
4352  SmallVector<int, 8> MaskVec;
4353  SVOp->getMask(MaskVec);
4354
4355  for (unsigned i = 0; i != NumElems; ++i) {
4356    if (MaskVec[i] > (int)NumElems) {
4357      MaskVec[i] = NumElems;
4358      Changed = true;
4359    }
4360  }
4361  if (Changed)
4362    return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(0),
4363                                SVOp->getOperand(1), &MaskVec[0]);
4364  return SDValue(SVOp, 0);
4365}
4366
4367/// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
4368/// operation of specified width.
4369static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
4370                       SDValue V2) {
4371  unsigned NumElems = VT.getVectorNumElements();
4372  SmallVector<int, 8> Mask;
4373  Mask.push_back(NumElems);
4374  for (unsigned i = 1; i != NumElems; ++i)
4375    Mask.push_back(i);
4376  return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4377}
4378
4379/// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
4380static SDValue getUnpackl(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
4381                          SDValue V2) {
4382  unsigned NumElems = VT.getVectorNumElements();
4383  SmallVector<int, 8> Mask;
4384  for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
4385    Mask.push_back(i);
4386    Mask.push_back(i + NumElems);
4387  }
4388  return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4389}
4390
4391/// getUnpackh - Returns a vector_shuffle node for an unpackh operation.
4392static SDValue getUnpackh(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
4393                          SDValue V2) {
4394  unsigned NumElems = VT.getVectorNumElements();
4395  unsigned Half = NumElems/2;
4396  SmallVector<int, 8> Mask;
4397  for (unsigned i = 0; i != Half; ++i) {
4398    Mask.push_back(i + Half);
4399    Mask.push_back(i + NumElems + Half);
4400  }
4401  return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4402}
4403
4404// PromoteSplati8i16 - All i16 and i8 vector types can't be used directly by
4405// a generic shuffle instruction because the target has no such instructions.
4406// Generate shuffles which repeat i16 and i8 several times until they can be
4407// represented by v4f32 and then be manipulated by target suported shuffles.
4408static SDValue PromoteSplati8i16(SDValue V, SelectionDAG &DAG, int &EltNo) {
4409  EVT VT = V.getValueType();
4410  int NumElems = VT.getVectorNumElements();
4411  DebugLoc dl = V.getDebugLoc();
4412
4413  while (NumElems > 4) {
4414    if (EltNo < NumElems/2) {
4415      V = getUnpackl(DAG, dl, VT, V, V);
4416    } else {
4417      V = getUnpackh(DAG, dl, VT, V, V);
4418      EltNo -= NumElems/2;
4419    }
4420    NumElems >>= 1;
4421  }
4422  return V;
4423}
4424
4425/// getLegalSplat - Generate a legal splat with supported x86 shuffles
4426static SDValue getLegalSplat(SelectionDAG &DAG, SDValue V, int EltNo) {
4427  EVT VT = V.getValueType();
4428  DebugLoc dl = V.getDebugLoc();
4429  assert((VT.getSizeInBits() == 128 || VT.getSizeInBits() == 256)
4430         && "Vector size not supported");
4431
4432  if (VT.getSizeInBits() == 128) {
4433    V = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V);
4434    int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo };
4435    V = DAG.getVectorShuffle(MVT::v4f32, dl, V, DAG.getUNDEF(MVT::v4f32),
4436                             &SplatMask[0]);
4437  } else {
4438    // To use VPERMILPS to splat scalars, the second half of indicies must
4439    // refer to the higher part, which is a duplication of the lower one,
4440    // because VPERMILPS can only handle in-lane permutations.
4441    int SplatMask[8] = { EltNo, EltNo, EltNo, EltNo,
4442                         EltNo+4, EltNo+4, EltNo+4, EltNo+4 };
4443
4444    V = DAG.getNode(ISD::BITCAST, dl, MVT::v8f32, V);
4445    V = DAG.getVectorShuffle(MVT::v8f32, dl, V, DAG.getUNDEF(MVT::v8f32),
4446                             &SplatMask[0]);
4447  }
4448
4449  return DAG.getNode(ISD::BITCAST, dl, VT, V);
4450}
4451
4452/// PromoteSplat - Splat is promoted to target supported vector shuffles.
4453static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG) {
4454  EVT SrcVT = SV->getValueType(0);
4455  SDValue V1 = SV->getOperand(0);
4456  DebugLoc dl = SV->getDebugLoc();
4457
4458  int EltNo = SV->getSplatIndex();
4459  int NumElems = SrcVT.getVectorNumElements();
4460  unsigned Size = SrcVT.getSizeInBits();
4461
4462  assert(((Size == 128 && NumElems > 4) || Size == 256) &&
4463          "Unknown how to promote splat for type");
4464
4465  // Extract the 128-bit part containing the splat element and update
4466  // the splat element index when it refers to the higher register.
4467  if (Size == 256) {
4468    unsigned Idx = (EltNo > NumElems/2) ? NumElems/2 : 0;
4469    V1 = Extract128BitVector(V1, DAG.getConstant(Idx, MVT::i32), DAG, dl);
4470    if (Idx > 0)
4471      EltNo -= NumElems/2;
4472  }
4473
4474  // All i16 and i8 vector types can't be used directly by a generic shuffle
4475  // instruction because the target has no such instruction. Generate shuffles
4476  // which repeat i16 and i8 several times until they fit in i32, and then can
4477  // be manipulated by target suported shuffles.
4478  EVT EltVT = SrcVT.getVectorElementType();
4479  if (EltVT == MVT::i8 || EltVT == MVT::i16)
4480    V1 = PromoteSplati8i16(V1, DAG, EltNo);
4481
4482  // Recreate the 256-bit vector and place the same 128-bit vector
4483  // into the low and high part. This is necessary because we want
4484  // to use VPERM* to shuffle the vectors
4485  if (Size == 256) {
4486    SDValue InsV = Insert128BitVector(DAG.getUNDEF(SrcVT), V1,
4487                         DAG.getConstant(0, MVT::i32), DAG, dl);
4488    V1 = Insert128BitVector(InsV, V1,
4489               DAG.getConstant(NumElems/2, MVT::i32), DAG, dl);
4490  }
4491
4492  return getLegalSplat(DAG, V1, EltNo);
4493}
4494
4495/// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
4496/// vector of zero or undef vector.  This produces a shuffle where the low
4497/// element of V2 is swizzled into the zero/undef vector, landing at element
4498/// Idx.  This produces a shuffle mask like 4,1,2,3 (idx=0) or  0,1,2,4 (idx=3).
4499static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
4500                                           bool isZero, bool HasXMMInt,
4501                                           SelectionDAG &DAG) {
4502  EVT VT = V2.getValueType();
4503  SDValue V1 = isZero
4504    ? getZeroVector(VT, HasXMMInt, DAG, V2.getDebugLoc()) : DAG.getUNDEF(VT);
4505  unsigned NumElems = VT.getVectorNumElements();
4506  SmallVector<int, 16> MaskVec;
4507  for (unsigned i = 0; i != NumElems; ++i)
4508    // If this is the insertion idx, put the low elt of V2 here.
4509    MaskVec.push_back(i == Idx ? NumElems : i);
4510  return DAG.getVectorShuffle(VT, V2.getDebugLoc(), V1, V2, &MaskVec[0]);
4511}
4512
4513/// getShuffleScalarElt - Returns the scalar element that will make up the ith
4514/// element of the result of the vector shuffle.
4515static SDValue getShuffleScalarElt(SDNode *N, int Index, SelectionDAG &DAG,
4516                                   unsigned Depth) {
4517  if (Depth == 6)
4518    return SDValue();  // Limit search depth.
4519
4520  SDValue V = SDValue(N, 0);
4521  EVT VT = V.getValueType();
4522  unsigned Opcode = V.getOpcode();
4523
4524  // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
4525  if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
4526    Index = SV->getMaskElt(Index);
4527
4528    if (Index < 0)
4529      return DAG.getUNDEF(VT.getVectorElementType());
4530
4531    int NumElems = VT.getVectorNumElements();
4532    SDValue NewV = (Index < NumElems) ? SV->getOperand(0) : SV->getOperand(1);
4533    return getShuffleScalarElt(NewV.getNode(), Index % NumElems, DAG, Depth+1);
4534  }
4535
4536  // Recurse into target specific vector shuffles to find scalars.
4537  if (isTargetShuffle(Opcode)) {
4538    int NumElems = VT.getVectorNumElements();
4539    SmallVector<unsigned, 16> ShuffleMask;
4540    SDValue ImmN;
4541
4542    switch(Opcode) {
4543    case X86ISD::SHUFPS:
4544    case X86ISD::SHUFPD:
4545      ImmN = N->getOperand(N->getNumOperands()-1);
4546      DecodeSHUFPSMask(NumElems,
4547                       cast<ConstantSDNode>(ImmN)->getZExtValue(),
4548                       ShuffleMask);
4549      break;
4550    case X86ISD::PUNPCKHBW:
4551    case X86ISD::PUNPCKHWD:
4552    case X86ISD::PUNPCKHDQ:
4553    case X86ISD::PUNPCKHQDQ:
4554      DecodePUNPCKHMask(NumElems, ShuffleMask);
4555      break;
4556    case X86ISD::UNPCKHPS:
4557    case X86ISD::UNPCKHPD:
4558    case X86ISD::VUNPCKHPSY:
4559    case X86ISD::VUNPCKHPDY:
4560      DecodeUNPCKHPMask(NumElems, ShuffleMask);
4561      break;
4562    case X86ISD::PUNPCKLBW:
4563    case X86ISD::PUNPCKLWD:
4564    case X86ISD::PUNPCKLDQ:
4565    case X86ISD::PUNPCKLQDQ:
4566      DecodePUNPCKLMask(VT, ShuffleMask);
4567      break;
4568    case X86ISD::UNPCKLPS:
4569    case X86ISD::UNPCKLPD:
4570    case X86ISD::VUNPCKLPSY:
4571    case X86ISD::VUNPCKLPDY:
4572      DecodeUNPCKLPMask(VT, ShuffleMask);
4573      break;
4574    case X86ISD::MOVHLPS:
4575      DecodeMOVHLPSMask(NumElems, ShuffleMask);
4576      break;
4577    case X86ISD::MOVLHPS:
4578      DecodeMOVLHPSMask(NumElems, ShuffleMask);
4579      break;
4580    case X86ISD::PSHUFD:
4581      ImmN = N->getOperand(N->getNumOperands()-1);
4582      DecodePSHUFMask(NumElems,
4583                      cast<ConstantSDNode>(ImmN)->getZExtValue(),
4584                      ShuffleMask);
4585      break;
4586    case X86ISD::PSHUFHW:
4587      ImmN = N->getOperand(N->getNumOperands()-1);
4588      DecodePSHUFHWMask(cast<ConstantSDNode>(ImmN)->getZExtValue(),
4589                        ShuffleMask);
4590      break;
4591    case X86ISD::PSHUFLW:
4592      ImmN = N->getOperand(N->getNumOperands()-1);
4593      DecodePSHUFLWMask(cast<ConstantSDNode>(ImmN)->getZExtValue(),
4594                        ShuffleMask);
4595      break;
4596    case X86ISD::MOVSS:
4597    case X86ISD::MOVSD: {
4598      // The index 0 always comes from the first element of the second source,
4599      // this is why MOVSS and MOVSD are used in the first place. The other
4600      // elements come from the other positions of the first source vector.
4601      unsigned OpNum = (Index == 0) ? 1 : 0;
4602      return getShuffleScalarElt(V.getOperand(OpNum).getNode(), Index, DAG,
4603                                 Depth+1);
4604    }
4605    case X86ISD::VPERMILPS:
4606      ImmN = N->getOperand(N->getNumOperands()-1);
4607      DecodeVPERMILPSMask(4, cast<ConstantSDNode>(ImmN)->getZExtValue(),
4608                        ShuffleMask);
4609      break;
4610    case X86ISD::VPERMILPSY:
4611      ImmN = N->getOperand(N->getNumOperands()-1);
4612      DecodeVPERMILPSMask(8, cast<ConstantSDNode>(ImmN)->getZExtValue(),
4613                        ShuffleMask);
4614      break;
4615    case X86ISD::VPERMILPD:
4616      ImmN = N->getOperand(N->getNumOperands()-1);
4617      DecodeVPERMILPDMask(2, cast<ConstantSDNode>(ImmN)->getZExtValue(),
4618                        ShuffleMask);
4619      break;
4620    case X86ISD::VPERMILPDY:
4621      ImmN = N->getOperand(N->getNumOperands()-1);
4622      DecodeVPERMILPDMask(4, cast<ConstantSDNode>(ImmN)->getZExtValue(),
4623                        ShuffleMask);
4624      break;
4625    case X86ISD::VPERM2F128:
4626      ImmN = N->getOperand(N->getNumOperands()-1);
4627      DecodeVPERM2F128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(),
4628                           ShuffleMask);
4629      break;
4630    case X86ISD::MOVDDUP:
4631    case X86ISD::MOVLHPD:
4632    case X86ISD::MOVLPD:
4633    case X86ISD::MOVLPS:
4634    case X86ISD::MOVSHDUP:
4635    case X86ISD::MOVSLDUP:
4636    case X86ISD::PALIGN:
4637      return SDValue(); // Not yet implemented.
4638    default:
4639      assert(0 && "unknown target shuffle node");
4640      return SDValue();
4641    }
4642
4643    Index = ShuffleMask[Index];
4644    if (Index < 0)
4645      return DAG.getUNDEF(VT.getVectorElementType());
4646
4647    SDValue NewV = (Index < NumElems) ? N->getOperand(0) : N->getOperand(1);
4648    return getShuffleScalarElt(NewV.getNode(), Index % NumElems, DAG,
4649                               Depth+1);
4650  }
4651
4652  // Actual nodes that may contain scalar elements
4653  if (Opcode == ISD::BITCAST) {
4654    V = V.getOperand(0);
4655    EVT SrcVT = V.getValueType();
4656    unsigned NumElems = VT.getVectorNumElements();
4657
4658    if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
4659      return SDValue();
4660  }
4661
4662  if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
4663    return (Index == 0) ? V.getOperand(0)
4664                          : DAG.getUNDEF(VT.getVectorElementType());
4665
4666  if (V.getOpcode() == ISD::BUILD_VECTOR)
4667    return V.getOperand(Index);
4668
4669  return SDValue();
4670}
4671
4672/// getNumOfConsecutiveZeros - Return the number of elements of a vector
4673/// shuffle operation which come from a consecutively from a zero. The
4674/// search can start in two different directions, from left or right.
4675static
4676unsigned getNumOfConsecutiveZeros(SDNode *N, int NumElems,
4677                                  bool ZerosFromLeft, SelectionDAG &DAG) {
4678  int i = 0;
4679
4680  while (i < NumElems) {
4681    unsigned Index = ZerosFromLeft ? i : NumElems-i-1;
4682    SDValue Elt = getShuffleScalarElt(N, Index, DAG, 0);
4683    if (!(Elt.getNode() &&
4684         (Elt.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elt))))
4685      break;
4686    ++i;
4687  }
4688
4689  return i;
4690}
4691
4692/// isShuffleMaskConsecutive - Check if the shuffle mask indicies from MaskI to
4693/// MaskE correspond consecutively to elements from one of the vector operands,
4694/// starting from its index OpIdx. Also tell OpNum which source vector operand.
4695static
4696bool isShuffleMaskConsecutive(ShuffleVectorSDNode *SVOp, int MaskI, int MaskE,
4697                              int OpIdx, int NumElems, unsigned &OpNum) {
4698  bool SeenV1 = false;
4699  bool SeenV2 = false;
4700
4701  for (int i = MaskI; i <= MaskE; ++i, ++OpIdx) {
4702    int Idx = SVOp->getMaskElt(i);
4703    // Ignore undef indicies
4704    if (Idx < 0)
4705      continue;
4706
4707    if (Idx < NumElems)
4708      SeenV1 = true;
4709    else
4710      SeenV2 = true;
4711
4712    // Only accept consecutive elements from the same vector
4713    if ((Idx % NumElems != OpIdx) || (SeenV1 && SeenV2))
4714      return false;
4715  }
4716
4717  OpNum = SeenV1 ? 0 : 1;
4718  return true;
4719}
4720
4721/// isVectorShiftRight - Returns true if the shuffle can be implemented as a
4722/// logical left shift of a vector.
4723static bool isVectorShiftRight(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4724                               bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4725  unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
4726  unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems,
4727              false /* check zeros from right */, DAG);
4728  unsigned OpSrc;
4729
4730  if (!NumZeros)
4731    return false;
4732
4733  // Considering the elements in the mask that are not consecutive zeros,
4734  // check if they consecutively come from only one of the source vectors.
4735  //
4736  //               V1 = {X, A, B, C}     0
4737  //                         \  \  \    /
4738  //   vector_shuffle V1, V2 <1, 2, 3, X>
4739  //
4740  if (!isShuffleMaskConsecutive(SVOp,
4741            0,                   // Mask Start Index
4742            NumElems-NumZeros-1, // Mask End Index
4743            NumZeros,            // Where to start looking in the src vector
4744            NumElems,            // Number of elements in vector
4745            OpSrc))              // Which source operand ?
4746    return false;
4747
4748  isLeft = false;
4749  ShAmt = NumZeros;
4750  ShVal = SVOp->getOperand(OpSrc);
4751  return true;
4752}
4753
4754/// isVectorShiftLeft - Returns true if the shuffle can be implemented as a
4755/// logical left shift of a vector.
4756static bool isVectorShiftLeft(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4757                              bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4758  unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
4759  unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems,
4760              true /* check zeros from left */, DAG);
4761  unsigned OpSrc;
4762
4763  if (!NumZeros)
4764    return false;
4765
4766  // Considering the elements in the mask that are not consecutive zeros,
4767  // check if they consecutively come from only one of the source vectors.
4768  //
4769  //                           0    { A, B, X, X } = V2
4770  //                          / \    /  /
4771  //   vector_shuffle V1, V2 <X, X, 4, 5>
4772  //
4773  if (!isShuffleMaskConsecutive(SVOp,
4774            NumZeros,     // Mask Start Index
4775            NumElems-1,   // Mask End Index
4776            0,            // Where to start looking in the src vector
4777            NumElems,     // Number of elements in vector
4778            OpSrc))       // Which source operand ?
4779    return false;
4780
4781  isLeft = true;
4782  ShAmt = NumZeros;
4783  ShVal = SVOp->getOperand(OpSrc);
4784  return true;
4785}
4786
4787/// isVectorShift - Returns true if the shuffle can be implemented as a
4788/// logical left or right shift of a vector.
4789static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4790                          bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4791  // Although the logic below support any bitwidth size, there are no
4792  // shift instructions which handle more than 128-bit vectors.
4793  if (SVOp->getValueType(0).getSizeInBits() > 128)
4794    return false;
4795
4796  if (isVectorShiftLeft(SVOp, DAG, isLeft, ShVal, ShAmt) ||
4797      isVectorShiftRight(SVOp, DAG, isLeft, ShVal, ShAmt))
4798    return true;
4799
4800  return false;
4801}
4802
4803/// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
4804///
4805static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
4806                                       unsigned NumNonZero, unsigned NumZero,
4807                                       SelectionDAG &DAG,
4808                                       const TargetLowering &TLI) {
4809  if (NumNonZero > 8)
4810    return SDValue();
4811
4812  DebugLoc dl = Op.getDebugLoc();
4813  SDValue V(0, 0);
4814  bool First = true;
4815  for (unsigned i = 0; i < 16; ++i) {
4816    bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
4817    if (ThisIsNonZero && First) {
4818      if (NumZero)
4819        V = getZeroVector(MVT::v8i16, true, DAG, dl);
4820      else
4821        V = DAG.getUNDEF(MVT::v8i16);
4822      First = false;
4823    }
4824
4825    if ((i & 1) != 0) {
4826      SDValue ThisElt(0, 0), LastElt(0, 0);
4827      bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
4828      if (LastIsNonZero) {
4829        LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
4830                              MVT::i16, Op.getOperand(i-1));
4831      }
4832      if (ThisIsNonZero) {
4833        ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
4834        ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
4835                              ThisElt, DAG.getConstant(8, MVT::i8));
4836        if (LastIsNonZero)
4837          ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
4838      } else
4839        ThisElt = LastElt;
4840
4841      if (ThisElt.getNode())
4842        V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
4843                        DAG.getIntPtrConstant(i/2));
4844    }
4845  }
4846
4847  return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V);
4848}
4849
4850/// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
4851///
4852static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
4853                                     unsigned NumNonZero, unsigned NumZero,
4854                                     SelectionDAG &DAG,
4855                                     const TargetLowering &TLI) {
4856  if (NumNonZero > 4)
4857    return SDValue();
4858
4859  DebugLoc dl = Op.getDebugLoc();
4860  SDValue V(0, 0);
4861  bool First = true;
4862  for (unsigned i = 0; i < 8; ++i) {
4863    bool isNonZero = (NonZeros & (1 << i)) != 0;
4864    if (isNonZero) {
4865      if (First) {
4866        if (NumZero)
4867          V = getZeroVector(MVT::v8i16, true, DAG, dl);
4868        else
4869          V = DAG.getUNDEF(MVT::v8i16);
4870        First = false;
4871      }
4872      V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
4873                      MVT::v8i16, V, Op.getOperand(i),
4874                      DAG.getIntPtrConstant(i));
4875    }
4876  }
4877
4878  return V;
4879}
4880
4881/// getVShift - Return a vector logical shift node.
4882///
4883static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
4884                         unsigned NumBits, SelectionDAG &DAG,
4885                         const TargetLowering &TLI, DebugLoc dl) {
4886  assert(VT.getSizeInBits() == 128 && "Unknown type for VShift");
4887  EVT ShVT = MVT::v2i64;
4888  unsigned Opc = isLeft ? X86ISD::VSHL : X86ISD::VSRL;
4889  SrcOp = DAG.getNode(ISD::BITCAST, dl, ShVT, SrcOp);
4890  return DAG.getNode(ISD::BITCAST, dl, VT,
4891                     DAG.getNode(Opc, dl, ShVT, SrcOp,
4892                             DAG.getConstant(NumBits,
4893                                  TLI.getShiftAmountTy(SrcOp.getValueType()))));
4894}
4895
4896SDValue
4897X86TargetLowering::LowerAsSplatVectorLoad(SDValue SrcOp, EVT VT, DebugLoc dl,
4898                                          SelectionDAG &DAG) const {
4899
4900  // Check if the scalar load can be widened into a vector load. And if
4901  // the address is "base + cst" see if the cst can be "absorbed" into
4902  // the shuffle mask.
4903  if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
4904    SDValue Ptr = LD->getBasePtr();
4905    if (!ISD::isNormalLoad(LD) || LD->isVolatile())
4906      return SDValue();
4907    EVT PVT = LD->getValueType(0);
4908    if (PVT != MVT::i32 && PVT != MVT::f32)
4909      return SDValue();
4910
4911    int FI = -1;
4912    int64_t Offset = 0;
4913    if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
4914      FI = FINode->getIndex();
4915      Offset = 0;
4916    } else if (DAG.isBaseWithConstantOffset(Ptr) &&
4917               isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
4918      FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
4919      Offset = Ptr.getConstantOperandVal(1);
4920      Ptr = Ptr.getOperand(0);
4921    } else {
4922      return SDValue();
4923    }
4924
4925    // FIXME: 256-bit vector instructions don't require a strict alignment,
4926    // improve this code to support it better.
4927    unsigned RequiredAlign = VT.getSizeInBits()/8;
4928    SDValue Chain = LD->getChain();
4929    // Make sure the stack object alignment is at least 16 or 32.
4930    MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
4931    if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
4932      if (MFI->isFixedObjectIndex(FI)) {
4933        // Can't change the alignment. FIXME: It's possible to compute
4934        // the exact stack offset and reference FI + adjust offset instead.
4935        // If someone *really* cares about this. That's the way to implement it.
4936        return SDValue();
4937      } else {
4938        MFI->setObjectAlignment(FI, RequiredAlign);
4939      }
4940    }
4941
4942    // (Offset % 16 or 32) must be multiple of 4. Then address is then
4943    // Ptr + (Offset & ~15).
4944    if (Offset < 0)
4945      return SDValue();
4946    if ((Offset % RequiredAlign) & 3)
4947      return SDValue();
4948    int64_t StartOffset = Offset & ~(RequiredAlign-1);
4949    if (StartOffset)
4950      Ptr = DAG.getNode(ISD::ADD, Ptr.getDebugLoc(), Ptr.getValueType(),
4951                        Ptr,DAG.getConstant(StartOffset, Ptr.getValueType()));
4952
4953    int EltNo = (Offset - StartOffset) >> 2;
4954    int NumElems = VT.getVectorNumElements();
4955
4956    EVT CanonVT = VT.getSizeInBits() == 128 ? MVT::v4i32 : MVT::v8i32;
4957    EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
4958    SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
4959                             LD->getPointerInfo().getWithOffset(StartOffset),
4960                             false, false, 0);
4961
4962    // Canonicalize it to a v4i32 or v8i32 shuffle.
4963    SmallVector<int, 8> Mask;
4964    for (int i = 0; i < NumElems; ++i)
4965      Mask.push_back(EltNo);
4966
4967    V1 = DAG.getNode(ISD::BITCAST, dl, CanonVT, V1);
4968    return DAG.getNode(ISD::BITCAST, dl, NVT,
4969                       DAG.getVectorShuffle(CanonVT, dl, V1,
4970                                            DAG.getUNDEF(CanonVT),&Mask[0]));
4971  }
4972
4973  return SDValue();
4974}
4975
4976/// EltsFromConsecutiveLoads - Given the initializing elements 'Elts' of a
4977/// vector of type 'VT', see if the elements can be replaced by a single large
4978/// load which has the same value as a build_vector whose operands are 'elts'.
4979///
4980/// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
4981///
4982/// FIXME: we'd also like to handle the case where the last elements are zero
4983/// rather than undef via VZEXT_LOAD, but we do not detect that case today.
4984/// There's even a handy isZeroNode for that purpose.
4985static SDValue EltsFromConsecutiveLoads(EVT VT, SmallVectorImpl<SDValue> &Elts,
4986                                        DebugLoc &DL, SelectionDAG &DAG) {
4987  EVT EltVT = VT.getVectorElementType();
4988  unsigned NumElems = Elts.size();
4989
4990  LoadSDNode *LDBase = NULL;
4991  unsigned LastLoadedElt = -1U;
4992
4993  // For each element in the initializer, see if we've found a load or an undef.
4994  // If we don't find an initial load element, or later load elements are
4995  // non-consecutive, bail out.
4996  for (unsigned i = 0; i < NumElems; ++i) {
4997    SDValue Elt = Elts[i];
4998
4999    if (!Elt.getNode() ||
5000        (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
5001      return SDValue();
5002    if (!LDBase) {
5003      if (Elt.getNode()->getOpcode() == ISD::UNDEF)
5004        return SDValue();
5005      LDBase = cast<LoadSDNode>(Elt.getNode());
5006      LastLoadedElt = i;
5007      continue;
5008    }
5009    if (Elt.getOpcode() == ISD::UNDEF)
5010      continue;
5011
5012    LoadSDNode *LD = cast<LoadSDNode>(Elt);
5013    if (!DAG.isConsecutiveLoad(LD, LDBase, EltVT.getSizeInBits()/8, i))
5014      return SDValue();
5015    LastLoadedElt = i;
5016  }
5017
5018  // If we have found an entire vector of loads and undefs, then return a large
5019  // load of the entire vector width starting at the base pointer.  If we found
5020  // consecutive loads for the low half, generate a vzext_load node.
5021  if (LastLoadedElt == NumElems - 1) {
5022    if (DAG.InferPtrAlignment(LDBase->getBasePtr()) >= 16)
5023      return DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5024                         LDBase->getPointerInfo(),
5025                         LDBase->isVolatile(), LDBase->isNonTemporal(), 0);
5026    return DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5027                       LDBase->getPointerInfo(),
5028                       LDBase->isVolatile(), LDBase->isNonTemporal(),
5029                       LDBase->getAlignment());
5030  } else if (NumElems == 4 && LastLoadedElt == 1 &&
5031             DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) {
5032    SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
5033    SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
5034    SDValue ResNode =
5035        DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops, 2, MVT::i64,
5036                                LDBase->getPointerInfo(),
5037                                LDBase->getAlignment(),
5038                                false/*isVolatile*/, true/*ReadMem*/,
5039                                false/*WriteMem*/);
5040    return DAG.getNode(ISD::BITCAST, DL, VT, ResNode);
5041  }
5042  return SDValue();
5043}
5044
5045SDValue
5046X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
5047  DebugLoc dl = Op.getDebugLoc();
5048
5049  EVT VT = Op.getValueType();
5050  EVT ExtVT = VT.getVectorElementType();
5051  unsigned NumElems = Op.getNumOperands();
5052
5053  // Vectors containing all zeros can be matched by pxor and xorps later
5054  if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5055    // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
5056    // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
5057    if (Op.getValueType() == MVT::v4i32 ||
5058        Op.getValueType() == MVT::v8i32)
5059      return Op;
5060
5061    return getZeroVector(Op.getValueType(), Subtarget->hasXMMInt(), DAG, dl);
5062  }
5063
5064  // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
5065  // vectors or broken into v4i32 operations on 256-bit vectors.
5066  if (ISD::isBuildVectorAllOnes(Op.getNode())) {
5067    if (Op.getValueType() == MVT::v4i32)
5068      return Op;
5069
5070    return getOnesVector(Op.getValueType(), DAG, dl);
5071  }
5072
5073  unsigned EVTBits = ExtVT.getSizeInBits();
5074
5075  unsigned NumZero  = 0;
5076  unsigned NumNonZero = 0;
5077  unsigned NonZeros = 0;
5078  bool IsAllConstants = true;
5079  SmallSet<SDValue, 8> Values;
5080  for (unsigned i = 0; i < NumElems; ++i) {
5081    SDValue Elt = Op.getOperand(i);
5082    if (Elt.getOpcode() == ISD::UNDEF)
5083      continue;
5084    Values.insert(Elt);
5085    if (Elt.getOpcode() != ISD::Constant &&
5086        Elt.getOpcode() != ISD::ConstantFP)
5087      IsAllConstants = false;
5088    if (X86::isZeroNode(Elt))
5089      NumZero++;
5090    else {
5091      NonZeros |= (1 << i);
5092      NumNonZero++;
5093    }
5094  }
5095
5096  // All undef vector. Return an UNDEF.  All zero vectors were handled above.
5097  if (NumNonZero == 0)
5098    return DAG.getUNDEF(VT);
5099
5100  // Special case for single non-zero, non-undef, element.
5101  if (NumNonZero == 1) {
5102    unsigned Idx = CountTrailingZeros_32(NonZeros);
5103    SDValue Item = Op.getOperand(Idx);
5104
5105    // If this is an insertion of an i64 value on x86-32, and if the top bits of
5106    // the value are obviously zero, truncate the value to i32 and do the
5107    // insertion that way.  Only do this if the value is non-constant or if the
5108    // value is a constant being inserted into element 0.  It is cheaper to do
5109    // a constant pool load than it is to do a movd + shuffle.
5110    if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
5111        (!IsAllConstants || Idx == 0)) {
5112      if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
5113        // Handle SSE only.
5114        assert(VT == MVT::v2i64 && "Expected an SSE value type!");
5115        EVT VecVT = MVT::v4i32;
5116        unsigned VecElts = 4;
5117
5118        // Truncate the value (which may itself be a constant) to i32, and
5119        // convert it to a vector with movd (S2V+shuffle to zero extend).
5120        Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
5121        Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
5122        Item = getShuffleVectorZeroOrUndef(Item, 0, true,
5123                                           Subtarget->hasXMMInt(), DAG);
5124
5125        // Now we have our 32-bit value zero extended in the low element of
5126        // a vector.  If Idx != 0, swizzle it into place.
5127        if (Idx != 0) {
5128          SmallVector<int, 4> Mask;
5129          Mask.push_back(Idx);
5130          for (unsigned i = 1; i != VecElts; ++i)
5131            Mask.push_back(i);
5132          Item = DAG.getVectorShuffle(VecVT, dl, Item,
5133                                      DAG.getUNDEF(Item.getValueType()),
5134                                      &Mask[0]);
5135        }
5136        return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Item);
5137      }
5138    }
5139
5140    // If we have a constant or non-constant insertion into the low element of
5141    // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
5142    // the rest of the elements.  This will be matched as movd/movq/movss/movsd
5143    // depending on what the source datatype is.
5144    if (Idx == 0) {
5145      if (NumZero == 0) {
5146        return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5147      } else if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
5148          (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
5149        Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5150        // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
5151        return getShuffleVectorZeroOrUndef(Item, 0, true,Subtarget->hasXMMInt(),
5152                                           DAG);
5153      } else if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
5154        Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
5155        assert(VT.getSizeInBits() == 128 && "Expected an SSE value type!");
5156        EVT MiddleVT = MVT::v4i32;
5157        Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MiddleVT, Item);
5158        Item = getShuffleVectorZeroOrUndef(Item, 0, true,
5159                                           Subtarget->hasXMMInt(), DAG);
5160        return DAG.getNode(ISD::BITCAST, dl, VT, Item);
5161      }
5162    }
5163
5164    // Is it a vector logical left shift?
5165    if (NumElems == 2 && Idx == 1 &&
5166        X86::isZeroNode(Op.getOperand(0)) &&
5167        !X86::isZeroNode(Op.getOperand(1))) {
5168      unsigned NumBits = VT.getSizeInBits();
5169      return getVShift(true, VT,
5170                       DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
5171                                   VT, Op.getOperand(1)),
5172                       NumBits/2, DAG, *this, dl);
5173    }
5174
5175    if (IsAllConstants) // Otherwise, it's better to do a constpool load.
5176      return SDValue();
5177
5178    // Otherwise, if this is a vector with i32 or f32 elements, and the element
5179    // is a non-constant being inserted into an element other than the low one,
5180    // we can't use a constant pool load.  Instead, use SCALAR_TO_VECTOR (aka
5181    // movd/movss) to move this into the low element, then shuffle it into
5182    // place.
5183    if (EVTBits == 32) {
5184      Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5185
5186      // Turn it into a shuffle of zero and zero-extended scalar to vector.
5187      Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0,
5188                                         Subtarget->hasXMMInt(), DAG);
5189      SmallVector<int, 8> MaskVec;
5190      for (unsigned i = 0; i < NumElems; i++)
5191        MaskVec.push_back(i == Idx ? 0 : 1);
5192      return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
5193    }
5194  }
5195
5196  // Splat is obviously ok. Let legalizer expand it to a shuffle.
5197  if (Values.size() == 1) {
5198    if (EVTBits == 32) {
5199      // Instead of a shuffle like this:
5200      // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
5201      // Check if it's possible to issue this instead.
5202      // shuffle (vload ptr)), undef, <1, 1, 1, 1>
5203      unsigned Idx = CountTrailingZeros_32(NonZeros);
5204      SDValue Item = Op.getOperand(Idx);
5205      if (Op.getNode()->isOnlyUserOf(Item.getNode()))
5206        return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
5207    }
5208    return SDValue();
5209  }
5210
5211  // A vector full of immediates; various special cases are already
5212  // handled, so this is best done with a single constant-pool load.
5213  if (IsAllConstants)
5214    return SDValue();
5215
5216  // For AVX-length vectors, build the individual 128-bit pieces and use
5217  // shuffles to put them in place.
5218  if (VT.getSizeInBits() == 256 && !ISD::isBuildVectorAllZeros(Op.getNode())) {
5219    SmallVector<SDValue, 32> V;
5220    for (unsigned i = 0; i < NumElems; ++i)
5221      V.push_back(Op.getOperand(i));
5222
5223    EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
5224
5225    // Build both the lower and upper subvector.
5226    SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[0], NumElems/2);
5227    SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[NumElems / 2],
5228                                NumElems/2);
5229
5230    // Recreate the wider vector with the lower and upper part.
5231    SDValue Vec = Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, VT), Lower,
5232                                DAG.getConstant(0, MVT::i32), DAG, dl);
5233    return Insert128BitVector(Vec, Upper, DAG.getConstant(NumElems/2, MVT::i32),
5234                              DAG, dl);
5235  }
5236
5237  // Let legalizer expand 2-wide build_vectors.
5238  if (EVTBits == 64) {
5239    if (NumNonZero == 1) {
5240      // One half is zero or undef.
5241      unsigned Idx = CountTrailingZeros_32(NonZeros);
5242      SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
5243                                 Op.getOperand(Idx));
5244      return getShuffleVectorZeroOrUndef(V2, Idx, true,
5245                                         Subtarget->hasXMMInt(), DAG);
5246    }
5247    return SDValue();
5248  }
5249
5250  // If element VT is < 32 bits, convert it to inserts into a zero vector.
5251  if (EVTBits == 8 && NumElems == 16) {
5252    SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
5253                                        *this);
5254    if (V.getNode()) return V;
5255  }
5256
5257  if (EVTBits == 16 && NumElems == 8) {
5258    SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
5259                                      *this);
5260    if (V.getNode()) return V;
5261  }
5262
5263  // If element VT is == 32 bits, turn it into a number of shuffles.
5264  SmallVector<SDValue, 8> V;
5265  V.resize(NumElems);
5266  if (NumElems == 4 && NumZero > 0) {
5267    for (unsigned i = 0; i < 4; ++i) {
5268      bool isZero = !(NonZeros & (1 << i));
5269      if (isZero)
5270        V[i] = getZeroVector(VT, Subtarget->hasXMMInt(), DAG, dl);
5271      else
5272        V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
5273    }
5274
5275    for (unsigned i = 0; i < 2; ++i) {
5276      switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
5277        default: break;
5278        case 0:
5279          V[i] = V[i*2];  // Must be a zero vector.
5280          break;
5281        case 1:
5282          V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
5283          break;
5284        case 2:
5285          V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
5286          break;
5287        case 3:
5288          V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
5289          break;
5290      }
5291    }
5292
5293    SmallVector<int, 8> MaskVec;
5294    bool Reverse = (NonZeros & 0x3) == 2;
5295    for (unsigned i = 0; i < 2; ++i)
5296      MaskVec.push_back(Reverse ? 1-i : i);
5297    Reverse = ((NonZeros & (0x3 << 2)) >> 2) == 2;
5298    for (unsigned i = 0; i < 2; ++i)
5299      MaskVec.push_back(Reverse ? 1-i+NumElems : i+NumElems);
5300    return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
5301  }
5302
5303  if (Values.size() > 1 && VT.getSizeInBits() == 128) {
5304    // Check for a build vector of consecutive loads.
5305    for (unsigned i = 0; i < NumElems; ++i)
5306      V[i] = Op.getOperand(i);
5307
5308    // Check for elements which are consecutive loads.
5309    SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG);
5310    if (LD.getNode())
5311      return LD;
5312
5313    // For SSE 4.1, use insertps to put the high elements into the low element.
5314    if (getSubtarget()->hasSSE41() || getSubtarget()->hasAVX()) {
5315      SDValue Result;
5316      if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
5317        Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
5318      else
5319        Result = DAG.getUNDEF(VT);
5320
5321      for (unsigned i = 1; i < NumElems; ++i) {
5322        if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
5323        Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
5324                             Op.getOperand(i), DAG.getIntPtrConstant(i));
5325      }
5326      return Result;
5327    }
5328
5329    // Otherwise, expand into a number of unpckl*, start by extending each of
5330    // our (non-undef) elements to the full vector width with the element in the
5331    // bottom slot of the vector (which generates no code for SSE).
5332    for (unsigned i = 0; i < NumElems; ++i) {
5333      if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
5334        V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
5335      else
5336        V[i] = DAG.getUNDEF(VT);
5337    }
5338
5339    // Next, we iteratively mix elements, e.g. for v4f32:
5340    //   Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
5341    //         : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
5342    //   Step 2: unpcklps X, Y ==>    <3, 2, 1, 0>
5343    unsigned EltStride = NumElems >> 1;
5344    while (EltStride != 0) {
5345      for (unsigned i = 0; i < EltStride; ++i) {
5346        // If V[i+EltStride] is undef and this is the first round of mixing,
5347        // then it is safe to just drop this shuffle: V[i] is already in the
5348        // right place, the one element (since it's the first round) being
5349        // inserted as undef can be dropped.  This isn't safe for successive
5350        // rounds because they will permute elements within both vectors.
5351        if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
5352            EltStride == NumElems/2)
5353          continue;
5354
5355        V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
5356      }
5357      EltStride >>= 1;
5358    }
5359    return V[0];
5360  }
5361  return SDValue();
5362}
5363
5364// LowerMMXCONCAT_VECTORS - We support concatenate two MMX registers and place
5365// them in a MMX register.  This is better than doing a stack convert.
5366static SDValue LowerMMXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5367  DebugLoc dl = Op.getDebugLoc();
5368  EVT ResVT = Op.getValueType();
5369
5370  assert(ResVT == MVT::v2i64 || ResVT == MVT::v4i32 ||
5371         ResVT == MVT::v8i16 || ResVT == MVT::v16i8);
5372  int Mask[2];
5373  SDValue InVec = DAG.getNode(ISD::BITCAST,dl, MVT::v1i64, Op.getOperand(0));
5374  SDValue VecOp = DAG.getNode(X86ISD::MOVQ2DQ, dl, MVT::v2i64, InVec);
5375  InVec = Op.getOperand(1);
5376  if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
5377    unsigned NumElts = ResVT.getVectorNumElements();
5378    VecOp = DAG.getNode(ISD::BITCAST, dl, ResVT, VecOp);
5379    VecOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ResVT, VecOp,
5380                       InVec.getOperand(0), DAG.getIntPtrConstant(NumElts/2+1));
5381  } else {
5382    InVec = DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, InVec);
5383    SDValue VecOp2 = DAG.getNode(X86ISD::MOVQ2DQ, dl, MVT::v2i64, InVec);
5384    Mask[0] = 0; Mask[1] = 2;
5385    VecOp = DAG.getVectorShuffle(MVT::v2i64, dl, VecOp, VecOp2, Mask);
5386  }
5387  return DAG.getNode(ISD::BITCAST, dl, ResVT, VecOp);
5388}
5389
5390// LowerAVXCONCAT_VECTORS - 256-bit AVX can use the vinsertf128 instruction
5391// to create 256-bit vectors from two other 128-bit ones.
5392static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5393  DebugLoc dl = Op.getDebugLoc();
5394  EVT ResVT = Op.getValueType();
5395
5396  assert(ResVT.getSizeInBits() == 256 && "Value type must be 256-bit wide");
5397
5398  SDValue V1 = Op.getOperand(0);
5399  SDValue V2 = Op.getOperand(1);
5400  unsigned NumElems = ResVT.getVectorNumElements();
5401
5402  SDValue V = Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, ResVT), V1,
5403                                 DAG.getConstant(0, MVT::i32), DAG, dl);
5404  return Insert128BitVector(V, V2, DAG.getConstant(NumElems/2, MVT::i32),
5405                            DAG, dl);
5406}
5407
5408SDValue
5409X86TargetLowering::LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) const {
5410  EVT ResVT = Op.getValueType();
5411
5412  assert(Op.getNumOperands() == 2);
5413  assert((ResVT.getSizeInBits() == 128 || ResVT.getSizeInBits() == 256) &&
5414         "Unsupported CONCAT_VECTORS for value type");
5415
5416  // We support concatenate two MMX registers and place them in a MMX register.
5417  // This is better than doing a stack convert.
5418  if (ResVT.is128BitVector())
5419    return LowerMMXCONCAT_VECTORS(Op, DAG);
5420
5421  // 256-bit AVX can use the vinsertf128 instruction to create 256-bit vectors
5422  // from two other 128-bit ones.
5423  return LowerAVXCONCAT_VECTORS(Op, DAG);
5424}
5425
5426// v8i16 shuffles - Prefer shuffles in the following order:
5427// 1. [all]   pshuflw, pshufhw, optional move
5428// 2. [ssse3] 1 x pshufb
5429// 3. [ssse3] 2 x pshufb + 1 x por
5430// 4. [all]   mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
5431SDValue
5432X86TargetLowering::LowerVECTOR_SHUFFLEv8i16(SDValue Op,
5433                                            SelectionDAG &DAG) const {
5434  ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5435  SDValue V1 = SVOp->getOperand(0);
5436  SDValue V2 = SVOp->getOperand(1);
5437  DebugLoc dl = SVOp->getDebugLoc();
5438  SmallVector<int, 8> MaskVals;
5439
5440  // Determine if more than 1 of the words in each of the low and high quadwords
5441  // of the result come from the same quadword of one of the two inputs.  Undef
5442  // mask values count as coming from any quadword, for better codegen.
5443  SmallVector<unsigned, 4> LoQuad(4);
5444  SmallVector<unsigned, 4> HiQuad(4);
5445  BitVector InputQuads(4);
5446  for (unsigned i = 0; i < 8; ++i) {
5447    SmallVectorImpl<unsigned> &Quad = i < 4 ? LoQuad : HiQuad;
5448    int EltIdx = SVOp->getMaskElt(i);
5449    MaskVals.push_back(EltIdx);
5450    if (EltIdx < 0) {
5451      ++Quad[0];
5452      ++Quad[1];
5453      ++Quad[2];
5454      ++Quad[3];
5455      continue;
5456    }
5457    ++Quad[EltIdx / 4];
5458    InputQuads.set(EltIdx / 4);
5459  }
5460
5461  int BestLoQuad = -1;
5462  unsigned MaxQuad = 1;
5463  for (unsigned i = 0; i < 4; ++i) {
5464    if (LoQuad[i] > MaxQuad) {
5465      BestLoQuad = i;
5466      MaxQuad = LoQuad[i];
5467    }
5468  }
5469
5470  int BestHiQuad = -1;
5471  MaxQuad = 1;
5472  for (unsigned i = 0; i < 4; ++i) {
5473    if (HiQuad[i] > MaxQuad) {
5474      BestHiQuad = i;
5475      MaxQuad = HiQuad[i];
5476    }
5477  }
5478
5479  // For SSSE3, If all 8 words of the result come from only 1 quadword of each
5480  // of the two input vectors, shuffle them into one input vector so only a
5481  // single pshufb instruction is necessary. If There are more than 2 input
5482  // quads, disable the next transformation since it does not help SSSE3.
5483  bool V1Used = InputQuads[0] || InputQuads[1];
5484  bool V2Used = InputQuads[2] || InputQuads[3];
5485  if (Subtarget->hasSSSE3() || Subtarget->hasAVX()) {
5486    if (InputQuads.count() == 2 && V1Used && V2Used) {
5487      BestLoQuad = InputQuads.find_first();
5488      BestHiQuad = InputQuads.find_next(BestLoQuad);
5489    }
5490    if (InputQuads.count() > 2) {
5491      BestLoQuad = -1;
5492      BestHiQuad = -1;
5493    }
5494  }
5495
5496  // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
5497  // the shuffle mask.  If a quad is scored as -1, that means that it contains
5498  // words from all 4 input quadwords.
5499  SDValue NewV;
5500  if (BestLoQuad >= 0 || BestHiQuad >= 0) {
5501    SmallVector<int, 8> MaskV;
5502    MaskV.push_back(BestLoQuad < 0 ? 0 : BestLoQuad);
5503    MaskV.push_back(BestHiQuad < 0 ? 1 : BestHiQuad);
5504    NewV = DAG.getVectorShuffle(MVT::v2i64, dl,
5505                  DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1),
5506                  DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2), &MaskV[0]);
5507    NewV = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, NewV);
5508
5509    // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
5510    // source words for the shuffle, to aid later transformations.
5511    bool AllWordsInNewV = true;
5512    bool InOrder[2] = { true, true };
5513    for (unsigned i = 0; i != 8; ++i) {
5514      int idx = MaskVals[i];
5515      if (idx != (int)i)
5516        InOrder[i/4] = false;
5517      if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
5518        continue;
5519      AllWordsInNewV = false;
5520      break;
5521    }
5522
5523    bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
5524    if (AllWordsInNewV) {
5525      for (int i = 0; i != 8; ++i) {
5526        int idx = MaskVals[i];
5527        if (idx < 0)
5528          continue;
5529        idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
5530        if ((idx != i) && idx < 4)
5531          pshufhw = false;
5532        if ((idx != i) && idx > 3)
5533          pshuflw = false;
5534      }
5535      V1 = NewV;
5536      V2Used = false;
5537      BestLoQuad = 0;
5538      BestHiQuad = 1;
5539    }
5540
5541    // If we've eliminated the use of V2, and the new mask is a pshuflw or
5542    // pshufhw, that's as cheap as it gets.  Return the new shuffle.
5543    if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
5544      unsigned Opc = pshufhw ? X86ISD::PSHUFHW : X86ISD::PSHUFLW;
5545      unsigned TargetMask = 0;
5546      NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV,
5547                                  DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
5548      TargetMask = pshufhw ? X86::getShufflePSHUFHWImmediate(NewV.getNode()):
5549                             X86::getShufflePSHUFLWImmediate(NewV.getNode());
5550      V1 = NewV.getOperand(0);
5551      return getTargetShuffleNode(Opc, dl, MVT::v8i16, V1, TargetMask, DAG);
5552    }
5553  }
5554
5555  // If we have SSSE3, and all words of the result are from 1 input vector,
5556  // case 2 is generated, otherwise case 3 is generated.  If no SSSE3
5557  // is present, fall back to case 4.
5558  if (Subtarget->hasSSSE3() || Subtarget->hasAVX()) {
5559    SmallVector<SDValue,16> pshufbMask;
5560
5561    // If we have elements from both input vectors, set the high bit of the
5562    // shuffle mask element to zero out elements that come from V2 in the V1
5563    // mask, and elements that come from V1 in the V2 mask, so that the two
5564    // results can be OR'd together.
5565    bool TwoInputs = V1Used && V2Used;
5566    for (unsigned i = 0; i != 8; ++i) {
5567      int EltIdx = MaskVals[i] * 2;
5568      if (TwoInputs && (EltIdx >= 16)) {
5569        pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
5570        pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
5571        continue;
5572      }
5573      pshufbMask.push_back(DAG.getConstant(EltIdx,   MVT::i8));
5574      pshufbMask.push_back(DAG.getConstant(EltIdx+1, MVT::i8));
5575    }
5576    V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V1);
5577    V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
5578                     DAG.getNode(ISD::BUILD_VECTOR, dl,
5579                                 MVT::v16i8, &pshufbMask[0], 16));
5580    if (!TwoInputs)
5581      return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5582
5583    // Calculate the shuffle mask for the second input, shuffle it, and
5584    // OR it with the first shuffled input.
5585    pshufbMask.clear();
5586    for (unsigned i = 0; i != 8; ++i) {
5587      int EltIdx = MaskVals[i] * 2;
5588      if (EltIdx < 16) {
5589        pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
5590        pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
5591        continue;
5592      }
5593      pshufbMask.push_back(DAG.getConstant(EltIdx - 16, MVT::i8));
5594      pshufbMask.push_back(DAG.getConstant(EltIdx - 15, MVT::i8));
5595    }
5596    V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V2);
5597    V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
5598                     DAG.getNode(ISD::BUILD_VECTOR, dl,
5599                                 MVT::v16i8, &pshufbMask[0], 16));
5600    V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
5601    return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5602  }
5603
5604  // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
5605  // and update MaskVals with new element order.
5606  BitVector InOrder(8);
5607  if (BestLoQuad >= 0) {
5608    SmallVector<int, 8> MaskV;
5609    for (int i = 0; i != 4; ++i) {
5610      int idx = MaskVals[i];
5611      if (idx < 0) {
5612        MaskV.push_back(-1);
5613        InOrder.set(i);
5614      } else if ((idx / 4) == BestLoQuad) {
5615        MaskV.push_back(idx & 3);
5616        InOrder.set(i);
5617      } else {
5618        MaskV.push_back(-1);
5619      }
5620    }
5621    for (unsigned i = 4; i != 8; ++i)
5622      MaskV.push_back(i);
5623    NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
5624                                &MaskV[0]);
5625
5626    if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE &&
5627        (Subtarget->hasSSSE3() || Subtarget->hasAVX()))
5628      NewV = getTargetShuffleNode(X86ISD::PSHUFLW, dl, MVT::v8i16,
5629                               NewV.getOperand(0),
5630                               X86::getShufflePSHUFLWImmediate(NewV.getNode()),
5631                               DAG);
5632  }
5633
5634  // If BestHi >= 0, generate a pshufhw to put the high elements in order,
5635  // and update MaskVals with the new element order.
5636  if (BestHiQuad >= 0) {
5637    SmallVector<int, 8> MaskV;
5638    for (unsigned i = 0; i != 4; ++i)
5639      MaskV.push_back(i);
5640    for (unsigned i = 4; i != 8; ++i) {
5641      int idx = MaskVals[i];
5642      if (idx < 0) {
5643        MaskV.push_back(-1);
5644        InOrder.set(i);
5645      } else if ((idx / 4) == BestHiQuad) {
5646        MaskV.push_back((idx & 3) + 4);
5647        InOrder.set(i);
5648      } else {
5649        MaskV.push_back(-1);
5650      }
5651    }
5652    NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
5653                                &MaskV[0]);
5654
5655    if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE &&
5656        (Subtarget->hasSSSE3() || Subtarget->hasAVX()))
5657      NewV = getTargetShuffleNode(X86ISD::PSHUFHW, dl, MVT::v8i16,
5658                              NewV.getOperand(0),
5659                              X86::getShufflePSHUFHWImmediate(NewV.getNode()),
5660                              DAG);
5661  }
5662
5663  // In case BestHi & BestLo were both -1, which means each quadword has a word
5664  // from each of the four input quadwords, calculate the InOrder bitvector now
5665  // before falling through to the insert/extract cleanup.
5666  if (BestLoQuad == -1 && BestHiQuad == -1) {
5667    NewV = V1;
5668    for (int i = 0; i != 8; ++i)
5669      if (MaskVals[i] < 0 || MaskVals[i] == i)
5670        InOrder.set(i);
5671  }
5672
5673  // The other elements are put in the right place using pextrw and pinsrw.
5674  for (unsigned i = 0; i != 8; ++i) {
5675    if (InOrder[i])
5676      continue;
5677    int EltIdx = MaskVals[i];
5678    if (EltIdx < 0)
5679      continue;
5680    SDValue ExtOp = (EltIdx < 8)
5681    ? DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
5682                  DAG.getIntPtrConstant(EltIdx))
5683    : DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
5684                  DAG.getIntPtrConstant(EltIdx - 8));
5685    NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
5686                       DAG.getIntPtrConstant(i));
5687  }
5688  return NewV;
5689}
5690
5691// v16i8 shuffles - Prefer shuffles in the following order:
5692// 1. [ssse3] 1 x pshufb
5693// 2. [ssse3] 2 x pshufb + 1 x por
5694// 3. [all]   v8i16 shuffle + N x pextrw + rotate + pinsrw
5695static
5696SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
5697                                 SelectionDAG &DAG,
5698                                 const X86TargetLowering &TLI) {
5699  SDValue V1 = SVOp->getOperand(0);
5700  SDValue V2 = SVOp->getOperand(1);
5701  DebugLoc dl = SVOp->getDebugLoc();
5702  SmallVector<int, 16> MaskVals;
5703  SVOp->getMask(MaskVals);
5704
5705  // If we have SSSE3, case 1 is generated when all result bytes come from
5706  // one of  the inputs.  Otherwise, case 2 is generated.  If no SSSE3 is
5707  // present, fall back to case 3.
5708  // FIXME: kill V2Only once shuffles are canonizalized by getNode.
5709  bool V1Only = true;
5710  bool V2Only = true;
5711  for (unsigned i = 0; i < 16; ++i) {
5712    int EltIdx = MaskVals[i];
5713    if (EltIdx < 0)
5714      continue;
5715    if (EltIdx < 16)
5716      V2Only = false;
5717    else
5718      V1Only = false;
5719  }
5720
5721  // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
5722  if (TLI.getSubtarget()->hasSSSE3() || TLI.getSubtarget()->hasAVX()) {
5723    SmallVector<SDValue,16> pshufbMask;
5724
5725    // If all result elements are from one input vector, then only translate
5726    // undef mask values to 0x80 (zero out result) in the pshufb mask.
5727    //
5728    // Otherwise, we have elements from both input vectors, and must zero out
5729    // elements that come from V2 in the first mask, and V1 in the second mask
5730    // so that we can OR them together.
5731    bool TwoInputs = !(V1Only || V2Only);
5732    for (unsigned i = 0; i != 16; ++i) {
5733      int EltIdx = MaskVals[i];
5734      if (EltIdx < 0 || (TwoInputs && EltIdx >= 16)) {
5735        pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
5736        continue;
5737      }
5738      pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
5739    }
5740    // If all the elements are from V2, assign it to V1 and return after
5741    // building the first pshufb.
5742    if (V2Only)
5743      V1 = V2;
5744    V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
5745                     DAG.getNode(ISD::BUILD_VECTOR, dl,
5746                                 MVT::v16i8, &pshufbMask[0], 16));
5747    if (!TwoInputs)
5748      return V1;
5749
5750    // Calculate the shuffle mask for the second input, shuffle it, and
5751    // OR it with the first shuffled input.
5752    pshufbMask.clear();
5753    for (unsigned i = 0; i != 16; ++i) {
5754      int EltIdx = MaskVals[i];
5755      if (EltIdx < 16) {
5756        pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
5757        continue;
5758      }
5759      pshufbMask.push_back(DAG.getConstant(EltIdx - 16, MVT::i8));
5760    }
5761    V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
5762                     DAG.getNode(ISD::BUILD_VECTOR, dl,
5763                                 MVT::v16i8, &pshufbMask[0], 16));
5764    return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
5765  }
5766
5767  // No SSSE3 - Calculate in place words and then fix all out of place words
5768  // With 0-16 extracts & inserts.  Worst case is 16 bytes out of order from
5769  // the 16 different words that comprise the two doublequadword input vectors.
5770  V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5771  V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
5772  SDValue NewV = V2Only ? V2 : V1;
5773  for (int i = 0; i != 8; ++i) {
5774    int Elt0 = MaskVals[i*2];
5775    int Elt1 = MaskVals[i*2+1];
5776
5777    // This word of the result is all undef, skip it.
5778    if (Elt0 < 0 && Elt1 < 0)
5779      continue;
5780
5781    // This word of the result is already in the correct place, skip it.
5782    if (V1Only && (Elt0 == i*2) && (Elt1 == i*2+1))
5783      continue;
5784    if (V2Only && (Elt0 == i*2+16) && (Elt1 == i*2+17))
5785      continue;
5786
5787    SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
5788    SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
5789    SDValue InsElt;
5790
5791    // If Elt0 and Elt1 are defined, are consecutive, and can be load
5792    // using a single extract together, load it and store it.
5793    if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
5794      InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
5795                           DAG.getIntPtrConstant(Elt1 / 2));
5796      NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
5797                        DAG.getIntPtrConstant(i));
5798      continue;
5799    }
5800
5801    // If Elt1 is defined, extract it from the appropriate source.  If the
5802    // source byte is not also odd, shift the extracted word left 8 bits
5803    // otherwise clear the bottom 8 bits if we need to do an or.
5804    if (Elt1 >= 0) {
5805      InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
5806                           DAG.getIntPtrConstant(Elt1 / 2));
5807      if ((Elt1 & 1) == 0)
5808        InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
5809                             DAG.getConstant(8,
5810                                  TLI.getShiftAmountTy(InsElt.getValueType())));
5811      else if (Elt0 >= 0)
5812        InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
5813                             DAG.getConstant(0xFF00, MVT::i16));
5814    }
5815    // If Elt0 is defined, extract it from the appropriate source.  If the
5816    // source byte is not also even, shift the extracted word right 8 bits. If
5817    // Elt1 was also defined, OR the extracted values together before
5818    // inserting them in the result.
5819    if (Elt0 >= 0) {
5820      SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
5821                                    Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
5822      if ((Elt0 & 1) != 0)
5823        InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
5824                              DAG.getConstant(8,
5825                                 TLI.getShiftAmountTy(InsElt0.getValueType())));
5826      else if (Elt1 >= 0)
5827        InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
5828                             DAG.getConstant(0x00FF, MVT::i16));
5829      InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
5830                         : InsElt0;
5831    }
5832    NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
5833                       DAG.getIntPtrConstant(i));
5834  }
5835  return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, NewV);
5836}
5837
5838/// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
5839/// ones, or rewriting v4i32 / v4f32 as 2 wide ones if possible. This can be
5840/// done when every pair / quad of shuffle mask elements point to elements in
5841/// the right sequence. e.g.
5842/// vector_shuffle X, Y, <2, 3, | 10, 11, | 0, 1, | 14, 15>
5843static
5844SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
5845                                 SelectionDAG &DAG, DebugLoc dl) {
5846  EVT VT = SVOp->getValueType(0);
5847  SDValue V1 = SVOp->getOperand(0);
5848  SDValue V2 = SVOp->getOperand(1);
5849  unsigned NumElems = VT.getVectorNumElements();
5850  unsigned NewWidth = (NumElems == 4) ? 2 : 4;
5851  EVT NewVT;
5852  switch (VT.getSimpleVT().SimpleTy) {
5853  default: assert(false && "Unexpected!");
5854  case MVT::v4f32: NewVT = MVT::v2f64; break;
5855  case MVT::v4i32: NewVT = MVT::v2i64; break;
5856  case MVT::v8i16: NewVT = MVT::v4i32; break;
5857  case MVT::v16i8: NewVT = MVT::v4i32; break;
5858  }
5859
5860  int Scale = NumElems / NewWidth;
5861  SmallVector<int, 8> MaskVec;
5862  for (unsigned i = 0; i < NumElems; i += Scale) {
5863    int StartIdx = -1;
5864    for (int j = 0; j < Scale; ++j) {
5865      int EltIdx = SVOp->getMaskElt(i+j);
5866      if (EltIdx < 0)
5867        continue;
5868      if (StartIdx == -1)
5869        StartIdx = EltIdx - (EltIdx % Scale);
5870      if (EltIdx != StartIdx + j)
5871        return SDValue();
5872    }
5873    if (StartIdx == -1)
5874      MaskVec.push_back(-1);
5875    else
5876      MaskVec.push_back(StartIdx / Scale);
5877  }
5878
5879  V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, V1);
5880  V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, V2);
5881  return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
5882}
5883
5884/// getVZextMovL - Return a zero-extending vector move low node.
5885///
5886static SDValue getVZextMovL(EVT VT, EVT OpVT,
5887                            SDValue SrcOp, SelectionDAG &DAG,
5888                            const X86Subtarget *Subtarget, DebugLoc dl) {
5889  if (VT == MVT::v2f64 || VT == MVT::v4f32) {
5890    LoadSDNode *LD = NULL;
5891    if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
5892      LD = dyn_cast<LoadSDNode>(SrcOp);
5893    if (!LD) {
5894      // movssrr and movsdrr do not clear top bits. Try to use movd, movq
5895      // instead.
5896      MVT ExtVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
5897      if ((ExtVT != MVT::i64 || Subtarget->is64Bit()) &&
5898          SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
5899          SrcOp.getOperand(0).getOpcode() == ISD::BITCAST &&
5900          SrcOp.getOperand(0).getOperand(0).getValueType() == ExtVT) {
5901        // PR2108
5902        OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
5903        return DAG.getNode(ISD::BITCAST, dl, VT,
5904                           DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
5905                                       DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
5906                                                   OpVT,
5907                                                   SrcOp.getOperand(0)
5908                                                          .getOperand(0))));
5909      }
5910    }
5911  }
5912
5913  return DAG.getNode(ISD::BITCAST, dl, VT,
5914                     DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
5915                                 DAG.getNode(ISD::BITCAST, dl,
5916                                             OpVT, SrcOp)));
5917}
5918
5919/// areShuffleHalvesWithinDisjointLanes - Check whether each half of a vector
5920/// shuffle node referes to only one lane in the sources.
5921static bool areShuffleHalvesWithinDisjointLanes(ShuffleVectorSDNode *SVOp) {
5922  EVT VT = SVOp->getValueType(0);
5923  int NumElems = VT.getVectorNumElements();
5924  int HalfSize = NumElems/2;
5925  SmallVector<int, 16> M;
5926  SVOp->getMask(M);
5927  bool MatchA = false, MatchB = false;
5928
5929  for (int l = 0; l < NumElems*2; l += HalfSize) {
5930    if (isUndefOrInRange(M, 0, HalfSize, l, l+HalfSize)) {
5931      MatchA = true;
5932      break;
5933    }
5934  }
5935
5936  for (int l = 0; l < NumElems*2; l += HalfSize) {
5937    if (isUndefOrInRange(M, HalfSize, HalfSize, l, l+HalfSize)) {
5938      MatchB = true;
5939      break;
5940    }
5941  }
5942
5943  return MatchA && MatchB;
5944}
5945
5946/// LowerVECTOR_SHUFFLE_256 - Handle all 256-bit wide vectors shuffles
5947/// which could not be matched by any known target speficic shuffle
5948static SDValue
5949LowerVECTOR_SHUFFLE_256(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
5950  if (areShuffleHalvesWithinDisjointLanes(SVOp)) {
5951    // If each half of a vector shuffle node referes to only one lane in the
5952    // source vectors, extract each used 128-bit lane and shuffle them using
5953    // 128-bit shuffles. Then, concatenate the results. Otherwise leave
5954    // the work to the legalizer.
5955    DebugLoc dl = SVOp->getDebugLoc();
5956    EVT VT = SVOp->getValueType(0);
5957    int NumElems = VT.getVectorNumElements();
5958    int HalfSize = NumElems/2;
5959
5960    // Extract the reference for each half
5961    int FstVecExtractIdx = 0, SndVecExtractIdx = 0;
5962    int FstVecOpNum = 0, SndVecOpNum = 0;
5963    for (int i = 0; i < HalfSize; ++i) {
5964      int Elt = SVOp->getMaskElt(i);
5965      if (SVOp->getMaskElt(i) < 0)
5966        continue;
5967      FstVecOpNum = Elt/NumElems;
5968      FstVecExtractIdx = Elt % NumElems < HalfSize ? 0 : HalfSize;
5969      break;
5970    }
5971    for (int i = HalfSize; i < NumElems; ++i) {
5972      int Elt = SVOp->getMaskElt(i);
5973      if (SVOp->getMaskElt(i) < 0)
5974        continue;
5975      SndVecOpNum = Elt/NumElems;
5976      SndVecExtractIdx = Elt % NumElems < HalfSize ? 0 : HalfSize;
5977      break;
5978    }
5979
5980    // Extract the subvectors
5981    SDValue V1 = Extract128BitVector(SVOp->getOperand(FstVecOpNum),
5982                      DAG.getConstant(FstVecExtractIdx, MVT::i32), DAG, dl);
5983    SDValue V2 = Extract128BitVector(SVOp->getOperand(SndVecOpNum),
5984                      DAG.getConstant(SndVecExtractIdx, MVT::i32), DAG, dl);
5985
5986    // Generate 128-bit shuffles
5987    SmallVector<int, 16> MaskV1, MaskV2;
5988    for (int i = 0; i < HalfSize; ++i) {
5989      int Elt = SVOp->getMaskElt(i);
5990      MaskV1.push_back(Elt < 0 ? Elt : Elt % HalfSize);
5991    }
5992    for (int i = HalfSize; i < NumElems; ++i) {
5993      int Elt = SVOp->getMaskElt(i);
5994      MaskV2.push_back(Elt < 0 ? Elt : Elt % HalfSize);
5995    }
5996
5997    EVT NVT = V1.getValueType();
5998    V1 = DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &MaskV1[0]);
5999    V2 = DAG.getVectorShuffle(NVT, dl, V2, DAG.getUNDEF(NVT), &MaskV2[0]);
6000
6001    // Concatenate the result back
6002    SDValue V = Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, VT), V1,
6003                                   DAG.getConstant(0, MVT::i32), DAG, dl);
6004    return Insert128BitVector(V, V2, DAG.getConstant(NumElems/2, MVT::i32),
6005                              DAG, dl);
6006  }
6007
6008  return SDValue();
6009}
6010
6011/// LowerVECTOR_SHUFFLE_128v4 - Handle all 128-bit wide vectors with
6012/// 4 elements, and match them with several different shuffle types.
6013static SDValue
6014LowerVECTOR_SHUFFLE_128v4(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
6015  SDValue V1 = SVOp->getOperand(0);
6016  SDValue V2 = SVOp->getOperand(1);
6017  DebugLoc dl = SVOp->getDebugLoc();
6018  EVT VT = SVOp->getValueType(0);
6019
6020  assert(VT.getSizeInBits() == 128 && "Unsupported vector size");
6021
6022  SmallVector<std::pair<int, int>, 8> Locs;
6023  Locs.resize(4);
6024  SmallVector<int, 8> Mask1(4U, -1);
6025  SmallVector<int, 8> PermMask;
6026  SVOp->getMask(PermMask);
6027
6028  unsigned NumHi = 0;
6029  unsigned NumLo = 0;
6030  for (unsigned i = 0; i != 4; ++i) {
6031    int Idx = PermMask[i];
6032    if (Idx < 0) {
6033      Locs[i] = std::make_pair(-1, -1);
6034    } else {
6035      assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
6036      if (Idx < 4) {
6037        Locs[i] = std::make_pair(0, NumLo);
6038        Mask1[NumLo] = Idx;
6039        NumLo++;
6040      } else {
6041        Locs[i] = std::make_pair(1, NumHi);
6042        if (2+NumHi < 4)
6043          Mask1[2+NumHi] = Idx;
6044        NumHi++;
6045      }
6046    }
6047  }
6048
6049  if (NumLo <= 2 && NumHi <= 2) {
6050    // If no more than two elements come from either vector. This can be
6051    // implemented with two shuffles. First shuffle gather the elements.
6052    // The second shuffle, which takes the first shuffle as both of its
6053    // vector operands, put the elements into the right order.
6054    V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6055
6056    SmallVector<int, 8> Mask2(4U, -1);
6057
6058    for (unsigned i = 0; i != 4; ++i) {
6059      if (Locs[i].first == -1)
6060        continue;
6061      else {
6062        unsigned Idx = (i < 2) ? 0 : 4;
6063        Idx += Locs[i].first * 2 + Locs[i].second;
6064        Mask2[i] = Idx;
6065      }
6066    }
6067
6068    return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
6069  } else if (NumLo == 3 || NumHi == 3) {
6070    // Otherwise, we must have three elements from one vector, call it X, and
6071    // one element from the other, call it Y.  First, use a shufps to build an
6072    // intermediate vector with the one element from Y and the element from X
6073    // that will be in the same half in the final destination (the indexes don't
6074    // matter). Then, use a shufps to build the final vector, taking the half
6075    // containing the element from Y from the intermediate, and the other half
6076    // from X.
6077    if (NumHi == 3) {
6078      // Normalize it so the 3 elements come from V1.
6079      CommuteVectorShuffleMask(PermMask, VT);
6080      std::swap(V1, V2);
6081    }
6082
6083    // Find the element from V2.
6084    unsigned HiIndex;
6085    for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
6086      int Val = PermMask[HiIndex];
6087      if (Val < 0)
6088        continue;
6089      if (Val >= 4)
6090        break;
6091    }
6092
6093    Mask1[0] = PermMask[HiIndex];
6094    Mask1[1] = -1;
6095    Mask1[2] = PermMask[HiIndex^1];
6096    Mask1[3] = -1;
6097    V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6098
6099    if (HiIndex >= 2) {
6100      Mask1[0] = PermMask[0];
6101      Mask1[1] = PermMask[1];
6102      Mask1[2] = HiIndex & 1 ? 6 : 4;
6103      Mask1[3] = HiIndex & 1 ? 4 : 6;
6104      return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6105    } else {
6106      Mask1[0] = HiIndex & 1 ? 2 : 0;
6107      Mask1[1] = HiIndex & 1 ? 0 : 2;
6108      Mask1[2] = PermMask[2];
6109      Mask1[3] = PermMask[3];
6110      if (Mask1[2] >= 0)
6111        Mask1[2] += 4;
6112      if (Mask1[3] >= 0)
6113        Mask1[3] += 4;
6114      return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
6115    }
6116  }
6117
6118  // Break it into (shuffle shuffle_hi, shuffle_lo).
6119  Locs.clear();
6120  Locs.resize(4);
6121  SmallVector<int,8> LoMask(4U, -1);
6122  SmallVector<int,8> HiMask(4U, -1);
6123
6124  SmallVector<int,8> *MaskPtr = &LoMask;
6125  unsigned MaskIdx = 0;
6126  unsigned LoIdx = 0;
6127  unsigned HiIdx = 2;
6128  for (unsigned i = 0; i != 4; ++i) {
6129    if (i == 2) {
6130      MaskPtr = &HiMask;
6131      MaskIdx = 1;
6132      LoIdx = 0;
6133      HiIdx = 2;
6134    }
6135    int Idx = PermMask[i];
6136    if (Idx < 0) {
6137      Locs[i] = std::make_pair(-1, -1);
6138    } else if (Idx < 4) {
6139      Locs[i] = std::make_pair(MaskIdx, LoIdx);
6140      (*MaskPtr)[LoIdx] = Idx;
6141      LoIdx++;
6142    } else {
6143      Locs[i] = std::make_pair(MaskIdx, HiIdx);
6144      (*MaskPtr)[HiIdx] = Idx;
6145      HiIdx++;
6146    }
6147  }
6148
6149  SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
6150  SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
6151  SmallVector<int, 8> MaskOps;
6152  for (unsigned i = 0; i != 4; ++i) {
6153    if (Locs[i].first == -1) {
6154      MaskOps.push_back(-1);
6155    } else {
6156      unsigned Idx = Locs[i].first * 4 + Locs[i].second;
6157      MaskOps.push_back(Idx);
6158    }
6159  }
6160  return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
6161}
6162
6163static bool MayFoldVectorLoad(SDValue V) {
6164  if (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
6165    V = V.getOperand(0);
6166  if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
6167    V = V.getOperand(0);
6168  if (MayFoldLoad(V))
6169    return true;
6170  return false;
6171}
6172
6173// FIXME: the version above should always be used. Since there's
6174// a bug where several vector shuffles can't be folded because the
6175// DAG is not updated during lowering and a node claims to have two
6176// uses while it only has one, use this version, and let isel match
6177// another instruction if the load really happens to have more than
6178// one use. Remove this version after this bug get fixed.
6179// rdar://8434668, PR8156
6180static bool RelaxedMayFoldVectorLoad(SDValue V) {
6181  if (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
6182    V = V.getOperand(0);
6183  if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
6184    V = V.getOperand(0);
6185  if (ISD::isNormalLoad(V.getNode()))
6186    return true;
6187  return false;
6188}
6189
6190/// CanFoldShuffleIntoVExtract - Check if the current shuffle is used by
6191/// a vector extract, and if both can be later optimized into a single load.
6192/// This is done in visitEXTRACT_VECTOR_ELT and the conditions are checked
6193/// here because otherwise a target specific shuffle node is going to be
6194/// emitted for this shuffle, and the optimization not done.
6195/// FIXME: This is probably not the best approach, but fix the problem
6196/// until the right path is decided.
6197static
6198bool CanXFormVExtractWithShuffleIntoLoad(SDValue V, SelectionDAG &DAG,
6199                                         const TargetLowering &TLI) {
6200  EVT VT = V.getValueType();
6201  ShuffleVectorSDNode *SVOp = dyn_cast<ShuffleVectorSDNode>(V);
6202
6203  // Be sure that the vector shuffle is present in a pattern like this:
6204  // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), c) -> (f32 load $addr)
6205  if (!V.hasOneUse())
6206    return false;
6207
6208  SDNode *N = *V.getNode()->use_begin();
6209  if (N->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
6210    return false;
6211
6212  SDValue EltNo = N->getOperand(1);
6213  if (!isa<ConstantSDNode>(EltNo))
6214    return false;
6215
6216  // If the bit convert changed the number of elements, it is unsafe
6217  // to examine the mask.
6218  bool HasShuffleIntoBitcast = false;
6219  if (V.getOpcode() == ISD::BITCAST) {
6220    EVT SrcVT = V.getOperand(0).getValueType();
6221    if (SrcVT.getVectorNumElements() != VT.getVectorNumElements())
6222      return false;
6223    V = V.getOperand(0);
6224    HasShuffleIntoBitcast = true;
6225  }
6226
6227  // Select the input vector, guarding against out of range extract vector.
6228  unsigned NumElems = VT.getVectorNumElements();
6229  unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
6230  int Idx = (Elt > NumElems) ? -1 : SVOp->getMaskElt(Elt);
6231  V = (Idx < (int)NumElems) ? V.getOperand(0) : V.getOperand(1);
6232
6233  // Skip one more bit_convert if necessary
6234  if (V.getOpcode() == ISD::BITCAST)
6235    V = V.getOperand(0);
6236
6237  if (ISD::isNormalLoad(V.getNode())) {
6238    // Is the original load suitable?
6239    LoadSDNode *LN0 = cast<LoadSDNode>(V);
6240
6241    // FIXME: avoid the multi-use bug that is preventing lots of
6242    // of foldings to be detected, this is still wrong of course, but
6243    // give the temporary desired behavior, and if it happens that
6244    // the load has real more uses, during isel it will not fold, and
6245    // will generate poor code.
6246    if (!LN0 || LN0->isVolatile()) // || !LN0->hasOneUse()
6247      return false;
6248
6249    if (!HasShuffleIntoBitcast)
6250      return true;
6251
6252    // If there's a bitcast before the shuffle, check if the load type and
6253    // alignment is valid.
6254    unsigned Align = LN0->getAlignment();
6255    unsigned NewAlign =
6256      TLI.getTargetData()->getABITypeAlignment(
6257                                    VT.getTypeForEVT(*DAG.getContext()));
6258
6259    if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VT))
6260      return false;
6261  }
6262
6263  return true;
6264}
6265
6266static
6267SDValue getMOVDDup(SDValue &Op, DebugLoc &dl, SDValue V1, SelectionDAG &DAG) {
6268  EVT VT = Op.getValueType();
6269
6270  // Canonizalize to v2f64.
6271  V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
6272  return DAG.getNode(ISD::BITCAST, dl, VT,
6273                     getTargetShuffleNode(X86ISD::MOVDDUP, dl, MVT::v2f64,
6274                                          V1, DAG));
6275}
6276
6277static
6278SDValue getMOVLowToHigh(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG,
6279                        bool HasXMMInt) {
6280  SDValue V1 = Op.getOperand(0);
6281  SDValue V2 = Op.getOperand(1);
6282  EVT VT = Op.getValueType();
6283
6284  assert(VT != MVT::v2i64 && "unsupported shuffle type");
6285
6286  if (HasXMMInt && VT == MVT::v2f64)
6287    return getTargetShuffleNode(X86ISD::MOVLHPD, dl, VT, V1, V2, DAG);
6288
6289  // v4f32 or v4i32: canonizalized to v4f32 (which is legal for SSE1)
6290  return DAG.getNode(ISD::BITCAST, dl, VT,
6291                     getTargetShuffleNode(X86ISD::MOVLHPS, dl, MVT::v4f32,
6292                           DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V1),
6293                           DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V2), DAG));
6294}
6295
6296static
6297SDValue getMOVHighToLow(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG) {
6298  SDValue V1 = Op.getOperand(0);
6299  SDValue V2 = Op.getOperand(1);
6300  EVT VT = Op.getValueType();
6301
6302  assert((VT == MVT::v4i32 || VT == MVT::v4f32) &&
6303         "unsupported shuffle type");
6304
6305  if (V2.getOpcode() == ISD::UNDEF)
6306    V2 = V1;
6307
6308  // v4i32 or v4f32
6309  return getTargetShuffleNode(X86ISD::MOVHLPS, dl, VT, V1, V2, DAG);
6310}
6311
6312static inline unsigned getSHUFPOpcode(EVT VT) {
6313  switch(VT.getSimpleVT().SimpleTy) {
6314  case MVT::v8i32: // Use fp unit for int unpack.
6315  case MVT::v8f32:
6316  case MVT::v4i32: // Use fp unit for int unpack.
6317  case MVT::v4f32: return X86ISD::SHUFPS;
6318  case MVT::v4i64: // Use fp unit for int unpack.
6319  case MVT::v4f64:
6320  case MVT::v2i64: // Use fp unit for int unpack.
6321  case MVT::v2f64: return X86ISD::SHUFPD;
6322  default:
6323    llvm_unreachable("Unknown type for shufp*");
6324  }
6325  return 0;
6326}
6327
6328static
6329SDValue getMOVLP(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG, bool HasXMMInt) {
6330  SDValue V1 = Op.getOperand(0);
6331  SDValue V2 = Op.getOperand(1);
6332  EVT VT = Op.getValueType();
6333  unsigned NumElems = VT.getVectorNumElements();
6334
6335  // Use MOVLPS and MOVLPD in case V1 or V2 are loads. During isel, the second
6336  // operand of these instructions is only memory, so check if there's a
6337  // potencial load folding here, otherwise use SHUFPS or MOVSD to match the
6338  // same masks.
6339  bool CanFoldLoad = false;
6340
6341  // Trivial case, when V2 comes from a load.
6342  if (MayFoldVectorLoad(V2))
6343    CanFoldLoad = true;
6344
6345  // When V1 is a load, it can be folded later into a store in isel, example:
6346  //  (store (v4f32 (X86Movlps (load addr:$src1), VR128:$src2)), addr:$src1)
6347  //    turns into:
6348  //  (MOVLPSmr addr:$src1, VR128:$src2)
6349  // So, recognize this potential and also use MOVLPS or MOVLPD
6350  if (MayFoldVectorLoad(V1) && MayFoldIntoStore(Op))
6351    CanFoldLoad = true;
6352
6353  // Both of them can't be memory operations though.
6354  if (MayFoldVectorLoad(V1) && MayFoldVectorLoad(V2))
6355    CanFoldLoad = false;
6356
6357  if (CanFoldLoad) {
6358    if (HasXMMInt && NumElems == 2)
6359      return getTargetShuffleNode(X86ISD::MOVLPD, dl, VT, V1, V2, DAG);
6360
6361    if (NumElems == 4)
6362      return getTargetShuffleNode(X86ISD::MOVLPS, dl, VT, V1, V2, DAG);
6363  }
6364
6365  ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6366  // movl and movlp will both match v2i64, but v2i64 is never matched by
6367  // movl earlier because we make it strict to avoid messing with the movlp load
6368  // folding logic (see the code above getMOVLP call). Match it here then,
6369  // this is horrible, but will stay like this until we move all shuffle
6370  // matching to x86 specific nodes. Note that for the 1st condition all
6371  // types are matched with movsd.
6372  if (HasXMMInt) {
6373    // FIXME: isMOVLMask should be checked and matched before getMOVLP,
6374    // as to remove this logic from here, as much as possible
6375    if (NumElems == 2 || !X86::isMOVLMask(SVOp))
6376      return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
6377    return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
6378  }
6379
6380  assert(VT != MVT::v4i32 && "unsupported shuffle type");
6381
6382  // Invert the operand order and use SHUFPS to match it.
6383  return getTargetShuffleNode(getSHUFPOpcode(VT), dl, VT, V2, V1,
6384                              X86::getShuffleSHUFImmediate(SVOp), DAG);
6385}
6386
6387static inline unsigned getUNPCKLOpcode(EVT VT) {
6388  switch(VT.getSimpleVT().SimpleTy) {
6389  case MVT::v4i32: return X86ISD::PUNPCKLDQ;
6390  case MVT::v2i64: return X86ISD::PUNPCKLQDQ;
6391  case MVT::v4f32: return X86ISD::UNPCKLPS;
6392  case MVT::v2f64: return X86ISD::UNPCKLPD;
6393  case MVT::v8i32: // Use fp unit for int unpack.
6394  case MVT::v8f32: return X86ISD::VUNPCKLPSY;
6395  case MVT::v4i64: // Use fp unit for int unpack.
6396  case MVT::v4f64: return X86ISD::VUNPCKLPDY;
6397  case MVT::v16i8: return X86ISD::PUNPCKLBW;
6398  case MVT::v8i16: return X86ISD::PUNPCKLWD;
6399  default:
6400    llvm_unreachable("Unknown type for unpckl");
6401  }
6402  return 0;
6403}
6404
6405static inline unsigned getUNPCKHOpcode(EVT VT) {
6406  switch(VT.getSimpleVT().SimpleTy) {
6407  case MVT::v4i32: return X86ISD::PUNPCKHDQ;
6408  case MVT::v2i64: return X86ISD::PUNPCKHQDQ;
6409  case MVT::v4f32: return X86ISD::UNPCKHPS;
6410  case MVT::v2f64: return X86ISD::UNPCKHPD;
6411  case MVT::v8i32: // Use fp unit for int unpack.
6412  case MVT::v8f32: return X86ISD::VUNPCKHPSY;
6413  case MVT::v4i64: // Use fp unit for int unpack.
6414  case MVT::v4f64: return X86ISD::VUNPCKHPDY;
6415  case MVT::v16i8: return X86ISD::PUNPCKHBW;
6416  case MVT::v8i16: return X86ISD::PUNPCKHWD;
6417  default:
6418    llvm_unreachable("Unknown type for unpckh");
6419  }
6420  return 0;
6421}
6422
6423static inline unsigned getVPERMILOpcode(EVT VT) {
6424  switch(VT.getSimpleVT().SimpleTy) {
6425  case MVT::v4i32:
6426  case MVT::v4f32: return X86ISD::VPERMILPS;
6427  case MVT::v2i64:
6428  case MVT::v2f64: return X86ISD::VPERMILPD;
6429  case MVT::v8i32:
6430  case MVT::v8f32: return X86ISD::VPERMILPSY;
6431  case MVT::v4i64:
6432  case MVT::v4f64: return X86ISD::VPERMILPDY;
6433  default:
6434    llvm_unreachable("Unknown type for vpermil");
6435  }
6436  return 0;
6437}
6438
6439/// isVectorBroadcast - Check if the node chain is suitable to be xformed to
6440/// a vbroadcast node. The nodes are suitable whenever we can fold a load coming
6441/// from a 32 or 64 bit scalar. Update Op to the desired load to be folded.
6442static bool isVectorBroadcast(SDValue &Op) {
6443  EVT VT = Op.getValueType();
6444  bool Is256 = VT.getSizeInBits() == 256;
6445
6446  assert((VT.getSizeInBits() == 128 || Is256) &&
6447         "Unsupported type for vbroadcast node");
6448
6449  SDValue V = Op;
6450  if (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
6451    V = V.getOperand(0);
6452
6453  if (Is256 && !(V.hasOneUse() &&
6454                 V.getOpcode() == ISD::INSERT_SUBVECTOR &&
6455                 V.getOperand(0).getOpcode() == ISD::UNDEF))
6456    return false;
6457
6458  if (Is256)
6459    V = V.getOperand(1);
6460
6461  if (!V.hasOneUse())
6462    return false;
6463
6464  // Check the source scalar_to_vector type. 256-bit broadcasts are
6465  // supported for 32/64-bit sizes, while 128-bit ones are only supported
6466  // for 32-bit scalars.
6467  if (V.getOpcode() != ISD::SCALAR_TO_VECTOR)
6468    return false;
6469
6470  unsigned ScalarSize = V.getOperand(0).getValueType().getSizeInBits();
6471  if (ScalarSize != 32 && ScalarSize != 64)
6472    return false;
6473  if (!Is256 && ScalarSize == 64)
6474    return false;
6475
6476  V = V.getOperand(0);
6477  if (!MayFoldLoad(V))
6478    return false;
6479
6480  // Return the load node
6481  Op = V;
6482  return true;
6483}
6484
6485static
6486SDValue NormalizeVectorShuffle(SDValue Op, SelectionDAG &DAG,
6487                               const TargetLowering &TLI,
6488                               const X86Subtarget *Subtarget) {
6489  ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6490  EVT VT = Op.getValueType();
6491  DebugLoc dl = Op.getDebugLoc();
6492  SDValue V1 = Op.getOperand(0);
6493  SDValue V2 = Op.getOperand(1);
6494
6495  if (isZeroShuffle(SVOp))
6496    return getZeroVector(VT, Subtarget->hasXMMInt(), DAG, dl);
6497
6498  // Handle splat operations
6499  if (SVOp->isSplat()) {
6500    unsigned NumElem = VT.getVectorNumElements();
6501    int Size = VT.getSizeInBits();
6502    // Special case, this is the only place now where it's allowed to return
6503    // a vector_shuffle operation without using a target specific node, because
6504    // *hopefully* it will be optimized away by the dag combiner. FIXME: should
6505    // this be moved to DAGCombine instead?
6506    if (NumElem <= 4 && CanXFormVExtractWithShuffleIntoLoad(Op, DAG, TLI))
6507      return Op;
6508
6509    // Use vbroadcast whenever the splat comes from a foldable load
6510    if (Subtarget->hasAVX() && isVectorBroadcast(V1))
6511      return DAG.getNode(X86ISD::VBROADCAST, dl, VT, V1);
6512
6513    // Handle splats by matching through known shuffle masks
6514    if ((Size == 128 && NumElem <= 4) ||
6515        (Size == 256 && NumElem < 8))
6516      return SDValue();
6517
6518    // All remaning splats are promoted to target supported vector shuffles.
6519    return PromoteSplat(SVOp, DAG);
6520  }
6521
6522  // If the shuffle can be profitably rewritten as a narrower shuffle, then
6523  // do it!
6524  if (VT == MVT::v8i16 || VT == MVT::v16i8) {
6525    SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
6526    if (NewOp.getNode())
6527      return DAG.getNode(ISD::BITCAST, dl, VT, NewOp);
6528  } else if ((VT == MVT::v4i32 ||
6529             (VT == MVT::v4f32 && Subtarget->hasXMMInt()))) {
6530    // FIXME: Figure out a cleaner way to do this.
6531    // Try to make use of movq to zero out the top part.
6532    if (ISD::isBuildVectorAllZeros(V2.getNode())) {
6533      SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
6534      if (NewOp.getNode()) {
6535        if (isCommutedMOVL(cast<ShuffleVectorSDNode>(NewOp), true, false))
6536          return getVZextMovL(VT, NewOp.getValueType(), NewOp.getOperand(0),
6537                              DAG, Subtarget, dl);
6538      }
6539    } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
6540      SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
6541      if (NewOp.getNode() && X86::isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)))
6542        return getVZextMovL(VT, NewOp.getValueType(), NewOp.getOperand(1),
6543                            DAG, Subtarget, dl);
6544    }
6545  }
6546  return SDValue();
6547}
6548
6549SDValue
6550X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) const {
6551  ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6552  SDValue V1 = Op.getOperand(0);
6553  SDValue V2 = Op.getOperand(1);
6554  EVT VT = Op.getValueType();
6555  DebugLoc dl = Op.getDebugLoc();
6556  unsigned NumElems = VT.getVectorNumElements();
6557  bool isMMX = VT.getSizeInBits() == 64;
6558  bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
6559  bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
6560  bool V1IsSplat = false;
6561  bool V2IsSplat = false;
6562  bool HasXMMInt = Subtarget->hasXMMInt();
6563  MachineFunction &MF = DAG.getMachineFunction();
6564  bool OptForSize = MF.getFunction()->hasFnAttr(Attribute::OptimizeForSize);
6565
6566  // Shuffle operations on MMX not supported.
6567  if (isMMX)
6568    return Op;
6569
6570  // Vector shuffle lowering takes 3 steps:
6571  //
6572  // 1) Normalize the input vectors. Here splats, zeroed vectors, profitable
6573  //    narrowing and commutation of operands should be handled.
6574  // 2) Matching of shuffles with known shuffle masks to x86 target specific
6575  //    shuffle nodes.
6576  // 3) Rewriting of unmatched masks into new generic shuffle operations,
6577  //    so the shuffle can be broken into other shuffles and the legalizer can
6578  //    try the lowering again.
6579  //
6580  // The general ideia is that no vector_shuffle operation should be left to
6581  // be matched during isel, all of them must be converted to a target specific
6582  // node here.
6583
6584  // Normalize the input vectors. Here splats, zeroed vectors, profitable
6585  // narrowing and commutation of operands should be handled. The actual code
6586  // doesn't include all of those, work in progress...
6587  SDValue NewOp = NormalizeVectorShuffle(Op, DAG, *this, Subtarget);
6588  if (NewOp.getNode())
6589    return NewOp;
6590
6591  // NOTE: isPSHUFDMask can also match both masks below (unpckl_undef and
6592  // unpckh_undef). Only use pshufd if speed is more important than size.
6593  if (OptForSize && X86::isUNPCKL_v_undef_Mask(SVOp))
6594    return getTargetShuffleNode(getUNPCKLOpcode(VT), dl, VT, V1, V1, DAG);
6595  if (OptForSize && X86::isUNPCKH_v_undef_Mask(SVOp))
6596    return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V1, V1, DAG);
6597
6598  if (X86::isMOVDDUPMask(SVOp) &&
6599      (Subtarget->hasSSE3() || Subtarget->hasAVX()) &&
6600      V2IsUndef && RelaxedMayFoldVectorLoad(V1))
6601    return getMOVDDup(Op, dl, V1, DAG);
6602
6603  if (X86::isMOVHLPS_v_undef_Mask(SVOp))
6604    return getMOVHighToLow(Op, dl, DAG);
6605
6606  // Use to match splats
6607  if (HasXMMInt && X86::isUNPCKHMask(SVOp) && V2IsUndef &&
6608      (VT == MVT::v2f64 || VT == MVT::v2i64))
6609    return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V1, V1, DAG);
6610
6611  if (X86::isPSHUFDMask(SVOp)) {
6612    // The actual implementation will match the mask in the if above and then
6613    // during isel it can match several different instructions, not only pshufd
6614    // as its name says, sad but true, emulate the behavior for now...
6615    if (X86::isMOVDDUPMask(SVOp) && ((VT == MVT::v4f32 || VT == MVT::v2i64)))
6616        return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V1, DAG);
6617
6618    unsigned TargetMask = X86::getShuffleSHUFImmediate(SVOp);
6619
6620    if (HasXMMInt && (VT == MVT::v4f32 || VT == MVT::v4i32))
6621      return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1, TargetMask, DAG);
6622
6623    return getTargetShuffleNode(getSHUFPOpcode(VT), dl, VT, V1, V1,
6624                                TargetMask, DAG);
6625  }
6626
6627  // Check if this can be converted into a logical shift.
6628  bool isLeft = false;
6629  unsigned ShAmt = 0;
6630  SDValue ShVal;
6631  bool isShift = getSubtarget()->hasXMMInt() &&
6632                 isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
6633  if (isShift && ShVal.hasOneUse()) {
6634    // If the shifted value has multiple uses, it may be cheaper to use
6635    // v_set0 + movlhps or movhlps, etc.
6636    EVT EltVT = VT.getVectorElementType();
6637    ShAmt *= EltVT.getSizeInBits();
6638    return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
6639  }
6640
6641  if (X86::isMOVLMask(SVOp)) {
6642    if (V1IsUndef)
6643      return V2;
6644    if (ISD::isBuildVectorAllZeros(V1.getNode()))
6645      return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
6646    if (!X86::isMOVLPMask(SVOp)) {
6647      if (HasXMMInt && (VT == MVT::v2i64 || VT == MVT::v2f64))
6648        return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
6649
6650      if (VT == MVT::v4i32 || VT == MVT::v4f32)
6651        return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
6652    }
6653  }
6654
6655  // FIXME: fold these into legal mask.
6656  if (X86::isMOVLHPSMask(SVOp) && !X86::isUNPCKLMask(SVOp))
6657    return getMOVLowToHigh(Op, dl, DAG, HasXMMInt);
6658
6659  if (X86::isMOVHLPSMask(SVOp))
6660    return getMOVHighToLow(Op, dl, DAG);
6661
6662  if (X86::isMOVSHDUPMask(SVOp, Subtarget))
6663    return getTargetShuffleNode(X86ISD::MOVSHDUP, dl, VT, V1, DAG);
6664
6665  if (X86::isMOVSLDUPMask(SVOp, Subtarget))
6666    return getTargetShuffleNode(X86ISD::MOVSLDUP, dl, VT, V1, DAG);
6667
6668  if (X86::isMOVLPMask(SVOp))
6669    return getMOVLP(Op, dl, DAG, HasXMMInt);
6670
6671  if (ShouldXformToMOVHLPS(SVOp) ||
6672      ShouldXformToMOVLP(V1.getNode(), V2.getNode(), SVOp))
6673    return CommuteVectorShuffle(SVOp, DAG);
6674
6675  if (isShift) {
6676    // No better options. Use a vshl / vsrl.
6677    EVT EltVT = VT.getVectorElementType();
6678    ShAmt *= EltVT.getSizeInBits();
6679    return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
6680  }
6681
6682  bool Commuted = false;
6683  // FIXME: This should also accept a bitcast of a splat?  Be careful, not
6684  // 1,1,1,1 -> v8i16 though.
6685  V1IsSplat = isSplatVector(V1.getNode());
6686  V2IsSplat = isSplatVector(V2.getNode());
6687
6688  // Canonicalize the splat or undef, if present, to be on the RHS.
6689  if ((V1IsSplat || V1IsUndef) && !(V2IsSplat || V2IsUndef)) {
6690    Op = CommuteVectorShuffle(SVOp, DAG);
6691    SVOp = cast<ShuffleVectorSDNode>(Op);
6692    V1 = SVOp->getOperand(0);
6693    V2 = SVOp->getOperand(1);
6694    std::swap(V1IsSplat, V2IsSplat);
6695    std::swap(V1IsUndef, V2IsUndef);
6696    Commuted = true;
6697  }
6698
6699  if (isCommutedMOVL(SVOp, V2IsSplat, V2IsUndef)) {
6700    // Shuffling low element of v1 into undef, just return v1.
6701    if (V2IsUndef)
6702      return V1;
6703    // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
6704    // the instruction selector will not match, so get a canonical MOVL with
6705    // swapped operands to undo the commute.
6706    return getMOVL(DAG, dl, VT, V2, V1);
6707  }
6708
6709  if (X86::isUNPCKLMask(SVOp))
6710    return getTargetShuffleNode(getUNPCKLOpcode(VT), dl, VT, V1, V2, DAG);
6711
6712  if (X86::isUNPCKHMask(SVOp))
6713    return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V1, V2, DAG);
6714
6715  if (V2IsSplat) {
6716    // Normalize mask so all entries that point to V2 points to its first
6717    // element then try to match unpck{h|l} again. If match, return a
6718    // new vector_shuffle with the corrected mask.
6719    SDValue NewMask = NormalizeMask(SVOp, DAG);
6720    ShuffleVectorSDNode *NSVOp = cast<ShuffleVectorSDNode>(NewMask);
6721    if (NSVOp != SVOp) {
6722      if (X86::isUNPCKLMask(NSVOp, true)) {
6723        return NewMask;
6724      } else if (X86::isUNPCKHMask(NSVOp, true)) {
6725        return NewMask;
6726      }
6727    }
6728  }
6729
6730  if (Commuted) {
6731    // Commute is back and try unpck* again.
6732    // FIXME: this seems wrong.
6733    SDValue NewOp = CommuteVectorShuffle(SVOp, DAG);
6734    ShuffleVectorSDNode *NewSVOp = cast<ShuffleVectorSDNode>(NewOp);
6735
6736    if (X86::isUNPCKLMask(NewSVOp))
6737      return getTargetShuffleNode(getUNPCKLOpcode(VT), dl, VT, V2, V1, DAG);
6738
6739    if (X86::isUNPCKHMask(NewSVOp))
6740      return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V2, V1, DAG);
6741  }
6742
6743  // Normalize the node to match x86 shuffle ops if needed
6744  if (V2.getOpcode() != ISD::UNDEF && isCommutedSHUFP(SVOp))
6745    return CommuteVectorShuffle(SVOp, DAG);
6746
6747  // The checks below are all present in isShuffleMaskLegal, but they are
6748  // inlined here right now to enable us to directly emit target specific
6749  // nodes, and remove one by one until they don't return Op anymore.
6750  SmallVector<int, 16> M;
6751  SVOp->getMask(M);
6752
6753  if (isPALIGNRMask(M, VT, Subtarget->hasSSSE3() || Subtarget->hasAVX()))
6754    return getTargetShuffleNode(X86ISD::PALIGN, dl, VT, V1, V2,
6755                                X86::getShufflePALIGNRImmediate(SVOp),
6756                                DAG);
6757
6758  if (ShuffleVectorSDNode::isSplatMask(&M[0], VT) &&
6759      SVOp->getSplatIndex() == 0 && V2IsUndef) {
6760    if (VT == MVT::v2f64)
6761      return getTargetShuffleNode(X86ISD::UNPCKLPD, dl, VT, V1, V1, DAG);
6762    if (VT == MVT::v2i64)
6763      return getTargetShuffleNode(X86ISD::PUNPCKLQDQ, dl, VT, V1, V1, DAG);
6764  }
6765
6766  if (isPSHUFHWMask(M, VT))
6767    return getTargetShuffleNode(X86ISD::PSHUFHW, dl, VT, V1,
6768                                X86::getShufflePSHUFHWImmediate(SVOp),
6769                                DAG);
6770
6771  if (isPSHUFLWMask(M, VT))
6772    return getTargetShuffleNode(X86ISD::PSHUFLW, dl, VT, V1,
6773                                X86::getShufflePSHUFLWImmediate(SVOp),
6774                                DAG);
6775
6776  if (isSHUFPMask(M, VT))
6777    return getTargetShuffleNode(getSHUFPOpcode(VT), dl, VT, V1, V2,
6778                                X86::getShuffleSHUFImmediate(SVOp), DAG);
6779
6780  if (X86::isUNPCKL_v_undef_Mask(SVOp))
6781    return getTargetShuffleNode(getUNPCKLOpcode(VT), dl, VT, V1, V1, DAG);
6782  if (X86::isUNPCKH_v_undef_Mask(SVOp))
6783    return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V1, V1, DAG);
6784
6785  //===--------------------------------------------------------------------===//
6786  // Generate target specific nodes for 128 or 256-bit shuffles only
6787  // supported in the AVX instruction set.
6788  //
6789
6790  // Handle VMOVDDUPY permutations
6791  if (isMOVDDUPYMask(SVOp, Subtarget))
6792    return getTargetShuffleNode(X86ISD::MOVDDUP, dl, VT, V1, DAG);
6793
6794  // Handle VPERMILPS* permutations
6795  if (isVPERMILPSMask(M, VT, Subtarget))
6796    return getTargetShuffleNode(getVPERMILOpcode(VT), dl, VT, V1,
6797                                getShuffleVPERMILPSImmediate(SVOp), DAG);
6798
6799  // Handle VPERMILPD* permutations
6800  if (isVPERMILPDMask(M, VT, Subtarget))
6801    return getTargetShuffleNode(getVPERMILOpcode(VT), dl, VT, V1,
6802                                getShuffleVPERMILPDImmediate(SVOp), DAG);
6803
6804  // Handle VPERM2F128 permutations
6805  if (isVPERM2F128Mask(M, VT, Subtarget))
6806    return getTargetShuffleNode(X86ISD::VPERM2F128, dl, VT, V1, V2,
6807                                getShuffleVPERM2F128Immediate(SVOp), DAG);
6808
6809  // Handle VSHUFPSY permutations
6810  if (isVSHUFPSYMask(M, VT, Subtarget))
6811    return getTargetShuffleNode(getSHUFPOpcode(VT), dl, VT, V1, V2,
6812                                getShuffleVSHUFPSYImmediate(SVOp), DAG);
6813
6814  // Handle VSHUFPDY permutations
6815  if (isVSHUFPDYMask(M, VT, Subtarget))
6816    return getTargetShuffleNode(getSHUFPOpcode(VT), dl, VT, V1, V2,
6817                                getShuffleVSHUFPDYImmediate(SVOp), DAG);
6818
6819  //===--------------------------------------------------------------------===//
6820  // Since no target specific shuffle was selected for this generic one,
6821  // lower it into other known shuffles. FIXME: this isn't true yet, but
6822  // this is the plan.
6823  //
6824
6825  // Handle v8i16 specifically since SSE can do byte extraction and insertion.
6826  if (VT == MVT::v8i16) {
6827    SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(Op, DAG);
6828    if (NewOp.getNode())
6829      return NewOp;
6830  }
6831
6832  if (VT == MVT::v16i8) {
6833    SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, DAG, *this);
6834    if (NewOp.getNode())
6835      return NewOp;
6836  }
6837
6838  // Handle all 128-bit wide vectors with 4 elements, and match them with
6839  // several different shuffle types.
6840  if (NumElems == 4 && VT.getSizeInBits() == 128)
6841    return LowerVECTOR_SHUFFLE_128v4(SVOp, DAG);
6842
6843  // Handle general 256-bit shuffles
6844  if (VT.is256BitVector())
6845    return LowerVECTOR_SHUFFLE_256(SVOp, DAG);
6846
6847  return SDValue();
6848}
6849
6850SDValue
6851X86TargetLowering::LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op,
6852                                                SelectionDAG &DAG) const {
6853  EVT VT = Op.getValueType();
6854  DebugLoc dl = Op.getDebugLoc();
6855
6856  if (Op.getOperand(0).getValueType().getSizeInBits() != 128)
6857    return SDValue();
6858
6859  if (VT.getSizeInBits() == 8) {
6860    SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
6861                                    Op.getOperand(0), Op.getOperand(1));
6862    SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
6863                                    DAG.getValueType(VT));
6864    return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
6865  } else if (VT.getSizeInBits() == 16) {
6866    unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6867    // If Idx is 0, it's cheaper to do a move instead of a pextrw.
6868    if (Idx == 0)
6869      return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
6870                         DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
6871                                     DAG.getNode(ISD::BITCAST, dl,
6872                                                 MVT::v4i32,
6873                                                 Op.getOperand(0)),
6874                                     Op.getOperand(1)));
6875    SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
6876                                    Op.getOperand(0), Op.getOperand(1));
6877    SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
6878                                    DAG.getValueType(VT));
6879    return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
6880  } else if (VT == MVT::f32) {
6881    // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
6882    // the result back to FR32 register. It's only worth matching if the
6883    // result has a single use which is a store or a bitcast to i32.  And in
6884    // the case of a store, it's not worth it if the index is a constant 0,
6885    // because a MOVSSmr can be used instead, which is smaller and faster.
6886    if (!Op.hasOneUse())
6887      return SDValue();
6888    SDNode *User = *Op.getNode()->use_begin();
6889    if ((User->getOpcode() != ISD::STORE ||
6890         (isa<ConstantSDNode>(Op.getOperand(1)) &&
6891          cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
6892        (User->getOpcode() != ISD::BITCAST ||
6893         User->getValueType(0) != MVT::i32))
6894      return SDValue();
6895    SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
6896                                  DAG.getNode(ISD::BITCAST, dl, MVT::v4i32,
6897                                              Op.getOperand(0)),
6898                                              Op.getOperand(1));
6899    return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Extract);
6900  } else if (VT == MVT::i32) {
6901    // ExtractPS works with constant index.
6902    if (isa<ConstantSDNode>(Op.getOperand(1)))
6903      return Op;
6904  }
6905  return SDValue();
6906}
6907
6908
6909SDValue
6910X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
6911                                           SelectionDAG &DAG) const {
6912  if (!isa<ConstantSDNode>(Op.getOperand(1)))
6913    return SDValue();
6914
6915  SDValue Vec = Op.getOperand(0);
6916  EVT VecVT = Vec.getValueType();
6917
6918  // If this is a 256-bit vector result, first extract the 128-bit vector and
6919  // then extract the element from the 128-bit vector.
6920  if (VecVT.getSizeInBits() == 256) {
6921    DebugLoc dl = Op.getNode()->getDebugLoc();
6922    unsigned NumElems = VecVT.getVectorNumElements();
6923    SDValue Idx = Op.getOperand(1);
6924    unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
6925
6926    // Get the 128-bit vector.
6927    bool Upper = IdxVal >= NumElems/2;
6928    Vec = Extract128BitVector(Vec,
6929                    DAG.getConstant(Upper ? NumElems/2 : 0, MVT::i32), DAG, dl);
6930
6931    return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
6932                    Upper ? DAG.getConstant(IdxVal-NumElems/2, MVT::i32) : Idx);
6933  }
6934
6935  assert(Vec.getValueSizeInBits() <= 128 && "Unexpected vector length");
6936
6937  if (Subtarget->hasSSE41() || Subtarget->hasAVX()) {
6938    SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
6939    if (Res.getNode())
6940      return Res;
6941  }
6942
6943  EVT VT = Op.getValueType();
6944  DebugLoc dl = Op.getDebugLoc();
6945  // TODO: handle v16i8.
6946  if (VT.getSizeInBits() == 16) {
6947    SDValue Vec = Op.getOperand(0);
6948    unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6949    if (Idx == 0)
6950      return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
6951                         DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
6952                                     DAG.getNode(ISD::BITCAST, dl,
6953                                                 MVT::v4i32, Vec),
6954                                     Op.getOperand(1)));
6955    // Transform it so it match pextrw which produces a 32-bit result.
6956    EVT EltVT = MVT::i32;
6957    SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
6958                                    Op.getOperand(0), Op.getOperand(1));
6959    SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
6960                                    DAG.getValueType(VT));
6961    return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
6962  } else if (VT.getSizeInBits() == 32) {
6963    unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6964    if (Idx == 0)
6965      return Op;
6966
6967    // SHUFPS the element to the lowest double word, then movss.
6968    int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
6969    EVT VVT = Op.getOperand(0).getValueType();
6970    SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
6971                                       DAG.getUNDEF(VVT), Mask);
6972    return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
6973                       DAG.getIntPtrConstant(0));
6974  } else if (VT.getSizeInBits() == 64) {
6975    // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
6976    // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
6977    //        to match extract_elt for f64.
6978    unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6979    if (Idx == 0)
6980      return Op;
6981
6982    // UNPCKHPD the element to the lowest double word, then movsd.
6983    // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
6984    // to a f64mem, the whole operation is folded into a single MOVHPDmr.
6985    int Mask[2] = { 1, -1 };
6986    EVT VVT = Op.getOperand(0).getValueType();
6987    SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
6988                                       DAG.getUNDEF(VVT), Mask);
6989    return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
6990                       DAG.getIntPtrConstant(0));
6991  }
6992
6993  return SDValue();
6994}
6995
6996SDValue
6997X86TargetLowering::LowerINSERT_VECTOR_ELT_SSE4(SDValue Op,
6998                                               SelectionDAG &DAG) const {
6999  EVT VT = Op.getValueType();
7000  EVT EltVT = VT.getVectorElementType();
7001  DebugLoc dl = Op.getDebugLoc();
7002
7003  SDValue N0 = Op.getOperand(0);
7004  SDValue N1 = Op.getOperand(1);
7005  SDValue N2 = Op.getOperand(2);
7006
7007  if (VT.getSizeInBits() == 256)
7008    return SDValue();
7009
7010  if ((EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) &&
7011      isa<ConstantSDNode>(N2)) {
7012    unsigned Opc;
7013    if (VT == MVT::v8i16)
7014      Opc = X86ISD::PINSRW;
7015    else if (VT == MVT::v16i8)
7016      Opc = X86ISD::PINSRB;
7017    else
7018      Opc = X86ISD::PINSRB;
7019
7020    // Transform it so it match pinsr{b,w} which expects a GR32 as its second
7021    // argument.
7022    if (N1.getValueType() != MVT::i32)
7023      N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
7024    if (N2.getValueType() != MVT::i32)
7025      N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
7026    return DAG.getNode(Opc, dl, VT, N0, N1, N2);
7027  } else if (EltVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
7028    // Bits [7:6] of the constant are the source select.  This will always be
7029    //  zero here.  The DAG Combiner may combine an extract_elt index into these
7030    //  bits.  For example (insert (extract, 3), 2) could be matched by putting
7031    //  the '3' into bits [7:6] of X86ISD::INSERTPS.
7032    // Bits [5:4] of the constant are the destination select.  This is the
7033    //  value of the incoming immediate.
7034    // Bits [3:0] of the constant are the zero mask.  The DAG Combiner may
7035    //   combine either bitwise AND or insert of float 0.0 to set these bits.
7036    N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
7037    // Create this as a scalar to vector..
7038    N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
7039    return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
7040  } else if (EltVT == MVT::i32 && isa<ConstantSDNode>(N2)) {
7041    // PINSR* works with constant index.
7042    return Op;
7043  }
7044  return SDValue();
7045}
7046
7047SDValue
7048X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) const {
7049  EVT VT = Op.getValueType();
7050  EVT EltVT = VT.getVectorElementType();
7051
7052  DebugLoc dl = Op.getDebugLoc();
7053  SDValue N0 = Op.getOperand(0);
7054  SDValue N1 = Op.getOperand(1);
7055  SDValue N2 = Op.getOperand(2);
7056
7057  // If this is a 256-bit vector result, first extract the 128-bit vector,
7058  // insert the element into the extracted half and then place it back.
7059  if (VT.getSizeInBits() == 256) {
7060    if (!isa<ConstantSDNode>(N2))
7061      return SDValue();
7062
7063    // Get the desired 128-bit vector half.
7064    unsigned NumElems = VT.getVectorNumElements();
7065    unsigned IdxVal = cast<ConstantSDNode>(N2)->getZExtValue();
7066    bool Upper = IdxVal >= NumElems/2;
7067    SDValue Ins128Idx = DAG.getConstant(Upper ? NumElems/2 : 0, MVT::i32);
7068    SDValue V = Extract128BitVector(N0, Ins128Idx, DAG, dl);
7069
7070    // Insert the element into the desired half.
7071    V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V,
7072                 N1, Upper ? DAG.getConstant(IdxVal-NumElems/2, MVT::i32) : N2);
7073
7074    // Insert the changed part back to the 256-bit vector
7075    return Insert128BitVector(N0, V, Ins128Idx, DAG, dl);
7076  }
7077
7078  if (Subtarget->hasSSE41() || Subtarget->hasAVX())
7079    return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
7080
7081  if (EltVT == MVT::i8)
7082    return SDValue();
7083
7084  if (EltVT.getSizeInBits() == 16 && isa<ConstantSDNode>(N2)) {
7085    // Transform it so it match pinsrw which expects a 16-bit value in a GR32
7086    // as its second argument.
7087    if (N1.getValueType() != MVT::i32)
7088      N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
7089    if (N2.getValueType() != MVT::i32)
7090      N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
7091    return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
7092  }
7093  return SDValue();
7094}
7095
7096SDValue
7097X86TargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) const {
7098  LLVMContext *Context = DAG.getContext();
7099  DebugLoc dl = Op.getDebugLoc();
7100  EVT OpVT = Op.getValueType();
7101
7102  // If this is a 256-bit vector result, first insert into a 128-bit
7103  // vector and then insert into the 256-bit vector.
7104  if (OpVT.getSizeInBits() > 128) {
7105    // Insert into a 128-bit vector.
7106    EVT VT128 = EVT::getVectorVT(*Context,
7107                                 OpVT.getVectorElementType(),
7108                                 OpVT.getVectorNumElements() / 2);
7109
7110    Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
7111
7112    // Insert the 128-bit vector.
7113    return Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, OpVT), Op,
7114                              DAG.getConstant(0, MVT::i32),
7115                              DAG, dl);
7116  }
7117
7118  if (Op.getValueType() == MVT::v1i64 &&
7119      Op.getOperand(0).getValueType() == MVT::i64)
7120    return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
7121
7122  SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
7123  assert(Op.getValueType().getSimpleVT().getSizeInBits() == 128 &&
7124         "Expected an SSE type!");
7125  return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(),
7126                     DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,AnyExt));
7127}
7128
7129// Lower a node with an EXTRACT_SUBVECTOR opcode.  This may result in
7130// a simple subregister reference or explicit instructions to grab
7131// upper bits of a vector.
7132SDValue
7133X86TargetLowering::LowerEXTRACT_SUBVECTOR(SDValue Op, SelectionDAG &DAG) const {
7134  if (Subtarget->hasAVX()) {
7135    DebugLoc dl = Op.getNode()->getDebugLoc();
7136    SDValue Vec = Op.getNode()->getOperand(0);
7137    SDValue Idx = Op.getNode()->getOperand(1);
7138
7139    if (Op.getNode()->getValueType(0).getSizeInBits() == 128
7140        && Vec.getNode()->getValueType(0).getSizeInBits() == 256) {
7141        return Extract128BitVector(Vec, Idx, DAG, dl);
7142    }
7143  }
7144  return SDValue();
7145}
7146
7147// Lower a node with an INSERT_SUBVECTOR opcode.  This may result in a
7148// simple superregister reference or explicit instructions to insert
7149// the upper bits of a vector.
7150SDValue
7151X86TargetLowering::LowerINSERT_SUBVECTOR(SDValue Op, SelectionDAG &DAG) const {
7152  if (Subtarget->hasAVX()) {
7153    DebugLoc dl = Op.getNode()->getDebugLoc();
7154    SDValue Vec = Op.getNode()->getOperand(0);
7155    SDValue SubVec = Op.getNode()->getOperand(1);
7156    SDValue Idx = Op.getNode()->getOperand(2);
7157
7158    if (Op.getNode()->getValueType(0).getSizeInBits() == 256
7159        && SubVec.getNode()->getValueType(0).getSizeInBits() == 128) {
7160      return Insert128BitVector(Vec, SubVec, Idx, DAG, dl);
7161    }
7162  }
7163  return SDValue();
7164}
7165
7166// ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
7167// their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
7168// one of the above mentioned nodes. It has to be wrapped because otherwise
7169// Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
7170// be used to form addressing mode. These wrapped nodes will be selected
7171// into MOV32ri.
7172SDValue
7173X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
7174  ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
7175
7176  // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7177  // global base reg.
7178  unsigned char OpFlag = 0;
7179  unsigned WrapperKind = X86ISD::Wrapper;
7180  CodeModel::Model M = getTargetMachine().getCodeModel();
7181
7182  if (Subtarget->isPICStyleRIPRel() &&
7183      (M == CodeModel::Small || M == CodeModel::Kernel))
7184    WrapperKind = X86ISD::WrapperRIP;
7185  else if (Subtarget->isPICStyleGOT())
7186    OpFlag = X86II::MO_GOTOFF;
7187  else if (Subtarget->isPICStyleStubPIC())
7188    OpFlag = X86II::MO_PIC_BASE_OFFSET;
7189
7190  SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
7191                                             CP->getAlignment(),
7192                                             CP->getOffset(), OpFlag);
7193  DebugLoc DL = CP->getDebugLoc();
7194  Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7195  // With PIC, the address is actually $g + Offset.
7196  if (OpFlag) {
7197    Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7198                         DAG.getNode(X86ISD::GlobalBaseReg,
7199                                     DebugLoc(), getPointerTy()),
7200                         Result);
7201  }
7202
7203  return Result;
7204}
7205
7206SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
7207  JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
7208
7209  // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7210  // global base reg.
7211  unsigned char OpFlag = 0;
7212  unsigned WrapperKind = X86ISD::Wrapper;
7213  CodeModel::Model M = getTargetMachine().getCodeModel();
7214
7215  if (Subtarget->isPICStyleRIPRel() &&
7216      (M == CodeModel::Small || M == CodeModel::Kernel))
7217    WrapperKind = X86ISD::WrapperRIP;
7218  else if (Subtarget->isPICStyleGOT())
7219    OpFlag = X86II::MO_GOTOFF;
7220  else if (Subtarget->isPICStyleStubPIC())
7221    OpFlag = X86II::MO_PIC_BASE_OFFSET;
7222
7223  SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
7224                                          OpFlag);
7225  DebugLoc DL = JT->getDebugLoc();
7226  Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7227
7228  // With PIC, the address is actually $g + Offset.
7229  if (OpFlag)
7230    Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7231                         DAG.getNode(X86ISD::GlobalBaseReg,
7232                                     DebugLoc(), getPointerTy()),
7233                         Result);
7234
7235  return Result;
7236}
7237
7238SDValue
7239X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
7240  const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
7241
7242  // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7243  // global base reg.
7244  unsigned char OpFlag = 0;
7245  unsigned WrapperKind = X86ISD::Wrapper;
7246  CodeModel::Model M = getTargetMachine().getCodeModel();
7247
7248  if (Subtarget->isPICStyleRIPRel() &&
7249      (M == CodeModel::Small || M == CodeModel::Kernel)) {
7250    if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
7251      OpFlag = X86II::MO_GOTPCREL;
7252    WrapperKind = X86ISD::WrapperRIP;
7253  } else if (Subtarget->isPICStyleGOT()) {
7254    OpFlag = X86II::MO_GOT;
7255  } else if (Subtarget->isPICStyleStubPIC()) {
7256    OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
7257  } else if (Subtarget->isPICStyleStubNoDynamic()) {
7258    OpFlag = X86II::MO_DARWIN_NONLAZY;
7259  }
7260
7261  SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
7262
7263  DebugLoc DL = Op.getDebugLoc();
7264  Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7265
7266
7267  // With PIC, the address is actually $g + Offset.
7268  if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
7269      !Subtarget->is64Bit()) {
7270    Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7271                         DAG.getNode(X86ISD::GlobalBaseReg,
7272                                     DebugLoc(), getPointerTy()),
7273                         Result);
7274  }
7275
7276  // For symbols that require a load from a stub to get the address, emit the
7277  // load.
7278  if (isGlobalStubReference(OpFlag))
7279    Result = DAG.getLoad(getPointerTy(), DL, DAG.getEntryNode(), Result,
7280                         MachinePointerInfo::getGOT(), false, false, 0);
7281
7282  return Result;
7283}
7284
7285SDValue
7286X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
7287  // Create the TargetBlockAddressAddress node.
7288  unsigned char OpFlags =
7289    Subtarget->ClassifyBlockAddressReference();
7290  CodeModel::Model M = getTargetMachine().getCodeModel();
7291  const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
7292  DebugLoc dl = Op.getDebugLoc();
7293  SDValue Result = DAG.getBlockAddress(BA, getPointerTy(),
7294                                       /*isTarget=*/true, OpFlags);
7295
7296  if (Subtarget->isPICStyleRIPRel() &&
7297      (M == CodeModel::Small || M == CodeModel::Kernel))
7298    Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
7299  else
7300    Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
7301
7302  // With PIC, the address is actually $g + Offset.
7303  if (isGlobalRelativeToPICBase(OpFlags)) {
7304    Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
7305                         DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
7306                         Result);
7307  }
7308
7309  return Result;
7310}
7311
7312SDValue
7313X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, DebugLoc dl,
7314                                      int64_t Offset,
7315                                      SelectionDAG &DAG) const {
7316  // Create the TargetGlobalAddress node, folding in the constant
7317  // offset if it is legal.
7318  unsigned char OpFlags =
7319    Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
7320  CodeModel::Model M = getTargetMachine().getCodeModel();
7321  SDValue Result;
7322  if (OpFlags == X86II::MO_NO_FLAG &&
7323      X86::isOffsetSuitableForCodeModel(Offset, M)) {
7324    // A direct static reference to a global.
7325    Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
7326    Offset = 0;
7327  } else {
7328    Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
7329  }
7330
7331  if (Subtarget->isPICStyleRIPRel() &&
7332      (M == CodeModel::Small || M == CodeModel::Kernel))
7333    Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
7334  else
7335    Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
7336
7337  // With PIC, the address is actually $g + Offset.
7338  if (isGlobalRelativeToPICBase(OpFlags)) {
7339    Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
7340                         DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
7341                         Result);
7342  }
7343
7344  // For globals that require a load from a stub to get the address, emit the
7345  // load.
7346  if (isGlobalStubReference(OpFlags))
7347    Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
7348                         MachinePointerInfo::getGOT(), false, false, 0);
7349
7350  // If there was a non-zero offset that we didn't fold, create an explicit
7351  // addition for it.
7352  if (Offset != 0)
7353    Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
7354                         DAG.getConstant(Offset, getPointerTy()));
7355
7356  return Result;
7357}
7358
7359SDValue
7360X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
7361  const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
7362  int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
7363  return LowerGlobalAddress(GV, Op.getDebugLoc(), Offset, DAG);
7364}
7365
7366static SDValue
7367GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
7368           SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
7369           unsigned char OperandFlags) {
7370  MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7371  SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7372  DebugLoc dl = GA->getDebugLoc();
7373  SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7374                                           GA->getValueType(0),
7375                                           GA->getOffset(),
7376                                           OperandFlags);
7377  if (InFlag) {
7378    SDValue Ops[] = { Chain,  TGA, *InFlag };
7379    Chain = DAG.getNode(X86ISD::TLSADDR, dl, NodeTys, Ops, 3);
7380  } else {
7381    SDValue Ops[]  = { Chain, TGA };
7382    Chain = DAG.getNode(X86ISD::TLSADDR, dl, NodeTys, Ops, 2);
7383  }
7384
7385  // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
7386  MFI->setAdjustsStack(true);
7387
7388  SDValue Flag = Chain.getValue(1);
7389  return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
7390}
7391
7392// Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
7393static SDValue
7394LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7395                                const EVT PtrVT) {
7396  SDValue InFlag;
7397  DebugLoc dl = GA->getDebugLoc();  // ? function entry point might be better
7398  SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
7399                                     DAG.getNode(X86ISD::GlobalBaseReg,
7400                                                 DebugLoc(), PtrVT), InFlag);
7401  InFlag = Chain.getValue(1);
7402
7403  return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
7404}
7405
7406// Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
7407static SDValue
7408LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7409                                const EVT PtrVT) {
7410  return GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT,
7411                    X86::RAX, X86II::MO_TLSGD);
7412}
7413
7414// Lower ISD::GlobalTLSAddress using the "initial exec" (for no-pic) or
7415// "local exec" model.
7416static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7417                                   const EVT PtrVT, TLSModel::Model model,
7418                                   bool is64Bit) {
7419  DebugLoc dl = GA->getDebugLoc();
7420
7421  // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
7422  Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
7423                                                         is64Bit ? 257 : 256));
7424
7425  SDValue ThreadPointer = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
7426                                      DAG.getIntPtrConstant(0),
7427                                      MachinePointerInfo(Ptr), false, false, 0);
7428
7429  unsigned char OperandFlags = 0;
7430  // Most TLS accesses are not RIP relative, even on x86-64.  One exception is
7431  // initialexec.
7432  unsigned WrapperKind = X86ISD::Wrapper;
7433  if (model == TLSModel::LocalExec) {
7434    OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
7435  } else if (is64Bit) {
7436    assert(model == TLSModel::InitialExec);
7437    OperandFlags = X86II::MO_GOTTPOFF;
7438    WrapperKind = X86ISD::WrapperRIP;
7439  } else {
7440    assert(model == TLSModel::InitialExec);
7441    OperandFlags = X86II::MO_INDNTPOFF;
7442  }
7443
7444  // emit "addl x@ntpoff,%eax" (local exec) or "addl x@indntpoff,%eax" (initial
7445  // exec)
7446  SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7447                                           GA->getValueType(0),
7448                                           GA->getOffset(), OperandFlags);
7449  SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
7450
7451  if (model == TLSModel::InitialExec)
7452    Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
7453                         MachinePointerInfo::getGOT(), false, false, 0);
7454
7455  // The address of the thread local variable is the add of the thread
7456  // pointer with the offset of the variable.
7457  return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
7458}
7459
7460SDValue
7461X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
7462
7463  GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
7464  const GlobalValue *GV = GA->getGlobal();
7465
7466  if (Subtarget->isTargetELF()) {
7467    // TODO: implement the "local dynamic" model
7468    // TODO: implement the "initial exec"model for pic executables
7469
7470    // If GV is an alias then use the aliasee for determining
7471    // thread-localness.
7472    if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
7473      GV = GA->resolveAliasedGlobal(false);
7474
7475    TLSModel::Model model
7476      = getTLSModel(GV, getTargetMachine().getRelocationModel());
7477
7478    switch (model) {
7479      case TLSModel::GeneralDynamic:
7480      case TLSModel::LocalDynamic: // not implemented
7481        if (Subtarget->is64Bit())
7482          return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
7483        return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
7484
7485      case TLSModel::InitialExec:
7486      case TLSModel::LocalExec:
7487        return LowerToTLSExecModel(GA, DAG, getPointerTy(), model,
7488                                   Subtarget->is64Bit());
7489    }
7490  } else if (Subtarget->isTargetDarwin()) {
7491    // Darwin only has one model of TLS.  Lower to that.
7492    unsigned char OpFlag = 0;
7493    unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
7494                           X86ISD::WrapperRIP : X86ISD::Wrapper;
7495
7496    // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7497    // global base reg.
7498    bool PIC32 = (getTargetMachine().getRelocationModel() == Reloc::PIC_) &&
7499                  !Subtarget->is64Bit();
7500    if (PIC32)
7501      OpFlag = X86II::MO_TLVP_PIC_BASE;
7502    else
7503      OpFlag = X86II::MO_TLVP;
7504    DebugLoc DL = Op.getDebugLoc();
7505    SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
7506                                                GA->getValueType(0),
7507                                                GA->getOffset(), OpFlag);
7508    SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7509
7510    // With PIC32, the address is actually $g + Offset.
7511    if (PIC32)
7512      Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7513                           DAG.getNode(X86ISD::GlobalBaseReg,
7514                                       DebugLoc(), getPointerTy()),
7515                           Offset);
7516
7517    // Lowering the machine isd will make sure everything is in the right
7518    // location.
7519    SDValue Chain = DAG.getEntryNode();
7520    SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7521    SDValue Args[] = { Chain, Offset };
7522    Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args, 2);
7523
7524    // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
7525    MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7526    MFI->setAdjustsStack(true);
7527
7528    // And our return value (tls address) is in the standard call return value
7529    // location.
7530    unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
7531    return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy(),
7532                              Chain.getValue(1));
7533  }
7534
7535  assert(false &&
7536         "TLS not implemented for this target.");
7537
7538  llvm_unreachable("Unreachable");
7539  return SDValue();
7540}
7541
7542
7543/// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values and
7544/// take a 2 x i32 value to shift plus a shift amount.
7545SDValue X86TargetLowering::LowerShiftParts(SDValue Op, SelectionDAG &DAG) const {
7546  assert(Op.getNumOperands() == 3 && "Not a double-shift!");
7547  EVT VT = Op.getValueType();
7548  unsigned VTBits = VT.getSizeInBits();
7549  DebugLoc dl = Op.getDebugLoc();
7550  bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
7551  SDValue ShOpLo = Op.getOperand(0);
7552  SDValue ShOpHi = Op.getOperand(1);
7553  SDValue ShAmt  = Op.getOperand(2);
7554  SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
7555                                     DAG.getConstant(VTBits - 1, MVT::i8))
7556                       : DAG.getConstant(0, VT);
7557
7558  SDValue Tmp2, Tmp3;
7559  if (Op.getOpcode() == ISD::SHL_PARTS) {
7560    Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
7561    Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
7562  } else {
7563    Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
7564    Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, ShAmt);
7565  }
7566
7567  SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
7568                                DAG.getConstant(VTBits, MVT::i8));
7569  SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
7570                             AndNode, DAG.getConstant(0, MVT::i8));
7571
7572  SDValue Hi, Lo;
7573  SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
7574  SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
7575  SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
7576
7577  if (Op.getOpcode() == ISD::SHL_PARTS) {
7578    Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
7579    Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
7580  } else {
7581    Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
7582    Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
7583  }
7584
7585  SDValue Ops[2] = { Lo, Hi };
7586  return DAG.getMergeValues(Ops, 2, dl);
7587}
7588
7589SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
7590                                           SelectionDAG &DAG) const {
7591  EVT SrcVT = Op.getOperand(0).getValueType();
7592
7593  if (SrcVT.isVector())
7594    return SDValue();
7595
7596  assert(SrcVT.getSimpleVT() <= MVT::i64 && SrcVT.getSimpleVT() >= MVT::i16 &&
7597         "Unknown SINT_TO_FP to lower!");
7598
7599  // These are really Legal; return the operand so the caller accepts it as
7600  // Legal.
7601  if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
7602    return Op;
7603  if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
7604      Subtarget->is64Bit()) {
7605    return Op;
7606  }
7607
7608  DebugLoc dl = Op.getDebugLoc();
7609  unsigned Size = SrcVT.getSizeInBits()/8;
7610  MachineFunction &MF = DAG.getMachineFunction();
7611  int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
7612  SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7613  SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
7614                               StackSlot,
7615                               MachinePointerInfo::getFixedStack(SSFI),
7616                               false, false, 0);
7617  return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
7618}
7619
7620SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
7621                                     SDValue StackSlot,
7622                                     SelectionDAG &DAG) const {
7623  // Build the FILD
7624  DebugLoc DL = Op.getDebugLoc();
7625  SDVTList Tys;
7626  bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
7627  if (useSSE)
7628    Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
7629  else
7630    Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
7631
7632  unsigned ByteSize = SrcVT.getSizeInBits()/8;
7633
7634  FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
7635  MachineMemOperand *MMO;
7636  if (FI) {
7637    int SSFI = FI->getIndex();
7638    MMO =
7639      DAG.getMachineFunction()
7640      .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7641                            MachineMemOperand::MOLoad, ByteSize, ByteSize);
7642  } else {
7643    MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
7644    StackSlot = StackSlot.getOperand(1);
7645  }
7646  SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
7647  SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
7648                                           X86ISD::FILD, DL,
7649                                           Tys, Ops, array_lengthof(Ops),
7650                                           SrcVT, MMO);
7651
7652  if (useSSE) {
7653    Chain = Result.getValue(1);
7654    SDValue InFlag = Result.getValue(2);
7655
7656    // FIXME: Currently the FST is flagged to the FILD_FLAG. This
7657    // shouldn't be necessary except that RFP cannot be live across
7658    // multiple blocks. When stackifier is fixed, they can be uncoupled.
7659    MachineFunction &MF = DAG.getMachineFunction();
7660    unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
7661    int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
7662    SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7663    Tys = DAG.getVTList(MVT::Other);
7664    SDValue Ops[] = {
7665      Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
7666    };
7667    MachineMemOperand *MMO =
7668      DAG.getMachineFunction()
7669      .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7670                            MachineMemOperand::MOStore, SSFISize, SSFISize);
7671
7672    Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
7673                                    Ops, array_lengthof(Ops),
7674                                    Op.getValueType(), MMO);
7675    Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
7676                         MachinePointerInfo::getFixedStack(SSFI),
7677                         false, false, 0);
7678  }
7679
7680  return Result;
7681}
7682
7683// LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
7684SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
7685                                               SelectionDAG &DAG) const {
7686  // This algorithm is not obvious. Here it is in C code, more or less:
7687  /*
7688    double uint64_to_double( uint32_t hi, uint32_t lo ) {
7689      static const __m128i exp = { 0x4330000045300000ULL, 0 };
7690      static const __m128d bias = { 0x1.0p84, 0x1.0p52 };
7691
7692      // Copy ints to xmm registers.
7693      __m128i xh = _mm_cvtsi32_si128( hi );
7694      __m128i xl = _mm_cvtsi32_si128( lo );
7695
7696      // Combine into low half of a single xmm register.
7697      __m128i x = _mm_unpacklo_epi32( xh, xl );
7698      __m128d d;
7699      double sd;
7700
7701      // Merge in appropriate exponents to give the integer bits the right
7702      // magnitude.
7703      x = _mm_unpacklo_epi32( x, exp );
7704
7705      // Subtract away the biases to deal with the IEEE-754 double precision
7706      // implicit 1.
7707      d = _mm_sub_pd( (__m128d) x, bias );
7708
7709      // All conversions up to here are exact. The correctly rounded result is
7710      // calculated using the current rounding mode using the following
7711      // horizontal add.
7712      d = _mm_add_sd( d, _mm_unpackhi_pd( d, d ) );
7713      _mm_store_sd( &sd, d );   // Because we are returning doubles in XMM, this
7714                                // store doesn't really need to be here (except
7715                                // maybe to zero the other double)
7716      return sd;
7717    }
7718  */
7719
7720  DebugLoc dl = Op.getDebugLoc();
7721  LLVMContext *Context = DAG.getContext();
7722
7723  // Build some magic constants.
7724  std::vector<Constant*> CV0;
7725  CV0.push_back(ConstantInt::get(*Context, APInt(32, 0x45300000)));
7726  CV0.push_back(ConstantInt::get(*Context, APInt(32, 0x43300000)));
7727  CV0.push_back(ConstantInt::get(*Context, APInt(32, 0)));
7728  CV0.push_back(ConstantInt::get(*Context, APInt(32, 0)));
7729  Constant *C0 = ConstantVector::get(CV0);
7730  SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
7731
7732  std::vector<Constant*> CV1;
7733  CV1.push_back(
7734    ConstantFP::get(*Context, APFloat(APInt(64, 0x4530000000000000ULL))));
7735  CV1.push_back(
7736    ConstantFP::get(*Context, APFloat(APInt(64, 0x4330000000000000ULL))));
7737  Constant *C1 = ConstantVector::get(CV1);
7738  SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
7739
7740  SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
7741                            DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
7742                                        Op.getOperand(0),
7743                                        DAG.getIntPtrConstant(1)));
7744  SDValue XR2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
7745                            DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
7746                                        Op.getOperand(0),
7747                                        DAG.getIntPtrConstant(0)));
7748  SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32, XR1, XR2);
7749  SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
7750                              MachinePointerInfo::getConstantPool(),
7751                              false, false, 16);
7752  SDValue Unpck2 = getUnpackl(DAG, dl, MVT::v4i32, Unpck1, CLod0);
7753  SDValue XR2F = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Unpck2);
7754  SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
7755                              MachinePointerInfo::getConstantPool(),
7756                              false, false, 16);
7757  SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
7758
7759  // Add the halves; easiest way is to swap them into another reg first.
7760  int ShufMask[2] = { 1, -1 };
7761  SDValue Shuf = DAG.getVectorShuffle(MVT::v2f64, dl, Sub,
7762                                      DAG.getUNDEF(MVT::v2f64), ShufMask);
7763  SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::v2f64, Shuf, Sub);
7764  return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Add,
7765                     DAG.getIntPtrConstant(0));
7766}
7767
7768// LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
7769SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
7770                                               SelectionDAG &DAG) const {
7771  DebugLoc dl = Op.getDebugLoc();
7772  // FP constant to bias correct the final result.
7773  SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
7774                                   MVT::f64);
7775
7776  // Load the 32-bit value into an XMM register.
7777  SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
7778                             Op.getOperand(0));
7779
7780  // Zero out the upper parts of the register.
7781  Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget->hasXMMInt(),
7782                                     DAG);
7783
7784  Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
7785                     DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Load),
7786                     DAG.getIntPtrConstant(0));
7787
7788  // Or the load with the bias.
7789  SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
7790                           DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
7791                                       DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
7792                                                   MVT::v2f64, Load)),
7793                           DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
7794                                       DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
7795                                                   MVT::v2f64, Bias)));
7796  Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
7797                   DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or),
7798                   DAG.getIntPtrConstant(0));
7799
7800  // Subtract the bias.
7801  SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
7802
7803  // Handle final rounding.
7804  EVT DestVT = Op.getValueType();
7805
7806  if (DestVT.bitsLT(MVT::f64)) {
7807    return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
7808                       DAG.getIntPtrConstant(0));
7809  } else if (DestVT.bitsGT(MVT::f64)) {
7810    return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
7811  }
7812
7813  // Handle final rounding.
7814  return Sub;
7815}
7816
7817SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
7818                                           SelectionDAG &DAG) const {
7819  SDValue N0 = Op.getOperand(0);
7820  DebugLoc dl = Op.getDebugLoc();
7821
7822  // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
7823  // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
7824  // the optimization here.
7825  if (DAG.SignBitIsZero(N0))
7826    return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
7827
7828  EVT SrcVT = N0.getValueType();
7829  EVT DstVT = Op.getValueType();
7830  if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
7831    return LowerUINT_TO_FP_i64(Op, DAG);
7832  else if (SrcVT == MVT::i32 && X86ScalarSSEf64)
7833    return LowerUINT_TO_FP_i32(Op, DAG);
7834
7835  // Make a 64-bit buffer, and use it to build an FILD.
7836  SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
7837  if (SrcVT == MVT::i32) {
7838    SDValue WordOff = DAG.getConstant(4, getPointerTy());
7839    SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
7840                                     getPointerTy(), StackSlot, WordOff);
7841    SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
7842                                  StackSlot, MachinePointerInfo(),
7843                                  false, false, 0);
7844    SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
7845                                  OffsetSlot, MachinePointerInfo(),
7846                                  false, false, 0);
7847    SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
7848    return Fild;
7849  }
7850
7851  assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
7852  SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
7853                                StackSlot, MachinePointerInfo(),
7854                               false, false, 0);
7855  // For i64 source, we need to add the appropriate power of 2 if the input
7856  // was negative.  This is the same as the optimization in
7857  // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
7858  // we must be careful to do the computation in x87 extended precision, not
7859  // in SSE. (The generic code can't know it's OK to do this, or how to.)
7860  int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
7861  MachineMemOperand *MMO =
7862    DAG.getMachineFunction()
7863    .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7864                          MachineMemOperand::MOLoad, 8, 8);
7865
7866  SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
7867  SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
7868  SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops, 3,
7869                                         MVT::i64, MMO);
7870
7871  APInt FF(32, 0x5F800000ULL);
7872
7873  // Check whether the sign bit is set.
7874  SDValue SignSet = DAG.getSetCC(dl, getSetCCResultType(MVT::i64),
7875                                 Op.getOperand(0), DAG.getConstant(0, MVT::i64),
7876                                 ISD::SETLT);
7877
7878  // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
7879  SDValue FudgePtr = DAG.getConstantPool(
7880                             ConstantInt::get(*DAG.getContext(), FF.zext(64)),
7881                                         getPointerTy());
7882
7883  // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
7884  SDValue Zero = DAG.getIntPtrConstant(0);
7885  SDValue Four = DAG.getIntPtrConstant(4);
7886  SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
7887                               Zero, Four);
7888  FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
7889
7890  // Load the value out, extending it from f32 to f80.
7891  // FIXME: Avoid the extend by constructing the right constant pool?
7892  SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(),
7893                                 FudgePtr, MachinePointerInfo::getConstantPool(),
7894                                 MVT::f32, false, false, 4);
7895  // Extend everything to 80 bits to force it to be done on x87.
7896  SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
7897  return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add, DAG.getIntPtrConstant(0));
7898}
7899
7900std::pair<SDValue,SDValue> X86TargetLowering::
7901FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG, bool IsSigned) const {
7902  DebugLoc DL = Op.getDebugLoc();
7903
7904  EVT DstTy = Op.getValueType();
7905
7906  if (!IsSigned) {
7907    assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
7908    DstTy = MVT::i64;
7909  }
7910
7911  assert(DstTy.getSimpleVT() <= MVT::i64 &&
7912         DstTy.getSimpleVT() >= MVT::i16 &&
7913         "Unknown FP_TO_SINT to lower!");
7914
7915  // These are really Legal.
7916  if (DstTy == MVT::i32 &&
7917      isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
7918    return std::make_pair(SDValue(), SDValue());
7919  if (Subtarget->is64Bit() &&
7920      DstTy == MVT::i64 &&
7921      isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
7922    return std::make_pair(SDValue(), SDValue());
7923
7924  // We lower FP->sint64 into FISTP64, followed by a load, all to a temporary
7925  // stack slot.
7926  MachineFunction &MF = DAG.getMachineFunction();
7927  unsigned MemSize = DstTy.getSizeInBits()/8;
7928  int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
7929  SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7930
7931
7932
7933  unsigned Opc;
7934  switch (DstTy.getSimpleVT().SimpleTy) {
7935  default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
7936  case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
7937  case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
7938  case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
7939  }
7940
7941  SDValue Chain = DAG.getEntryNode();
7942  SDValue Value = Op.getOperand(0);
7943  EVT TheVT = Op.getOperand(0).getValueType();
7944  if (isScalarFPTypeInSSEReg(TheVT)) {
7945    assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
7946    Chain = DAG.getStore(Chain, DL, Value, StackSlot,
7947                         MachinePointerInfo::getFixedStack(SSFI),
7948                         false, false, 0);
7949    SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
7950    SDValue Ops[] = {
7951      Chain, StackSlot, DAG.getValueType(TheVT)
7952    };
7953
7954    MachineMemOperand *MMO =
7955      MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7956                              MachineMemOperand::MOLoad, MemSize, MemSize);
7957    Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, 3,
7958                                    DstTy, MMO);
7959    Chain = Value.getValue(1);
7960    SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
7961    StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7962  }
7963
7964  MachineMemOperand *MMO =
7965    MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7966                            MachineMemOperand::MOStore, MemSize, MemSize);
7967
7968  // Build the FP_TO_INT*_IN_MEM
7969  SDValue Ops[] = { Chain, Value, StackSlot };
7970  SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
7971                                         Ops, 3, DstTy, MMO);
7972
7973  return std::make_pair(FIST, StackSlot);
7974}
7975
7976SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
7977                                           SelectionDAG &DAG) const {
7978  if (Op.getValueType().isVector())
7979    return SDValue();
7980
7981  std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG, true);
7982  SDValue FIST = Vals.first, StackSlot = Vals.second;
7983  // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
7984  if (FIST.getNode() == 0) return Op;
7985
7986  // Load the result.
7987  return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
7988                     FIST, StackSlot, MachinePointerInfo(), false, false, 0);
7989}
7990
7991SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
7992                                           SelectionDAG &DAG) const {
7993  std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG, false);
7994  SDValue FIST = Vals.first, StackSlot = Vals.second;
7995  assert(FIST.getNode() && "Unexpected failure");
7996
7997  // Load the result.
7998  return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
7999                     FIST, StackSlot, MachinePointerInfo(), false, false, 0);
8000}
8001
8002SDValue X86TargetLowering::LowerFABS(SDValue Op,
8003                                     SelectionDAG &DAG) const {
8004  LLVMContext *Context = DAG.getContext();
8005  DebugLoc dl = Op.getDebugLoc();
8006  EVT VT = Op.getValueType();
8007  EVT EltVT = VT;
8008  if (VT.isVector())
8009    EltVT = VT.getVectorElementType();
8010  std::vector<Constant*> CV;
8011  if (EltVT == MVT::f64) {
8012    Constant *C = ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63))));
8013    CV.push_back(C);
8014    CV.push_back(C);
8015  } else {
8016    Constant *C = ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31))));
8017    CV.push_back(C);
8018    CV.push_back(C);
8019    CV.push_back(C);
8020    CV.push_back(C);
8021  }
8022  Constant *C = ConstantVector::get(CV);
8023  SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8024  SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8025                             MachinePointerInfo::getConstantPool(),
8026                             false, false, 16);
8027  return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
8028}
8029
8030SDValue X86TargetLowering::LowerFNEG(SDValue Op, SelectionDAG &DAG) const {
8031  LLVMContext *Context = DAG.getContext();
8032  DebugLoc dl = Op.getDebugLoc();
8033  EVT VT = Op.getValueType();
8034  EVT EltVT = VT;
8035  if (VT.isVector())
8036    EltVT = VT.getVectorElementType();
8037  std::vector<Constant*> CV;
8038  if (EltVT == MVT::f64) {
8039    Constant *C = ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63)));
8040    CV.push_back(C);
8041    CV.push_back(C);
8042  } else {
8043    Constant *C = ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31)));
8044    CV.push_back(C);
8045    CV.push_back(C);
8046    CV.push_back(C);
8047    CV.push_back(C);
8048  }
8049  Constant *C = ConstantVector::get(CV);
8050  SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8051  SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8052                             MachinePointerInfo::getConstantPool(),
8053                             false, false, 16);
8054  if (VT.isVector()) {
8055    return DAG.getNode(ISD::BITCAST, dl, VT,
8056                       DAG.getNode(ISD::XOR, dl, MVT::v2i64,
8057                    DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
8058                                Op.getOperand(0)),
8059                    DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, Mask)));
8060  } else {
8061    return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
8062  }
8063}
8064
8065SDValue X86TargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
8066  LLVMContext *Context = DAG.getContext();
8067  SDValue Op0 = Op.getOperand(0);
8068  SDValue Op1 = Op.getOperand(1);
8069  DebugLoc dl = Op.getDebugLoc();
8070  EVT VT = Op.getValueType();
8071  EVT SrcVT = Op1.getValueType();
8072
8073  // If second operand is smaller, extend it first.
8074  if (SrcVT.bitsLT(VT)) {
8075    Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
8076    SrcVT = VT;
8077  }
8078  // And if it is bigger, shrink it first.
8079  if (SrcVT.bitsGT(VT)) {
8080    Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
8081    SrcVT = VT;
8082  }
8083
8084  // At this point the operands and the result should have the same
8085  // type, and that won't be f80 since that is not custom lowered.
8086
8087  // First get the sign bit of second operand.
8088  std::vector<Constant*> CV;
8089  if (SrcVT == MVT::f64) {
8090    CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63))));
8091    CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
8092  } else {
8093    CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31))));
8094    CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8095    CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8096    CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8097  }
8098  Constant *C = ConstantVector::get(CV);
8099  SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8100  SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
8101                              MachinePointerInfo::getConstantPool(),
8102                              false, false, 16);
8103  SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
8104
8105  // Shift sign bit right or left if the two operands have different types.
8106  if (SrcVT.bitsGT(VT)) {
8107    // Op0 is MVT::f32, Op1 is MVT::f64.
8108    SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
8109    SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
8110                          DAG.getConstant(32, MVT::i32));
8111    SignBit = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, SignBit);
8112    SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
8113                          DAG.getIntPtrConstant(0));
8114  }
8115
8116  // Clear first operand sign bit.
8117  CV.clear();
8118  if (VT == MVT::f64) {
8119    CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63)))));
8120    CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
8121  } else {
8122    CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31)))));
8123    CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8124    CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8125    CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8126  }
8127  C = ConstantVector::get(CV);
8128  CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8129  SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8130                              MachinePointerInfo::getConstantPool(),
8131                              false, false, 16);
8132  SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
8133
8134  // Or the value with the sign bit.
8135  return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
8136}
8137
8138SDValue X86TargetLowering::LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) const {
8139  SDValue N0 = Op.getOperand(0);
8140  DebugLoc dl = Op.getDebugLoc();
8141  EVT VT = Op.getValueType();
8142
8143  // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
8144  SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
8145                                  DAG.getConstant(1, VT));
8146  return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, VT));
8147}
8148
8149/// Emit nodes that will be selected as "test Op0,Op0", or something
8150/// equivalent.
8151SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC,
8152                                    SelectionDAG &DAG) const {
8153  DebugLoc dl = Op.getDebugLoc();
8154
8155  // CF and OF aren't always set the way we want. Determine which
8156  // of these we need.
8157  bool NeedCF = false;
8158  bool NeedOF = false;
8159  switch (X86CC) {
8160  default: break;
8161  case X86::COND_A: case X86::COND_AE:
8162  case X86::COND_B: case X86::COND_BE:
8163    NeedCF = true;
8164    break;
8165  case X86::COND_G: case X86::COND_GE:
8166  case X86::COND_L: case X86::COND_LE:
8167  case X86::COND_O: case X86::COND_NO:
8168    NeedOF = true;
8169    break;
8170  }
8171
8172  // See if we can use the EFLAGS value from the operand instead of
8173  // doing a separate TEST. TEST always sets OF and CF to 0, so unless
8174  // we prove that the arithmetic won't overflow, we can't use OF or CF.
8175  if (Op.getResNo() != 0 || NeedOF || NeedCF)
8176    // Emit a CMP with 0, which is the TEST pattern.
8177    return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
8178                       DAG.getConstant(0, Op.getValueType()));
8179
8180  unsigned Opcode = 0;
8181  unsigned NumOperands = 0;
8182  switch (Op.getNode()->getOpcode()) {
8183  case ISD::ADD:
8184    // Due to an isel shortcoming, be conservative if this add is likely to be
8185    // selected as part of a load-modify-store instruction. When the root node
8186    // in a match is a store, isel doesn't know how to remap non-chain non-flag
8187    // uses of other nodes in the match, such as the ADD in this case. This
8188    // leads to the ADD being left around and reselected, with the result being
8189    // two adds in the output.  Alas, even if none our users are stores, that
8190    // doesn't prove we're O.K.  Ergo, if we have any parents that aren't
8191    // CopyToReg or SETCC, eschew INC/DEC.  A better fix seems to require
8192    // climbing the DAG back to the root, and it doesn't seem to be worth the
8193    // effort.
8194    for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
8195           UE = Op.getNode()->use_end(); UI != UE; ++UI)
8196      if (UI->getOpcode() != ISD::CopyToReg && UI->getOpcode() != ISD::SETCC)
8197        goto default_case;
8198
8199    if (ConstantSDNode *C =
8200        dyn_cast<ConstantSDNode>(Op.getNode()->getOperand(1))) {
8201      // An add of one will be selected as an INC.
8202      if (C->getAPIntValue() == 1) {
8203        Opcode = X86ISD::INC;
8204        NumOperands = 1;
8205        break;
8206      }
8207
8208      // An add of negative one (subtract of one) will be selected as a DEC.
8209      if (C->getAPIntValue().isAllOnesValue()) {
8210        Opcode = X86ISD::DEC;
8211        NumOperands = 1;
8212        break;
8213      }
8214    }
8215
8216    // Otherwise use a regular EFLAGS-setting add.
8217    Opcode = X86ISD::ADD;
8218    NumOperands = 2;
8219    break;
8220  case ISD::AND: {
8221    // If the primary and result isn't used, don't bother using X86ISD::AND,
8222    // because a TEST instruction will be better.
8223    bool NonFlagUse = false;
8224    for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
8225           UE = Op.getNode()->use_end(); UI != UE; ++UI) {
8226      SDNode *User = *UI;
8227      unsigned UOpNo = UI.getOperandNo();
8228      if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
8229        // Look pass truncate.
8230        UOpNo = User->use_begin().getOperandNo();
8231        User = *User->use_begin();
8232      }
8233
8234      if (User->getOpcode() != ISD::BRCOND &&
8235          User->getOpcode() != ISD::SETCC &&
8236          (User->getOpcode() != ISD::SELECT || UOpNo != 0)) {
8237        NonFlagUse = true;
8238        break;
8239      }
8240    }
8241
8242    if (!NonFlagUse)
8243      break;
8244  }
8245    // FALL THROUGH
8246  case ISD::SUB:
8247  case ISD::OR:
8248  case ISD::XOR:
8249    // Due to the ISEL shortcoming noted above, be conservative if this op is
8250    // likely to be selected as part of a load-modify-store instruction.
8251    for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
8252           UE = Op.getNode()->use_end(); UI != UE; ++UI)
8253      if (UI->getOpcode() == ISD::STORE)
8254        goto default_case;
8255
8256    // Otherwise use a regular EFLAGS-setting instruction.
8257    switch (Op.getNode()->getOpcode()) {
8258    default: llvm_unreachable("unexpected operator!");
8259    case ISD::SUB: Opcode = X86ISD::SUB; break;
8260    case ISD::OR:  Opcode = X86ISD::OR;  break;
8261    case ISD::XOR: Opcode = X86ISD::XOR; break;
8262    case ISD::AND: Opcode = X86ISD::AND; break;
8263    }
8264
8265    NumOperands = 2;
8266    break;
8267  case X86ISD::ADD:
8268  case X86ISD::SUB:
8269  case X86ISD::INC:
8270  case X86ISD::DEC:
8271  case X86ISD::OR:
8272  case X86ISD::XOR:
8273  case X86ISD::AND:
8274    return SDValue(Op.getNode(), 1);
8275  default:
8276  default_case:
8277    break;
8278  }
8279
8280  if (Opcode == 0)
8281    // Emit a CMP with 0, which is the TEST pattern.
8282    return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
8283                       DAG.getConstant(0, Op.getValueType()));
8284
8285  SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
8286  SmallVector<SDValue, 4> Ops;
8287  for (unsigned i = 0; i != NumOperands; ++i)
8288    Ops.push_back(Op.getOperand(i));
8289
8290  SDValue New = DAG.getNode(Opcode, dl, VTs, &Ops[0], NumOperands);
8291  DAG.ReplaceAllUsesWith(Op, New);
8292  return SDValue(New.getNode(), 1);
8293}
8294
8295/// Emit nodes that will be selected as "cmp Op0,Op1", or something
8296/// equivalent.
8297SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
8298                                   SelectionDAG &DAG) const {
8299  if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1))
8300    if (C->getAPIntValue() == 0)
8301      return EmitTest(Op0, X86CC, DAG);
8302
8303  DebugLoc dl = Op0.getDebugLoc();
8304  return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
8305}
8306
8307/// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
8308/// if it's possible.
8309SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
8310                                     DebugLoc dl, SelectionDAG &DAG) const {
8311  SDValue Op0 = And.getOperand(0);
8312  SDValue Op1 = And.getOperand(1);
8313  if (Op0.getOpcode() == ISD::TRUNCATE)
8314    Op0 = Op0.getOperand(0);
8315  if (Op1.getOpcode() == ISD::TRUNCATE)
8316    Op1 = Op1.getOperand(0);
8317
8318  SDValue LHS, RHS;
8319  if (Op1.getOpcode() == ISD::SHL)
8320    std::swap(Op0, Op1);
8321  if (Op0.getOpcode() == ISD::SHL) {
8322    if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
8323      if (And00C->getZExtValue() == 1) {
8324        // If we looked past a truncate, check that it's only truncating away
8325        // known zeros.
8326        unsigned BitWidth = Op0.getValueSizeInBits();
8327        unsigned AndBitWidth = And.getValueSizeInBits();
8328        if (BitWidth > AndBitWidth) {
8329          APInt Mask = APInt::getAllOnesValue(BitWidth), Zeros, Ones;
8330          DAG.ComputeMaskedBits(Op0, Mask, Zeros, Ones);
8331          if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
8332            return SDValue();
8333        }
8334        LHS = Op1;
8335        RHS = Op0.getOperand(1);
8336      }
8337  } else if (Op1.getOpcode() == ISD::Constant) {
8338    ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
8339    SDValue AndLHS = Op0;
8340    if (AndRHS->getZExtValue() == 1 && AndLHS.getOpcode() == ISD::SRL) {
8341      LHS = AndLHS.getOperand(0);
8342      RHS = AndLHS.getOperand(1);
8343    }
8344  }
8345
8346  if (LHS.getNode()) {
8347    // If LHS is i8, promote it to i32 with any_extend.  There is no i8 BT
8348    // instruction.  Since the shift amount is in-range-or-undefined, we know
8349    // that doing a bittest on the i32 value is ok.  We extend to i32 because
8350    // the encoding for the i16 version is larger than the i32 version.
8351    // Also promote i16 to i32 for performance / code size reason.
8352    if (LHS.getValueType() == MVT::i8 ||
8353        LHS.getValueType() == MVT::i16)
8354      LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
8355
8356    // If the operand types disagree, extend the shift amount to match.  Since
8357    // BT ignores high bits (like shifts) we can use anyextend.
8358    if (LHS.getValueType() != RHS.getValueType())
8359      RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
8360
8361    SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
8362    unsigned Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
8363    return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
8364                       DAG.getConstant(Cond, MVT::i8), BT);
8365  }
8366
8367  return SDValue();
8368}
8369
8370SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
8371
8372  if (Op.getValueType().isVector()) return LowerVSETCC(Op, DAG);
8373
8374  assert(Op.getValueType() == MVT::i8 && "SetCC type must be 8-bit integer");
8375  SDValue Op0 = Op.getOperand(0);
8376  SDValue Op1 = Op.getOperand(1);
8377  DebugLoc dl = Op.getDebugLoc();
8378  ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
8379
8380  // Optimize to BT if possible.
8381  // Lower (X & (1 << N)) == 0 to BT(X, N).
8382  // Lower ((X >>u N) & 1) != 0 to BT(X, N).
8383  // Lower ((X >>s N) & 1) != 0 to BT(X, N).
8384  if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
8385      Op1.getOpcode() == ISD::Constant &&
8386      cast<ConstantSDNode>(Op1)->isNullValue() &&
8387      (CC == ISD::SETEQ || CC == ISD::SETNE)) {
8388    SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
8389    if (NewSetCC.getNode())
8390      return NewSetCC;
8391  }
8392
8393  // Look for X == 0, X == 1, X != 0, or X != 1.  We can simplify some forms of
8394  // these.
8395  if (Op1.getOpcode() == ISD::Constant &&
8396      (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
8397       cast<ConstantSDNode>(Op1)->isNullValue()) &&
8398      (CC == ISD::SETEQ || CC == ISD::SETNE)) {
8399
8400    // If the input is a setcc, then reuse the input setcc or use a new one with
8401    // the inverted condition.
8402    if (Op0.getOpcode() == X86ISD::SETCC) {
8403      X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
8404      bool Invert = (CC == ISD::SETNE) ^
8405        cast<ConstantSDNode>(Op1)->isNullValue();
8406      if (!Invert) return Op0;
8407
8408      CCode = X86::GetOppositeBranchCondition(CCode);
8409      return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
8410                         DAG.getConstant(CCode, MVT::i8), Op0.getOperand(1));
8411    }
8412  }
8413
8414  bool isFP = Op1.getValueType().isFloatingPoint();
8415  unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
8416  if (X86CC == X86::COND_INVALID)
8417    return SDValue();
8418
8419  SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, DAG);
8420  return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
8421                     DAG.getConstant(X86CC, MVT::i8), EFLAGS);
8422}
8423
8424// Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
8425// ones, and then concatenate the result back.
8426static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
8427  EVT VT = Op.getValueType();
8428
8429  assert(VT.getSizeInBits() == 256 && Op.getOpcode() == ISD::SETCC &&
8430         "Unsupported value type for operation");
8431
8432  int NumElems = VT.getVectorNumElements();
8433  DebugLoc dl = Op.getDebugLoc();
8434  SDValue CC = Op.getOperand(2);
8435  SDValue Idx0 = DAG.getConstant(0, MVT::i32);
8436  SDValue Idx1 = DAG.getConstant(NumElems/2, MVT::i32);
8437
8438  // Extract the LHS vectors
8439  SDValue LHS = Op.getOperand(0);
8440  SDValue LHS1 = Extract128BitVector(LHS, Idx0, DAG, dl);
8441  SDValue LHS2 = Extract128BitVector(LHS, Idx1, DAG, dl);
8442
8443  // Extract the RHS vectors
8444  SDValue RHS = Op.getOperand(1);
8445  SDValue RHS1 = Extract128BitVector(RHS, Idx0, DAG, dl);
8446  SDValue RHS2 = Extract128BitVector(RHS, Idx1, DAG, dl);
8447
8448  // Issue the operation on the smaller types and concatenate the result back
8449  MVT EltVT = VT.getVectorElementType().getSimpleVT();
8450  EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
8451  return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
8452                     DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
8453                     DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
8454}
8455
8456
8457SDValue X86TargetLowering::LowerVSETCC(SDValue Op, SelectionDAG &DAG) const {
8458  SDValue Cond;
8459  SDValue Op0 = Op.getOperand(0);
8460  SDValue Op1 = Op.getOperand(1);
8461  SDValue CC = Op.getOperand(2);
8462  EVT VT = Op.getValueType();
8463  ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
8464  bool isFP = Op.getOperand(1).getValueType().isFloatingPoint();
8465  DebugLoc dl = Op.getDebugLoc();
8466
8467  if (isFP) {
8468    unsigned SSECC = 8;
8469    EVT EltVT = Op0.getValueType().getVectorElementType();
8470    assert(EltVT == MVT::f32 || EltVT == MVT::f64);
8471
8472    unsigned Opc = EltVT == MVT::f32 ? X86ISD::CMPPS : X86ISD::CMPPD;
8473    bool Swap = false;
8474
8475    // SSE Condition code mapping:
8476    //  0 - EQ
8477    //  1 - LT
8478    //  2 - LE
8479    //  3 - UNORD
8480    //  4 - NEQ
8481    //  5 - NLT
8482    //  6 - NLE
8483    //  7 - ORD
8484    switch (SetCCOpcode) {
8485    default: break;
8486    case ISD::SETOEQ:
8487    case ISD::SETEQ:  SSECC = 0; break;
8488    case ISD::SETOGT:
8489    case ISD::SETGT: Swap = true; // Fallthrough
8490    case ISD::SETLT:
8491    case ISD::SETOLT: SSECC = 1; break;
8492    case ISD::SETOGE:
8493    case ISD::SETGE: Swap = true; // Fallthrough
8494    case ISD::SETLE:
8495    case ISD::SETOLE: SSECC = 2; break;
8496    case ISD::SETUO:  SSECC = 3; break;
8497    case ISD::SETUNE:
8498    case ISD::SETNE:  SSECC = 4; break;
8499    case ISD::SETULE: Swap = true;
8500    case ISD::SETUGE: SSECC = 5; break;
8501    case ISD::SETULT: Swap = true;
8502    case ISD::SETUGT: SSECC = 6; break;
8503    case ISD::SETO:   SSECC = 7; break;
8504    }
8505    if (Swap)
8506      std::swap(Op0, Op1);
8507
8508    // In the two special cases we can't handle, emit two comparisons.
8509    if (SSECC == 8) {
8510      if (SetCCOpcode == ISD::SETUEQ) {
8511        SDValue UNORD, EQ;
8512        UNORD = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(3, MVT::i8));
8513        EQ = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(0, MVT::i8));
8514        return DAG.getNode(ISD::OR, dl, VT, UNORD, EQ);
8515      }
8516      else if (SetCCOpcode == ISD::SETONE) {
8517        SDValue ORD, NEQ;
8518        ORD = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(7, MVT::i8));
8519        NEQ = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(4, MVT::i8));
8520        return DAG.getNode(ISD::AND, dl, VT, ORD, NEQ);
8521      }
8522      llvm_unreachable("Illegal FP comparison");
8523    }
8524    // Handle all other FP comparisons here.
8525    return DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(SSECC, MVT::i8));
8526  }
8527
8528  // Break 256-bit integer vector compare into smaller ones.
8529  if (!isFP && VT.getSizeInBits() == 256)
8530    return Lower256IntVSETCC(Op, DAG);
8531
8532  // We are handling one of the integer comparisons here.  Since SSE only has
8533  // GT and EQ comparisons for integer, swapping operands and multiple
8534  // operations may be required for some comparisons.
8535  unsigned Opc = 0, EQOpc = 0, GTOpc = 0;
8536  bool Swap = false, Invert = false, FlipSigns = false;
8537
8538  switch (VT.getSimpleVT().SimpleTy) {
8539  default: break;
8540  case MVT::v16i8: EQOpc = X86ISD::PCMPEQB; GTOpc = X86ISD::PCMPGTB; break;
8541  case MVT::v8i16: EQOpc = X86ISD::PCMPEQW; GTOpc = X86ISD::PCMPGTW; break;
8542  case MVT::v4i32: EQOpc = X86ISD::PCMPEQD; GTOpc = X86ISD::PCMPGTD; break;
8543  case MVT::v2i64: EQOpc = X86ISD::PCMPEQQ; GTOpc = X86ISD::PCMPGTQ; break;
8544  }
8545
8546  switch (SetCCOpcode) {
8547  default: break;
8548  case ISD::SETNE:  Invert = true;
8549  case ISD::SETEQ:  Opc = EQOpc; break;
8550  case ISD::SETLT:  Swap = true;
8551  case ISD::SETGT:  Opc = GTOpc; break;
8552  case ISD::SETGE:  Swap = true;
8553  case ISD::SETLE:  Opc = GTOpc; Invert = true; break;
8554  case ISD::SETULT: Swap = true;
8555  case ISD::SETUGT: Opc = GTOpc; FlipSigns = true; break;
8556  case ISD::SETUGE: Swap = true;
8557  case ISD::SETULE: Opc = GTOpc; FlipSigns = true; Invert = true; break;
8558  }
8559  if (Swap)
8560    std::swap(Op0, Op1);
8561
8562  // Check that the operation in question is available (most are plain SSE2,
8563  // but PCMPGTQ and PCMPEQQ have different requirements).
8564  if (Opc == X86ISD::PCMPGTQ && !Subtarget->hasSSE42() && !Subtarget->hasAVX())
8565    return SDValue();
8566  if (Opc == X86ISD::PCMPEQQ && !Subtarget->hasSSE41() && !Subtarget->hasAVX())
8567    return SDValue();
8568
8569  // Since SSE has no unsigned integer comparisons, we need to flip  the sign
8570  // bits of the inputs before performing those operations.
8571  if (FlipSigns) {
8572    EVT EltVT = VT.getVectorElementType();
8573    SDValue SignBit = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()),
8574                                      EltVT);
8575    std::vector<SDValue> SignBits(VT.getVectorNumElements(), SignBit);
8576    SDValue SignVec = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &SignBits[0],
8577                                    SignBits.size());
8578    Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SignVec);
8579    Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SignVec);
8580  }
8581
8582  SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
8583
8584  // If the logical-not of the result is required, perform that now.
8585  if (Invert)
8586    Result = DAG.getNOT(dl, Result, VT);
8587
8588  return Result;
8589}
8590
8591// isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
8592static bool isX86LogicalCmp(SDValue Op) {
8593  unsigned Opc = Op.getNode()->getOpcode();
8594  if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI)
8595    return true;
8596  if (Op.getResNo() == 1 &&
8597      (Opc == X86ISD::ADD ||
8598       Opc == X86ISD::SUB ||
8599       Opc == X86ISD::ADC ||
8600       Opc == X86ISD::SBB ||
8601       Opc == X86ISD::SMUL ||
8602       Opc == X86ISD::UMUL ||
8603       Opc == X86ISD::INC ||
8604       Opc == X86ISD::DEC ||
8605       Opc == X86ISD::OR ||
8606       Opc == X86ISD::XOR ||
8607       Opc == X86ISD::AND))
8608    return true;
8609
8610  if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
8611    return true;
8612
8613  return false;
8614}
8615
8616static bool isZero(SDValue V) {
8617  ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
8618  return C && C->isNullValue();
8619}
8620
8621static bool isAllOnes(SDValue V) {
8622  ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
8623  return C && C->isAllOnesValue();
8624}
8625
8626SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
8627  bool addTest = true;
8628  SDValue Cond  = Op.getOperand(0);
8629  SDValue Op1 = Op.getOperand(1);
8630  SDValue Op2 = Op.getOperand(2);
8631  DebugLoc DL = Op.getDebugLoc();
8632  SDValue CC;
8633
8634  if (Cond.getOpcode() == ISD::SETCC) {
8635    SDValue NewCond = LowerSETCC(Cond, DAG);
8636    if (NewCond.getNode())
8637      Cond = NewCond;
8638  }
8639
8640  // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
8641  // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
8642  // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
8643  // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
8644  if (Cond.getOpcode() == X86ISD::SETCC &&
8645      Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
8646      isZero(Cond.getOperand(1).getOperand(1))) {
8647    SDValue Cmp = Cond.getOperand(1);
8648
8649    unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
8650
8651    if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
8652        (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
8653      SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
8654
8655      SDValue CmpOp0 = Cmp.getOperand(0);
8656      Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
8657                        CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
8658
8659      SDValue Res =   // Res = 0 or -1.
8660        DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
8661                    DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
8662
8663      if (isAllOnes(Op1) != (CondCode == X86::COND_E))
8664        Res = DAG.getNOT(DL, Res, Res.getValueType());
8665
8666      ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
8667      if (N2C == 0 || !N2C->isNullValue())
8668        Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
8669      return Res;
8670    }
8671  }
8672
8673  // Look past (and (setcc_carry (cmp ...)), 1).
8674  if (Cond.getOpcode() == ISD::AND &&
8675      Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
8676    ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
8677    if (C && C->getAPIntValue() == 1)
8678      Cond = Cond.getOperand(0);
8679  }
8680
8681  // If condition flag is set by a X86ISD::CMP, then use it as the condition
8682  // setting operand in place of the X86ISD::SETCC.
8683  if (Cond.getOpcode() == X86ISD::SETCC ||
8684      Cond.getOpcode() == X86ISD::SETCC_CARRY) {
8685    CC = Cond.getOperand(0);
8686
8687    SDValue Cmp = Cond.getOperand(1);
8688    unsigned Opc = Cmp.getOpcode();
8689    EVT VT = Op.getValueType();
8690
8691    bool IllegalFPCMov = false;
8692    if (VT.isFloatingPoint() && !VT.isVector() &&
8693        !isScalarFPTypeInSSEReg(VT))  // FPStack?
8694      IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
8695
8696    if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
8697        Opc == X86ISD::BT) { // FIXME
8698      Cond = Cmp;
8699      addTest = false;
8700    }
8701  }
8702
8703  if (addTest) {
8704    // Look pass the truncate.
8705    if (Cond.getOpcode() == ISD::TRUNCATE)
8706      Cond = Cond.getOperand(0);
8707
8708    // We know the result of AND is compared against zero. Try to match
8709    // it to BT.
8710    if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
8711      SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
8712      if (NewSetCC.getNode()) {
8713        CC = NewSetCC.getOperand(0);
8714        Cond = NewSetCC.getOperand(1);
8715        addTest = false;
8716      }
8717    }
8718  }
8719
8720  if (addTest) {
8721    CC = DAG.getConstant(X86::COND_NE, MVT::i8);
8722    Cond = EmitTest(Cond, X86::COND_NE, DAG);
8723  }
8724
8725  // a <  b ? -1 :  0 -> RES = ~setcc_carry
8726  // a <  b ?  0 : -1 -> RES = setcc_carry
8727  // a >= b ? -1 :  0 -> RES = setcc_carry
8728  // a >= b ?  0 : -1 -> RES = ~setcc_carry
8729  if (Cond.getOpcode() == X86ISD::CMP) {
8730    unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
8731
8732    if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
8733        (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
8734      SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
8735                                DAG.getConstant(X86::COND_B, MVT::i8), Cond);
8736      if (isAllOnes(Op1) != (CondCode == X86::COND_B))
8737        return DAG.getNOT(DL, Res, Res.getValueType());
8738      return Res;
8739    }
8740  }
8741
8742  // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
8743  // condition is true.
8744  SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
8745  SDValue Ops[] = { Op2, Op1, CC, Cond };
8746  return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops, array_lengthof(Ops));
8747}
8748
8749// isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
8750// ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
8751// from the AND / OR.
8752static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
8753  Opc = Op.getOpcode();
8754  if (Opc != ISD::OR && Opc != ISD::AND)
8755    return false;
8756  return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
8757          Op.getOperand(0).hasOneUse() &&
8758          Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
8759          Op.getOperand(1).hasOneUse());
8760}
8761
8762// isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
8763// 1 and that the SETCC node has a single use.
8764static bool isXor1OfSetCC(SDValue Op) {
8765  if (Op.getOpcode() != ISD::XOR)
8766    return false;
8767  ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
8768  if (N1C && N1C->getAPIntValue() == 1) {
8769    return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
8770      Op.getOperand(0).hasOneUse();
8771  }
8772  return false;
8773}
8774
8775SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
8776  bool addTest = true;
8777  SDValue Chain = Op.getOperand(0);
8778  SDValue Cond  = Op.getOperand(1);
8779  SDValue Dest  = Op.getOperand(2);
8780  DebugLoc dl = Op.getDebugLoc();
8781  SDValue CC;
8782
8783  if (Cond.getOpcode() == ISD::SETCC) {
8784    SDValue NewCond = LowerSETCC(Cond, DAG);
8785    if (NewCond.getNode())
8786      Cond = NewCond;
8787  }
8788#if 0
8789  // FIXME: LowerXALUO doesn't handle these!!
8790  else if (Cond.getOpcode() == X86ISD::ADD  ||
8791           Cond.getOpcode() == X86ISD::SUB  ||
8792           Cond.getOpcode() == X86ISD::SMUL ||
8793           Cond.getOpcode() == X86ISD::UMUL)
8794    Cond = LowerXALUO(Cond, DAG);
8795#endif
8796
8797  // Look pass (and (setcc_carry (cmp ...)), 1).
8798  if (Cond.getOpcode() == ISD::AND &&
8799      Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
8800    ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
8801    if (C && C->getAPIntValue() == 1)
8802      Cond = Cond.getOperand(0);
8803  }
8804
8805  // If condition flag is set by a X86ISD::CMP, then use it as the condition
8806  // setting operand in place of the X86ISD::SETCC.
8807  if (Cond.getOpcode() == X86ISD::SETCC ||
8808      Cond.getOpcode() == X86ISD::SETCC_CARRY) {
8809    CC = Cond.getOperand(0);
8810
8811    SDValue Cmp = Cond.getOperand(1);
8812    unsigned Opc = Cmp.getOpcode();
8813    // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
8814    if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
8815      Cond = Cmp;
8816      addTest = false;
8817    } else {
8818      switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
8819      default: break;
8820      case X86::COND_O:
8821      case X86::COND_B:
8822        // These can only come from an arithmetic instruction with overflow,
8823        // e.g. SADDO, UADDO.
8824        Cond = Cond.getNode()->getOperand(1);
8825        addTest = false;
8826        break;
8827      }
8828    }
8829  } else {
8830    unsigned CondOpc;
8831    if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
8832      SDValue Cmp = Cond.getOperand(0).getOperand(1);
8833      if (CondOpc == ISD::OR) {
8834        // Also, recognize the pattern generated by an FCMP_UNE. We can emit
8835        // two branches instead of an explicit OR instruction with a
8836        // separate test.
8837        if (Cmp == Cond.getOperand(1).getOperand(1) &&
8838            isX86LogicalCmp(Cmp)) {
8839          CC = Cond.getOperand(0).getOperand(0);
8840          Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
8841                              Chain, Dest, CC, Cmp);
8842          CC = Cond.getOperand(1).getOperand(0);
8843          Cond = Cmp;
8844          addTest = false;
8845        }
8846      } else { // ISD::AND
8847        // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
8848        // two branches instead of an explicit AND instruction with a
8849        // separate test. However, we only do this if this block doesn't
8850        // have a fall-through edge, because this requires an explicit
8851        // jmp when the condition is false.
8852        if (Cmp == Cond.getOperand(1).getOperand(1) &&
8853            isX86LogicalCmp(Cmp) &&
8854            Op.getNode()->hasOneUse()) {
8855          X86::CondCode CCode =
8856            (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
8857          CCode = X86::GetOppositeBranchCondition(CCode);
8858          CC = DAG.getConstant(CCode, MVT::i8);
8859          SDNode *User = *Op.getNode()->use_begin();
8860          // Look for an unconditional branch following this conditional branch.
8861          // We need this because we need to reverse the successors in order
8862          // to implement FCMP_OEQ.
8863          if (User->getOpcode() == ISD::BR) {
8864            SDValue FalseBB = User->getOperand(1);
8865            SDNode *NewBR =
8866              DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
8867            assert(NewBR == User);
8868            (void)NewBR;
8869            Dest = FalseBB;
8870
8871            Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
8872                                Chain, Dest, CC, Cmp);
8873            X86::CondCode CCode =
8874              (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
8875            CCode = X86::GetOppositeBranchCondition(CCode);
8876            CC = DAG.getConstant(CCode, MVT::i8);
8877            Cond = Cmp;
8878            addTest = false;
8879          }
8880        }
8881      }
8882    } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
8883      // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
8884      // It should be transformed during dag combiner except when the condition
8885      // is set by a arithmetics with overflow node.
8886      X86::CondCode CCode =
8887        (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
8888      CCode = X86::GetOppositeBranchCondition(CCode);
8889      CC = DAG.getConstant(CCode, MVT::i8);
8890      Cond = Cond.getOperand(0).getOperand(1);
8891      addTest = false;
8892    }
8893  }
8894
8895  if (addTest) {
8896    // Look pass the truncate.
8897    if (Cond.getOpcode() == ISD::TRUNCATE)
8898      Cond = Cond.getOperand(0);
8899
8900    // We know the result of AND is compared against zero. Try to match
8901    // it to BT.
8902    if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
8903      SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
8904      if (NewSetCC.getNode()) {
8905        CC = NewSetCC.getOperand(0);
8906        Cond = NewSetCC.getOperand(1);
8907        addTest = false;
8908      }
8909    }
8910  }
8911
8912  if (addTest) {
8913    CC = DAG.getConstant(X86::COND_NE, MVT::i8);
8914    Cond = EmitTest(Cond, X86::COND_NE, DAG);
8915  }
8916  return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
8917                     Chain, Dest, CC, Cond);
8918}
8919
8920
8921// Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
8922// Calls to _alloca is needed to probe the stack when allocating more than 4k
8923// bytes in one go. Touching the stack at 4K increments is necessary to ensure
8924// that the guard pages used by the OS virtual memory manager are allocated in
8925// correct sequence.
8926SDValue
8927X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
8928                                           SelectionDAG &DAG) const {
8929  assert((Subtarget->isTargetCygMing() || Subtarget->isTargetWindows() ||
8930          EnableSegmentedStacks) &&
8931         "This should be used only on Windows targets or when segmented stacks "
8932         "are being used");
8933  assert(!Subtarget->isTargetEnvMacho() && "Not implemented");
8934  DebugLoc dl = Op.getDebugLoc();
8935
8936  // Get the inputs.
8937  SDValue Chain = Op.getOperand(0);
8938  SDValue Size  = Op.getOperand(1);
8939  // FIXME: Ensure alignment here
8940
8941  bool Is64Bit = Subtarget->is64Bit();
8942  EVT SPTy = Is64Bit ? MVT::i64 : MVT::i32;
8943
8944  if (EnableSegmentedStacks) {
8945    MachineFunction &MF = DAG.getMachineFunction();
8946    MachineRegisterInfo &MRI = MF.getRegInfo();
8947
8948    if (Is64Bit) {
8949      // The 64 bit implementation of segmented stacks needs to clobber both r10
8950      // r11. This makes it impossible to use it along with nested parameters.
8951      const Function *F = MF.getFunction();
8952
8953      for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
8954           I != E; I++)
8955        if (I->hasNestAttr())
8956          report_fatal_error("Cannot use segmented stacks with functions that "
8957                             "have nested arguments.");
8958    }
8959
8960    const TargetRegisterClass *AddrRegClass =
8961      getRegClassFor(Subtarget->is64Bit() ? MVT::i64:MVT::i32);
8962    unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
8963    Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
8964    SDValue Value = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
8965                                DAG.getRegister(Vreg, SPTy));
8966    SDValue Ops1[2] = { Value, Chain };
8967    return DAG.getMergeValues(Ops1, 2, dl);
8968  } else {
8969    SDValue Flag;
8970    unsigned Reg = (Subtarget->is64Bit() ? X86::RAX : X86::EAX);
8971
8972    Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
8973    Flag = Chain.getValue(1);
8974    SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
8975
8976    Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
8977    Flag = Chain.getValue(1);
8978
8979    Chain = DAG.getCopyFromReg(Chain, dl, X86StackPtr, SPTy).getValue(1);
8980
8981    SDValue Ops1[2] = { Chain.getValue(0), Chain };
8982    return DAG.getMergeValues(Ops1, 2, dl);
8983  }
8984}
8985
8986SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
8987  MachineFunction &MF = DAG.getMachineFunction();
8988  X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
8989
8990  const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
8991  DebugLoc DL = Op.getDebugLoc();
8992
8993  if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
8994    // vastart just stores the address of the VarArgsFrameIndex slot into the
8995    // memory location argument.
8996    SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
8997                                   getPointerTy());
8998    return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
8999                        MachinePointerInfo(SV), false, false, 0);
9000  }
9001
9002  // __va_list_tag:
9003  //   gp_offset         (0 - 6 * 8)
9004  //   fp_offset         (48 - 48 + 8 * 16)
9005  //   overflow_arg_area (point to parameters coming in memory).
9006  //   reg_save_area
9007  SmallVector<SDValue, 8> MemOps;
9008  SDValue FIN = Op.getOperand(1);
9009  // Store gp_offset
9010  SDValue Store = DAG.getStore(Op.getOperand(0), DL,
9011                               DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
9012                                               MVT::i32),
9013                               FIN, MachinePointerInfo(SV), false, false, 0);
9014  MemOps.push_back(Store);
9015
9016  // Store fp_offset
9017  FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
9018                    FIN, DAG.getIntPtrConstant(4));
9019  Store = DAG.getStore(Op.getOperand(0), DL,
9020                       DAG.getConstant(FuncInfo->getVarArgsFPOffset(),
9021                                       MVT::i32),
9022                       FIN, MachinePointerInfo(SV, 4), false, false, 0);
9023  MemOps.push_back(Store);
9024
9025  // Store ptr to overflow_arg_area
9026  FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
9027                    FIN, DAG.getIntPtrConstant(4));
9028  SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
9029                                    getPointerTy());
9030  Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
9031                       MachinePointerInfo(SV, 8),
9032                       false, false, 0);
9033  MemOps.push_back(Store);
9034
9035  // Store ptr to reg_save_area.
9036  FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
9037                    FIN, DAG.getIntPtrConstant(8));
9038  SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
9039                                    getPointerTy());
9040  Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
9041                       MachinePointerInfo(SV, 16), false, false, 0);
9042  MemOps.push_back(Store);
9043  return DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
9044                     &MemOps[0], MemOps.size());
9045}
9046
9047SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
9048  assert(Subtarget->is64Bit() &&
9049         "LowerVAARG only handles 64-bit va_arg!");
9050  assert((Subtarget->isTargetLinux() ||
9051          Subtarget->isTargetDarwin()) &&
9052          "Unhandled target in LowerVAARG");
9053  assert(Op.getNode()->getNumOperands() == 4);
9054  SDValue Chain = Op.getOperand(0);
9055  SDValue SrcPtr = Op.getOperand(1);
9056  const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
9057  unsigned Align = Op.getConstantOperandVal(3);
9058  DebugLoc dl = Op.getDebugLoc();
9059
9060  EVT ArgVT = Op.getNode()->getValueType(0);
9061  Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
9062  uint32_t ArgSize = getTargetData()->getTypeAllocSize(ArgTy);
9063  uint8_t ArgMode;
9064
9065  // Decide which area this value should be read from.
9066  // TODO: Implement the AMD64 ABI in its entirety. This simple
9067  // selection mechanism works only for the basic types.
9068  if (ArgVT == MVT::f80) {
9069    llvm_unreachable("va_arg for f80 not yet implemented");
9070  } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
9071    ArgMode = 2;  // Argument passed in XMM register. Use fp_offset.
9072  } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
9073    ArgMode = 1;  // Argument passed in GPR64 register(s). Use gp_offset.
9074  } else {
9075    llvm_unreachable("Unhandled argument type in LowerVAARG");
9076  }
9077
9078  if (ArgMode == 2) {
9079    // Sanity Check: Make sure using fp_offset makes sense.
9080    assert(!UseSoftFloat &&
9081           !(DAG.getMachineFunction()
9082                .getFunction()->hasFnAttr(Attribute::NoImplicitFloat)) &&
9083           Subtarget->hasXMM());
9084  }
9085
9086  // Insert VAARG_64 node into the DAG
9087  // VAARG_64 returns two values: Variable Argument Address, Chain
9088  SmallVector<SDValue, 11> InstOps;
9089  InstOps.push_back(Chain);
9090  InstOps.push_back(SrcPtr);
9091  InstOps.push_back(DAG.getConstant(ArgSize, MVT::i32));
9092  InstOps.push_back(DAG.getConstant(ArgMode, MVT::i8));
9093  InstOps.push_back(DAG.getConstant(Align, MVT::i32));
9094  SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other);
9095  SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
9096                                          VTs, &InstOps[0], InstOps.size(),
9097                                          MVT::i64,
9098                                          MachinePointerInfo(SV),
9099                                          /*Align=*/0,
9100                                          /*Volatile=*/false,
9101                                          /*ReadMem=*/true,
9102                                          /*WriteMem=*/true);
9103  Chain = VAARG.getValue(1);
9104
9105  // Load the next argument and return it
9106  return DAG.getLoad(ArgVT, dl,
9107                     Chain,
9108                     VAARG,
9109                     MachinePointerInfo(),
9110                     false, false, 0);
9111}
9112
9113SDValue X86TargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) const {
9114  // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
9115  assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
9116  SDValue Chain = Op.getOperand(0);
9117  SDValue DstPtr = Op.getOperand(1);
9118  SDValue SrcPtr = Op.getOperand(2);
9119  const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
9120  const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
9121  DebugLoc DL = Op.getDebugLoc();
9122
9123  return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
9124                       DAG.getIntPtrConstant(24), 8, /*isVolatile*/false,
9125                       false,
9126                       MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
9127}
9128
9129SDValue
9130X86TargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) const {
9131  DebugLoc dl = Op.getDebugLoc();
9132  unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9133  switch (IntNo) {
9134  default: return SDValue();    // Don't custom lower most intrinsics.
9135  // Comparison intrinsics.
9136  case Intrinsic::x86_sse_comieq_ss:
9137  case Intrinsic::x86_sse_comilt_ss:
9138  case Intrinsic::x86_sse_comile_ss:
9139  case Intrinsic::x86_sse_comigt_ss:
9140  case Intrinsic::x86_sse_comige_ss:
9141  case Intrinsic::x86_sse_comineq_ss:
9142  case Intrinsic::x86_sse_ucomieq_ss:
9143  case Intrinsic::x86_sse_ucomilt_ss:
9144  case Intrinsic::x86_sse_ucomile_ss:
9145  case Intrinsic::x86_sse_ucomigt_ss:
9146  case Intrinsic::x86_sse_ucomige_ss:
9147  case Intrinsic::x86_sse_ucomineq_ss:
9148  case Intrinsic::x86_sse2_comieq_sd:
9149  case Intrinsic::x86_sse2_comilt_sd:
9150  case Intrinsic::x86_sse2_comile_sd:
9151  case Intrinsic::x86_sse2_comigt_sd:
9152  case Intrinsic::x86_sse2_comige_sd:
9153  case Intrinsic::x86_sse2_comineq_sd:
9154  case Intrinsic::x86_sse2_ucomieq_sd:
9155  case Intrinsic::x86_sse2_ucomilt_sd:
9156  case Intrinsic::x86_sse2_ucomile_sd:
9157  case Intrinsic::x86_sse2_ucomigt_sd:
9158  case Intrinsic::x86_sse2_ucomige_sd:
9159  case Intrinsic::x86_sse2_ucomineq_sd: {
9160    unsigned Opc = 0;
9161    ISD::CondCode CC = ISD::SETCC_INVALID;
9162    switch (IntNo) {
9163    default: break;
9164    case Intrinsic::x86_sse_comieq_ss:
9165    case Intrinsic::x86_sse2_comieq_sd:
9166      Opc = X86ISD::COMI;
9167      CC = ISD::SETEQ;
9168      break;
9169    case Intrinsic::x86_sse_comilt_ss:
9170    case Intrinsic::x86_sse2_comilt_sd:
9171      Opc = X86ISD::COMI;
9172      CC = ISD::SETLT;
9173      break;
9174    case Intrinsic::x86_sse_comile_ss:
9175    case Intrinsic::x86_sse2_comile_sd:
9176      Opc = X86ISD::COMI;
9177      CC = ISD::SETLE;
9178      break;
9179    case Intrinsic::x86_sse_comigt_ss:
9180    case Intrinsic::x86_sse2_comigt_sd:
9181      Opc = X86ISD::COMI;
9182      CC = ISD::SETGT;
9183      break;
9184    case Intrinsic::x86_sse_comige_ss:
9185    case Intrinsic::x86_sse2_comige_sd:
9186      Opc = X86ISD::COMI;
9187      CC = ISD::SETGE;
9188      break;
9189    case Intrinsic::x86_sse_comineq_ss:
9190    case Intrinsic::x86_sse2_comineq_sd:
9191      Opc = X86ISD::COMI;
9192      CC = ISD::SETNE;
9193      break;
9194    case Intrinsic::x86_sse_ucomieq_ss:
9195    case Intrinsic::x86_sse2_ucomieq_sd:
9196      Opc = X86ISD::UCOMI;
9197      CC = ISD::SETEQ;
9198      break;
9199    case Intrinsic::x86_sse_ucomilt_ss:
9200    case Intrinsic::x86_sse2_ucomilt_sd:
9201      Opc = X86ISD::UCOMI;
9202      CC = ISD::SETLT;
9203      break;
9204    case Intrinsic::x86_sse_ucomile_ss:
9205    case Intrinsic::x86_sse2_ucomile_sd:
9206      Opc = X86ISD::UCOMI;
9207      CC = ISD::SETLE;
9208      break;
9209    case Intrinsic::x86_sse_ucomigt_ss:
9210    case Intrinsic::x86_sse2_ucomigt_sd:
9211      Opc = X86ISD::UCOMI;
9212      CC = ISD::SETGT;
9213      break;
9214    case Intrinsic::x86_sse_ucomige_ss:
9215    case Intrinsic::x86_sse2_ucomige_sd:
9216      Opc = X86ISD::UCOMI;
9217      CC = ISD::SETGE;
9218      break;
9219    case Intrinsic::x86_sse_ucomineq_ss:
9220    case Intrinsic::x86_sse2_ucomineq_sd:
9221      Opc = X86ISD::UCOMI;
9222      CC = ISD::SETNE;
9223      break;
9224    }
9225
9226    SDValue LHS = Op.getOperand(1);
9227    SDValue RHS = Op.getOperand(2);
9228    unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
9229    assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
9230    SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS);
9231    SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
9232                                DAG.getConstant(X86CC, MVT::i8), Cond);
9233    return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
9234  }
9235  // Arithmetic intrinsics.
9236  case Intrinsic::x86_sse3_hadd_ps:
9237  case Intrinsic::x86_sse3_hadd_pd:
9238  case Intrinsic::x86_avx_hadd_ps_256:
9239  case Intrinsic::x86_avx_hadd_pd_256:
9240    return DAG.getNode(X86ISD::FHADD, dl, Op.getValueType(),
9241                       Op.getOperand(1), Op.getOperand(2));
9242  case Intrinsic::x86_sse3_hsub_ps:
9243  case Intrinsic::x86_sse3_hsub_pd:
9244  case Intrinsic::x86_avx_hsub_ps_256:
9245  case Intrinsic::x86_avx_hsub_pd_256:
9246    return DAG.getNode(X86ISD::FHSUB, dl, Op.getValueType(),
9247                       Op.getOperand(1), Op.getOperand(2));
9248  // ptest and testp intrinsics. The intrinsic these come from are designed to
9249  // return an integer value, not just an instruction so lower it to the ptest
9250  // or testp pattern and a setcc for the result.
9251  case Intrinsic::x86_sse41_ptestz:
9252  case Intrinsic::x86_sse41_ptestc:
9253  case Intrinsic::x86_sse41_ptestnzc:
9254  case Intrinsic::x86_avx_ptestz_256:
9255  case Intrinsic::x86_avx_ptestc_256:
9256  case Intrinsic::x86_avx_ptestnzc_256:
9257  case Intrinsic::x86_avx_vtestz_ps:
9258  case Intrinsic::x86_avx_vtestc_ps:
9259  case Intrinsic::x86_avx_vtestnzc_ps:
9260  case Intrinsic::x86_avx_vtestz_pd:
9261  case Intrinsic::x86_avx_vtestc_pd:
9262  case Intrinsic::x86_avx_vtestnzc_pd:
9263  case Intrinsic::x86_avx_vtestz_ps_256:
9264  case Intrinsic::x86_avx_vtestc_ps_256:
9265  case Intrinsic::x86_avx_vtestnzc_ps_256:
9266  case Intrinsic::x86_avx_vtestz_pd_256:
9267  case Intrinsic::x86_avx_vtestc_pd_256:
9268  case Intrinsic::x86_avx_vtestnzc_pd_256: {
9269    bool IsTestPacked = false;
9270    unsigned X86CC = 0;
9271    switch (IntNo) {
9272    default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
9273    case Intrinsic::x86_avx_vtestz_ps:
9274    case Intrinsic::x86_avx_vtestz_pd:
9275    case Intrinsic::x86_avx_vtestz_ps_256:
9276    case Intrinsic::x86_avx_vtestz_pd_256:
9277      IsTestPacked = true; // Fallthrough
9278    case Intrinsic::x86_sse41_ptestz:
9279    case Intrinsic::x86_avx_ptestz_256:
9280      // ZF = 1
9281      X86CC = X86::COND_E;
9282      break;
9283    case Intrinsic::x86_avx_vtestc_ps:
9284    case Intrinsic::x86_avx_vtestc_pd:
9285    case Intrinsic::x86_avx_vtestc_ps_256:
9286    case Intrinsic::x86_avx_vtestc_pd_256:
9287      IsTestPacked = true; // Fallthrough
9288    case Intrinsic::x86_sse41_ptestc:
9289    case Intrinsic::x86_avx_ptestc_256:
9290      // CF = 1
9291      X86CC = X86::COND_B;
9292      break;
9293    case Intrinsic::x86_avx_vtestnzc_ps:
9294    case Intrinsic::x86_avx_vtestnzc_pd:
9295    case Intrinsic::x86_avx_vtestnzc_ps_256:
9296    case Intrinsic::x86_avx_vtestnzc_pd_256:
9297      IsTestPacked = true; // Fallthrough
9298    case Intrinsic::x86_sse41_ptestnzc:
9299    case Intrinsic::x86_avx_ptestnzc_256:
9300      // ZF and CF = 0
9301      X86CC = X86::COND_A;
9302      break;
9303    }
9304
9305    SDValue LHS = Op.getOperand(1);
9306    SDValue RHS = Op.getOperand(2);
9307    unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
9308    SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
9309    SDValue CC = DAG.getConstant(X86CC, MVT::i8);
9310    SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
9311    return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
9312  }
9313
9314  // Fix vector shift instructions where the last operand is a non-immediate
9315  // i32 value.
9316  case Intrinsic::x86_sse2_pslli_w:
9317  case Intrinsic::x86_sse2_pslli_d:
9318  case Intrinsic::x86_sse2_pslli_q:
9319  case Intrinsic::x86_sse2_psrli_w:
9320  case Intrinsic::x86_sse2_psrli_d:
9321  case Intrinsic::x86_sse2_psrli_q:
9322  case Intrinsic::x86_sse2_psrai_w:
9323  case Intrinsic::x86_sse2_psrai_d:
9324  case Intrinsic::x86_mmx_pslli_w:
9325  case Intrinsic::x86_mmx_pslli_d:
9326  case Intrinsic::x86_mmx_pslli_q:
9327  case Intrinsic::x86_mmx_psrli_w:
9328  case Intrinsic::x86_mmx_psrli_d:
9329  case Intrinsic::x86_mmx_psrli_q:
9330  case Intrinsic::x86_mmx_psrai_w:
9331  case Intrinsic::x86_mmx_psrai_d: {
9332    SDValue ShAmt = Op.getOperand(2);
9333    if (isa<ConstantSDNode>(ShAmt))
9334      return SDValue();
9335
9336    unsigned NewIntNo = 0;
9337    EVT ShAmtVT = MVT::v4i32;
9338    switch (IntNo) {
9339    case Intrinsic::x86_sse2_pslli_w:
9340      NewIntNo = Intrinsic::x86_sse2_psll_w;
9341      break;
9342    case Intrinsic::x86_sse2_pslli_d:
9343      NewIntNo = Intrinsic::x86_sse2_psll_d;
9344      break;
9345    case Intrinsic::x86_sse2_pslli_q:
9346      NewIntNo = Intrinsic::x86_sse2_psll_q;
9347      break;
9348    case Intrinsic::x86_sse2_psrli_w:
9349      NewIntNo = Intrinsic::x86_sse2_psrl_w;
9350      break;
9351    case Intrinsic::x86_sse2_psrli_d:
9352      NewIntNo = Intrinsic::x86_sse2_psrl_d;
9353      break;
9354    case Intrinsic::x86_sse2_psrli_q:
9355      NewIntNo = Intrinsic::x86_sse2_psrl_q;
9356      break;
9357    case Intrinsic::x86_sse2_psrai_w:
9358      NewIntNo = Intrinsic::x86_sse2_psra_w;
9359      break;
9360    case Intrinsic::x86_sse2_psrai_d:
9361      NewIntNo = Intrinsic::x86_sse2_psra_d;
9362      break;
9363    default: {
9364      ShAmtVT = MVT::v2i32;
9365      switch (IntNo) {
9366      case Intrinsic::x86_mmx_pslli_w:
9367        NewIntNo = Intrinsic::x86_mmx_psll_w;
9368        break;
9369      case Intrinsic::x86_mmx_pslli_d:
9370        NewIntNo = Intrinsic::x86_mmx_psll_d;
9371        break;
9372      case Intrinsic::x86_mmx_pslli_q:
9373        NewIntNo = Intrinsic::x86_mmx_psll_q;
9374        break;
9375      case Intrinsic::x86_mmx_psrli_w:
9376        NewIntNo = Intrinsic::x86_mmx_psrl_w;
9377        break;
9378      case Intrinsic::x86_mmx_psrli_d:
9379        NewIntNo = Intrinsic::x86_mmx_psrl_d;
9380        break;
9381      case Intrinsic::x86_mmx_psrli_q:
9382        NewIntNo = Intrinsic::x86_mmx_psrl_q;
9383        break;
9384      case Intrinsic::x86_mmx_psrai_w:
9385        NewIntNo = Intrinsic::x86_mmx_psra_w;
9386        break;
9387      case Intrinsic::x86_mmx_psrai_d:
9388        NewIntNo = Intrinsic::x86_mmx_psra_d;
9389        break;
9390      default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
9391      }
9392      break;
9393    }
9394    }
9395
9396    // The vector shift intrinsics with scalars uses 32b shift amounts but
9397    // the sse2/mmx shift instructions reads 64 bits. Set the upper 32 bits
9398    // to be zero.
9399    SDValue ShOps[4];
9400    ShOps[0] = ShAmt;
9401    ShOps[1] = DAG.getConstant(0, MVT::i32);
9402    if (ShAmtVT == MVT::v4i32) {
9403      ShOps[2] = DAG.getUNDEF(MVT::i32);
9404      ShOps[3] = DAG.getUNDEF(MVT::i32);
9405      ShAmt =  DAG.getNode(ISD::BUILD_VECTOR, dl, ShAmtVT, &ShOps[0], 4);
9406    } else {
9407      ShAmt =  DAG.getNode(ISD::BUILD_VECTOR, dl, ShAmtVT, &ShOps[0], 2);
9408// FIXME this must be lowered to get rid of the invalid type.
9409    }
9410
9411    EVT VT = Op.getValueType();
9412    ShAmt = DAG.getNode(ISD::BITCAST, dl, VT, ShAmt);
9413    return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9414                       DAG.getConstant(NewIntNo, MVT::i32),
9415                       Op.getOperand(1), ShAmt);
9416  }
9417  }
9418}
9419
9420SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
9421                                           SelectionDAG &DAG) const {
9422  MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
9423  MFI->setReturnAddressIsTaken(true);
9424
9425  unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9426  DebugLoc dl = Op.getDebugLoc();
9427
9428  if (Depth > 0) {
9429    SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
9430    SDValue Offset =
9431      DAG.getConstant(TD->getPointerSize(),
9432                      Subtarget->is64Bit() ? MVT::i64 : MVT::i32);
9433    return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
9434                       DAG.getNode(ISD::ADD, dl, getPointerTy(),
9435                                   FrameAddr, Offset),
9436                       MachinePointerInfo(), false, false, 0);
9437  }
9438
9439  // Just load the return address.
9440  SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
9441  return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
9442                     RetAddrFI, MachinePointerInfo(), false, false, 0);
9443}
9444
9445SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
9446  MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
9447  MFI->setFrameAddressIsTaken(true);
9448
9449  EVT VT = Op.getValueType();
9450  DebugLoc dl = Op.getDebugLoc();  // FIXME probably not meaningful
9451  unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9452  unsigned FrameReg = Subtarget->is64Bit() ? X86::RBP : X86::EBP;
9453  SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
9454  while (Depth--)
9455    FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
9456                            MachinePointerInfo(),
9457                            false, false, 0);
9458  return FrameAddr;
9459}
9460
9461SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
9462                                                     SelectionDAG &DAG) const {
9463  return DAG.getIntPtrConstant(2*TD->getPointerSize());
9464}
9465
9466SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
9467  MachineFunction &MF = DAG.getMachineFunction();
9468  SDValue Chain     = Op.getOperand(0);
9469  SDValue Offset    = Op.getOperand(1);
9470  SDValue Handler   = Op.getOperand(2);
9471  DebugLoc dl       = Op.getDebugLoc();
9472
9473  SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl,
9474                                     Subtarget->is64Bit() ? X86::RBP : X86::EBP,
9475                                     getPointerTy());
9476  unsigned StoreAddrReg = (Subtarget->is64Bit() ? X86::RCX : X86::ECX);
9477
9478  SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), Frame,
9479                                  DAG.getIntPtrConstant(TD->getPointerSize()));
9480  StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), StoreAddr, Offset);
9481  Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
9482                       false, false, 0);
9483  Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
9484  MF.getRegInfo().addLiveOut(StoreAddrReg);
9485
9486  return DAG.getNode(X86ISD::EH_RETURN, dl,
9487                     MVT::Other,
9488                     Chain, DAG.getRegister(StoreAddrReg, getPointerTy()));
9489}
9490
9491SDValue X86TargetLowering::LowerADJUST_TRAMPOLINE(SDValue Op,
9492                                                  SelectionDAG &DAG) const {
9493  return Op.getOperand(0);
9494}
9495
9496SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
9497                                                SelectionDAG &DAG) const {
9498  SDValue Root = Op.getOperand(0);
9499  SDValue Trmp = Op.getOperand(1); // trampoline
9500  SDValue FPtr = Op.getOperand(2); // nested function
9501  SDValue Nest = Op.getOperand(3); // 'nest' parameter value
9502  DebugLoc dl  = Op.getDebugLoc();
9503
9504  const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
9505
9506  if (Subtarget->is64Bit()) {
9507    SDValue OutChains[6];
9508
9509    // Large code-model.
9510    const unsigned char JMP64r  = 0xFF; // 64-bit jmp through register opcode.
9511    const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
9512
9513    const unsigned char N86R10 = X86_MC::getX86RegNum(X86::R10);
9514    const unsigned char N86R11 = X86_MC::getX86RegNum(X86::R11);
9515
9516    const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
9517
9518    // Load the pointer to the nested function into R11.
9519    unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
9520    SDValue Addr = Trmp;
9521    OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
9522                                Addr, MachinePointerInfo(TrmpAddr),
9523                                false, false, 0);
9524
9525    Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
9526                       DAG.getConstant(2, MVT::i64));
9527    OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
9528                                MachinePointerInfo(TrmpAddr, 2),
9529                                false, false, 2);
9530
9531    // Load the 'nest' parameter value into R10.
9532    // R10 is specified in X86CallingConv.td
9533    OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
9534    Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
9535                       DAG.getConstant(10, MVT::i64));
9536    OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
9537                                Addr, MachinePointerInfo(TrmpAddr, 10),
9538                                false, false, 0);
9539
9540    Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
9541                       DAG.getConstant(12, MVT::i64));
9542    OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
9543                                MachinePointerInfo(TrmpAddr, 12),
9544                                false, false, 2);
9545
9546    // Jump to the nested function.
9547    OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
9548    Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
9549                       DAG.getConstant(20, MVT::i64));
9550    OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
9551                                Addr, MachinePointerInfo(TrmpAddr, 20),
9552                                false, false, 0);
9553
9554    unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
9555    Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
9556                       DAG.getConstant(22, MVT::i64));
9557    OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
9558                                MachinePointerInfo(TrmpAddr, 22),
9559                                false, false, 0);
9560
9561    return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 6);
9562  } else {
9563    const Function *Func =
9564      cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
9565    CallingConv::ID CC = Func->getCallingConv();
9566    unsigned NestReg;
9567
9568    switch (CC) {
9569    default:
9570      llvm_unreachable("Unsupported calling convention");
9571    case CallingConv::C:
9572    case CallingConv::X86_StdCall: {
9573      // Pass 'nest' parameter in ECX.
9574      // Must be kept in sync with X86CallingConv.td
9575      NestReg = X86::ECX;
9576
9577      // Check that ECX wasn't needed by an 'inreg' parameter.
9578      FunctionType *FTy = Func->getFunctionType();
9579      const AttrListPtr &Attrs = Func->getAttributes();
9580
9581      if (!Attrs.isEmpty() && !Func->isVarArg()) {
9582        unsigned InRegCount = 0;
9583        unsigned Idx = 1;
9584
9585        for (FunctionType::param_iterator I = FTy->param_begin(),
9586             E = FTy->param_end(); I != E; ++I, ++Idx)
9587          if (Attrs.paramHasAttr(Idx, Attribute::InReg))
9588            // FIXME: should only count parameters that are lowered to integers.
9589            InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
9590
9591        if (InRegCount > 2) {
9592          report_fatal_error("Nest register in use - reduce number of inreg"
9593                             " parameters!");
9594        }
9595      }
9596      break;
9597    }
9598    case CallingConv::X86_FastCall:
9599    case CallingConv::X86_ThisCall:
9600    case CallingConv::Fast:
9601      // Pass 'nest' parameter in EAX.
9602      // Must be kept in sync with X86CallingConv.td
9603      NestReg = X86::EAX;
9604      break;
9605    }
9606
9607    SDValue OutChains[4];
9608    SDValue Addr, Disp;
9609
9610    Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
9611                       DAG.getConstant(10, MVT::i32));
9612    Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
9613
9614    // This is storing the opcode for MOV32ri.
9615    const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
9616    const unsigned char N86Reg = X86_MC::getX86RegNum(NestReg);
9617    OutChains[0] = DAG.getStore(Root, dl,
9618                                DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
9619                                Trmp, MachinePointerInfo(TrmpAddr),
9620                                false, false, 0);
9621
9622    Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
9623                       DAG.getConstant(1, MVT::i32));
9624    OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
9625                                MachinePointerInfo(TrmpAddr, 1),
9626                                false, false, 1);
9627
9628    const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
9629    Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
9630                       DAG.getConstant(5, MVT::i32));
9631    OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
9632                                MachinePointerInfo(TrmpAddr, 5),
9633                                false, false, 1);
9634
9635    Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
9636                       DAG.getConstant(6, MVT::i32));
9637    OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
9638                                MachinePointerInfo(TrmpAddr, 6),
9639                                false, false, 1);
9640
9641    return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 4);
9642  }
9643}
9644
9645SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
9646                                            SelectionDAG &DAG) const {
9647  /*
9648   The rounding mode is in bits 11:10 of FPSR, and has the following
9649   settings:
9650     00 Round to nearest
9651     01 Round to -inf
9652     10 Round to +inf
9653     11 Round to 0
9654
9655  FLT_ROUNDS, on the other hand, expects the following:
9656    -1 Undefined
9657     0 Round to 0
9658     1 Round to nearest
9659     2 Round to +inf
9660     3 Round to -inf
9661
9662  To perform the conversion, we do:
9663    (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
9664  */
9665
9666  MachineFunction &MF = DAG.getMachineFunction();
9667  const TargetMachine &TM = MF.getTarget();
9668  const TargetFrameLowering &TFI = *TM.getFrameLowering();
9669  unsigned StackAlignment = TFI.getStackAlignment();
9670  EVT VT = Op.getValueType();
9671  DebugLoc DL = Op.getDebugLoc();
9672
9673  // Save FP Control Word to stack slot
9674  int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
9675  SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
9676
9677
9678  MachineMemOperand *MMO =
9679   MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
9680                           MachineMemOperand::MOStore, 2, 2);
9681
9682  SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
9683  SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
9684                                          DAG.getVTList(MVT::Other),
9685                                          Ops, 2, MVT::i16, MMO);
9686
9687  // Load FP Control Word from stack slot
9688  SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
9689                            MachinePointerInfo(), false, false, 0);
9690
9691  // Transform as necessary
9692  SDValue CWD1 =
9693    DAG.getNode(ISD::SRL, DL, MVT::i16,
9694                DAG.getNode(ISD::AND, DL, MVT::i16,
9695                            CWD, DAG.getConstant(0x800, MVT::i16)),
9696                DAG.getConstant(11, MVT::i8));
9697  SDValue CWD2 =
9698    DAG.getNode(ISD::SRL, DL, MVT::i16,
9699                DAG.getNode(ISD::AND, DL, MVT::i16,
9700                            CWD, DAG.getConstant(0x400, MVT::i16)),
9701                DAG.getConstant(9, MVT::i8));
9702
9703  SDValue RetVal =
9704    DAG.getNode(ISD::AND, DL, MVT::i16,
9705                DAG.getNode(ISD::ADD, DL, MVT::i16,
9706                            DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
9707                            DAG.getConstant(1, MVT::i16)),
9708                DAG.getConstant(3, MVT::i16));
9709
9710
9711  return DAG.getNode((VT.getSizeInBits() < 16 ?
9712                      ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
9713}
9714
9715SDValue X86TargetLowering::LowerCTLZ(SDValue Op, SelectionDAG &DAG) const {
9716  EVT VT = Op.getValueType();
9717  EVT OpVT = VT;
9718  unsigned NumBits = VT.getSizeInBits();
9719  DebugLoc dl = Op.getDebugLoc();
9720
9721  Op = Op.getOperand(0);
9722  if (VT == MVT::i8) {
9723    // Zero extend to i32 since there is not an i8 bsr.
9724    OpVT = MVT::i32;
9725    Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
9726  }
9727
9728  // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
9729  SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
9730  Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
9731
9732  // If src is zero (i.e. bsr sets ZF), returns NumBits.
9733  SDValue Ops[] = {
9734    Op,
9735    DAG.getConstant(NumBits+NumBits-1, OpVT),
9736    DAG.getConstant(X86::COND_E, MVT::i8),
9737    Op.getValue(1)
9738  };
9739  Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
9740
9741  // Finally xor with NumBits-1.
9742  Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
9743
9744  if (VT == MVT::i8)
9745    Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
9746  return Op;
9747}
9748
9749SDValue X86TargetLowering::LowerCTTZ(SDValue Op, SelectionDAG &DAG) const {
9750  EVT VT = Op.getValueType();
9751  EVT OpVT = VT;
9752  unsigned NumBits = VT.getSizeInBits();
9753  DebugLoc dl = Op.getDebugLoc();
9754
9755  Op = Op.getOperand(0);
9756  if (VT == MVT::i8) {
9757    OpVT = MVT::i32;
9758    Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
9759  }
9760
9761  // Issue a bsf (scan bits forward) which also sets EFLAGS.
9762  SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
9763  Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
9764
9765  // If src is zero (i.e. bsf sets ZF), returns NumBits.
9766  SDValue Ops[] = {
9767    Op,
9768    DAG.getConstant(NumBits, OpVT),
9769    DAG.getConstant(X86::COND_E, MVT::i8),
9770    Op.getValue(1)
9771  };
9772  Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
9773
9774  if (VT == MVT::i8)
9775    Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
9776  return Op;
9777}
9778
9779// Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
9780// ones, and then concatenate the result back.
9781static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
9782  EVT VT = Op.getValueType();
9783
9784  assert(VT.getSizeInBits() == 256 && VT.isInteger() &&
9785         "Unsupported value type for operation");
9786
9787  int NumElems = VT.getVectorNumElements();
9788  DebugLoc dl = Op.getDebugLoc();
9789  SDValue Idx0 = DAG.getConstant(0, MVT::i32);
9790  SDValue Idx1 = DAG.getConstant(NumElems/2, MVT::i32);
9791
9792  // Extract the LHS vectors
9793  SDValue LHS = Op.getOperand(0);
9794  SDValue LHS1 = Extract128BitVector(LHS, Idx0, DAG, dl);
9795  SDValue LHS2 = Extract128BitVector(LHS, Idx1, DAG, dl);
9796
9797  // Extract the RHS vectors
9798  SDValue RHS = Op.getOperand(1);
9799  SDValue RHS1 = Extract128BitVector(RHS, Idx0, DAG, dl);
9800  SDValue RHS2 = Extract128BitVector(RHS, Idx1, DAG, dl);
9801
9802  MVT EltVT = VT.getVectorElementType().getSimpleVT();
9803  EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
9804
9805  return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
9806                     DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
9807                     DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
9808}
9809
9810SDValue X86TargetLowering::LowerADD(SDValue Op, SelectionDAG &DAG) const {
9811  assert(Op.getValueType().getSizeInBits() == 256 &&
9812         Op.getValueType().isInteger() &&
9813         "Only handle AVX 256-bit vector integer operation");
9814  return Lower256IntArith(Op, DAG);
9815}
9816
9817SDValue X86TargetLowering::LowerSUB(SDValue Op, SelectionDAG &DAG) const {
9818  assert(Op.getValueType().getSizeInBits() == 256 &&
9819         Op.getValueType().isInteger() &&
9820         "Only handle AVX 256-bit vector integer operation");
9821  return Lower256IntArith(Op, DAG);
9822}
9823
9824SDValue X86TargetLowering::LowerMUL(SDValue Op, SelectionDAG &DAG) const {
9825  EVT VT = Op.getValueType();
9826
9827  // Decompose 256-bit ops into smaller 128-bit ops.
9828  if (VT.getSizeInBits() == 256)
9829    return Lower256IntArith(Op, DAG);
9830
9831  assert(VT == MVT::v2i64 && "Only know how to lower V2I64 multiply");
9832  DebugLoc dl = Op.getDebugLoc();
9833
9834  //  ulong2 Ahi = __builtin_ia32_psrlqi128( a, 32);
9835  //  ulong2 Bhi = __builtin_ia32_psrlqi128( b, 32);
9836  //  ulong2 AloBlo = __builtin_ia32_pmuludq128( a, b );
9837  //  ulong2 AloBhi = __builtin_ia32_pmuludq128( a, Bhi );
9838  //  ulong2 AhiBlo = __builtin_ia32_pmuludq128( Ahi, b );
9839  //
9840  //  AloBhi = __builtin_ia32_psllqi128( AloBhi, 32 );
9841  //  AhiBlo = __builtin_ia32_psllqi128( AhiBlo, 32 );
9842  //  return AloBlo + AloBhi + AhiBlo;
9843
9844  SDValue A = Op.getOperand(0);
9845  SDValue B = Op.getOperand(1);
9846
9847  SDValue Ahi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9848                       DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
9849                       A, DAG.getConstant(32, MVT::i32));
9850  SDValue Bhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9851                       DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
9852                       B, DAG.getConstant(32, MVT::i32));
9853  SDValue AloBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9854                       DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
9855                       A, B);
9856  SDValue AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9857                       DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
9858                       A, Bhi);
9859  SDValue AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9860                       DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
9861                       Ahi, B);
9862  AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9863                       DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
9864                       AloBhi, DAG.getConstant(32, MVT::i32));
9865  AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9866                       DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
9867                       AhiBlo, DAG.getConstant(32, MVT::i32));
9868  SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
9869  Res = DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
9870  return Res;
9871}
9872
9873SDValue X86TargetLowering::LowerShift(SDValue Op, SelectionDAG &DAG) const {
9874
9875  EVT VT = Op.getValueType();
9876  DebugLoc dl = Op.getDebugLoc();
9877  SDValue R = Op.getOperand(0);
9878  SDValue Amt = Op.getOperand(1);
9879  LLVMContext *Context = DAG.getContext();
9880
9881  if (!Subtarget->hasXMMInt())
9882    return SDValue();
9883
9884  // Decompose 256-bit shifts into smaller 128-bit shifts.
9885  if (VT.getSizeInBits() == 256) {
9886    int NumElems = VT.getVectorNumElements();
9887    MVT EltVT = VT.getVectorElementType().getSimpleVT();
9888    EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
9889
9890    // Extract the two vectors
9891    SDValue V1 = Extract128BitVector(R, DAG.getConstant(0, MVT::i32), DAG, dl);
9892    SDValue V2 = Extract128BitVector(R, DAG.getConstant(NumElems/2, MVT::i32),
9893                                     DAG, dl);
9894
9895    // Recreate the shift amount vectors
9896    SDValue Amt1, Amt2;
9897    if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
9898      // Constant shift amount
9899      SmallVector<SDValue, 4> Amt1Csts;
9900      SmallVector<SDValue, 4> Amt2Csts;
9901      for (int i = 0; i < NumElems/2; ++i)
9902        Amt1Csts.push_back(Amt->getOperand(i));
9903      for (int i = NumElems/2; i < NumElems; ++i)
9904        Amt2Csts.push_back(Amt->getOperand(i));
9905
9906      Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT,
9907                                 &Amt1Csts[0], NumElems/2);
9908      Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT,
9909                                 &Amt2Csts[0], NumElems/2);
9910    } else {
9911      // Variable shift amount
9912      Amt1 = Extract128BitVector(Amt, DAG.getConstant(0, MVT::i32), DAG, dl);
9913      Amt2 = Extract128BitVector(Amt, DAG.getConstant(NumElems/2, MVT::i32),
9914                                 DAG, dl);
9915    }
9916
9917    // Issue new vector shifts for the smaller types
9918    V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
9919    V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
9920
9921    // Concatenate the result back
9922    return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
9923  }
9924
9925  // Optimize shl/srl/sra with constant shift amount.
9926  if (isSplatVector(Amt.getNode())) {
9927    SDValue SclrAmt = Amt->getOperand(0);
9928    if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt)) {
9929      uint64_t ShiftAmt = C->getZExtValue();
9930
9931      if (VT == MVT::v2i64 && Op.getOpcode() == ISD::SHL)
9932       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9933                     DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
9934                     R, DAG.getConstant(ShiftAmt, MVT::i32));
9935
9936      if (VT == MVT::v4i32 && Op.getOpcode() == ISD::SHL)
9937       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9938                     DAG.getConstant(Intrinsic::x86_sse2_pslli_d, MVT::i32),
9939                     R, DAG.getConstant(ShiftAmt, MVT::i32));
9940
9941      if (VT == MVT::v8i16 && Op.getOpcode() == ISD::SHL)
9942       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9943                     DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32),
9944                     R, DAG.getConstant(ShiftAmt, MVT::i32));
9945
9946      if (VT == MVT::v2i64 && Op.getOpcode() == ISD::SRL)
9947       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9948                     DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
9949                     R, DAG.getConstant(ShiftAmt, MVT::i32));
9950
9951      if (VT == MVT::v4i32 && Op.getOpcode() == ISD::SRL)
9952       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9953                     DAG.getConstant(Intrinsic::x86_sse2_psrli_d, MVT::i32),
9954                     R, DAG.getConstant(ShiftAmt, MVT::i32));
9955
9956      if (VT == MVT::v8i16 && Op.getOpcode() == ISD::SRL)
9957       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9958                     DAG.getConstant(Intrinsic::x86_sse2_psrli_w, MVT::i32),
9959                     R, DAG.getConstant(ShiftAmt, MVT::i32));
9960
9961      if (VT == MVT::v4i32 && Op.getOpcode() == ISD::SRA)
9962       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9963                     DAG.getConstant(Intrinsic::x86_sse2_psrai_d, MVT::i32),
9964                     R, DAG.getConstant(ShiftAmt, MVT::i32));
9965
9966      if (VT == MVT::v8i16 && Op.getOpcode() == ISD::SRA)
9967       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9968                     DAG.getConstant(Intrinsic::x86_sse2_psrai_w, MVT::i32),
9969                     R, DAG.getConstant(ShiftAmt, MVT::i32));
9970    }
9971  }
9972
9973  // Lower SHL with variable shift amount.
9974  if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
9975    Op = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9976                     DAG.getConstant(Intrinsic::x86_sse2_pslli_d, MVT::i32),
9977                     Op.getOperand(1), DAG.getConstant(23, MVT::i32));
9978
9979    ConstantInt *CI = ConstantInt::get(*Context, APInt(32, 0x3f800000U));
9980
9981    std::vector<Constant*> CV(4, CI);
9982    Constant *C = ConstantVector::get(CV);
9983    SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
9984    SDValue Addend = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
9985                                 MachinePointerInfo::getConstantPool(),
9986                                 false, false, 16);
9987
9988    Op = DAG.getNode(ISD::ADD, dl, VT, Op, Addend);
9989    Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, Op);
9990    Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
9991    return DAG.getNode(ISD::MUL, dl, VT, Op, R);
9992  }
9993  if (VT == MVT::v16i8 && Op->getOpcode() == ISD::SHL) {
9994    // a = a << 5;
9995    Op = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9996                     DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32),
9997                     Op.getOperand(1), DAG.getConstant(5, MVT::i32));
9998
9999    ConstantInt *CM1 = ConstantInt::get(*Context, APInt(8, 15));
10000    ConstantInt *CM2 = ConstantInt::get(*Context, APInt(8, 63));
10001
10002    std::vector<Constant*> CVM1(16, CM1);
10003    std::vector<Constant*> CVM2(16, CM2);
10004    Constant *C = ConstantVector::get(CVM1);
10005    SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
10006    SDValue M = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
10007                            MachinePointerInfo::getConstantPool(),
10008                            false, false, 16);
10009
10010    // r = pblendv(r, psllw(r & (char16)15, 4), a);
10011    M = DAG.getNode(ISD::AND, dl, VT, R, M);
10012    M = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10013                    DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32), M,
10014                    DAG.getConstant(4, MVT::i32));
10015    R = DAG.getNode(ISD::VSELECT, dl, VT, Op, R, M);
10016    // a += a
10017    Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
10018
10019    C = ConstantVector::get(CVM2);
10020    CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
10021    M = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
10022                    MachinePointerInfo::getConstantPool(),
10023                    false, false, 16);
10024
10025    // r = pblendv(r, psllw(r & (char16)63, 2), a);
10026    M = DAG.getNode(ISD::AND, dl, VT, R, M);
10027    M = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10028                    DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32), M,
10029                    DAG.getConstant(2, MVT::i32));
10030    R = DAG.getNode(ISD::VSELECT, dl, VT, Op, R, M);
10031    // a += a
10032    Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
10033
10034    // return pblendv(r, r+r, a);
10035    R = DAG.getNode(ISD::VSELECT, dl, VT, Op,
10036                    R, DAG.getNode(ISD::ADD, dl, VT, R, R));
10037    return R;
10038  }
10039  return SDValue();
10040}
10041
10042SDValue X86TargetLowering::LowerXALUO(SDValue Op, SelectionDAG &DAG) const {
10043  // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
10044  // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
10045  // looks for this combo and may remove the "setcc" instruction if the "setcc"
10046  // has only one use.
10047  SDNode *N = Op.getNode();
10048  SDValue LHS = N->getOperand(0);
10049  SDValue RHS = N->getOperand(1);
10050  unsigned BaseOp = 0;
10051  unsigned Cond = 0;
10052  DebugLoc DL = Op.getDebugLoc();
10053  switch (Op.getOpcode()) {
10054  default: llvm_unreachable("Unknown ovf instruction!");
10055  case ISD::SADDO:
10056    // A subtract of one will be selected as a INC. Note that INC doesn't
10057    // set CF, so we can't do this for UADDO.
10058    if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
10059      if (C->isOne()) {
10060        BaseOp = X86ISD::INC;
10061        Cond = X86::COND_O;
10062        break;
10063      }
10064    BaseOp = X86ISD::ADD;
10065    Cond = X86::COND_O;
10066    break;
10067  case ISD::UADDO:
10068    BaseOp = X86ISD::ADD;
10069    Cond = X86::COND_B;
10070    break;
10071  case ISD::SSUBO:
10072    // A subtract of one will be selected as a DEC. Note that DEC doesn't
10073    // set CF, so we can't do this for USUBO.
10074    if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
10075      if (C->isOne()) {
10076        BaseOp = X86ISD::DEC;
10077        Cond = X86::COND_O;
10078        break;
10079      }
10080    BaseOp = X86ISD::SUB;
10081    Cond = X86::COND_O;
10082    break;
10083  case ISD::USUBO:
10084    BaseOp = X86ISD::SUB;
10085    Cond = X86::COND_B;
10086    break;
10087  case ISD::SMULO:
10088    BaseOp = X86ISD::SMUL;
10089    Cond = X86::COND_O;
10090    break;
10091  case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
10092    SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
10093                                 MVT::i32);
10094    SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
10095
10096    SDValue SetCC =
10097      DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
10098                  DAG.getConstant(X86::COND_O, MVT::i32),
10099                  SDValue(Sum.getNode(), 2));
10100
10101    return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
10102  }
10103  }
10104
10105  // Also sets EFLAGS.
10106  SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
10107  SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
10108
10109  SDValue SetCC =
10110    DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
10111                DAG.getConstant(Cond, MVT::i32),
10112                SDValue(Sum.getNode(), 1));
10113
10114  return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
10115}
10116
10117SDValue X86TargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op, SelectionDAG &DAG) const{
10118  DebugLoc dl = Op.getDebugLoc();
10119  SDNode* Node = Op.getNode();
10120  EVT ExtraVT = cast<VTSDNode>(Node->getOperand(1))->getVT();
10121  EVT VT = Node->getValueType(0);
10122  if (Subtarget->hasXMMInt() && VT.isVector()) {
10123    unsigned BitsDiff = VT.getScalarType().getSizeInBits() -
10124                        ExtraVT.getScalarType().getSizeInBits();
10125    SDValue ShAmt = DAG.getConstant(BitsDiff, MVT::i32);
10126
10127    unsigned SHLIntrinsicsID = 0;
10128    unsigned SRAIntrinsicsID = 0;
10129    switch (VT.getSimpleVT().SimpleTy) {
10130      default:
10131        return SDValue();
10132      case MVT::v4i32: {
10133        SHLIntrinsicsID = Intrinsic::x86_sse2_pslli_d;
10134        SRAIntrinsicsID = Intrinsic::x86_sse2_psrai_d;
10135        break;
10136      }
10137      case MVT::v8i16: {
10138        SHLIntrinsicsID = Intrinsic::x86_sse2_pslli_w;
10139        SRAIntrinsicsID = Intrinsic::x86_sse2_psrai_w;
10140        break;
10141      }
10142    }
10143
10144    SDValue Tmp1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10145                         DAG.getConstant(SHLIntrinsicsID, MVT::i32),
10146                         Node->getOperand(0), ShAmt);
10147
10148    // In case of 1 bit sext, no need to shr
10149    if (ExtraVT.getScalarType().getSizeInBits() == 1) return Tmp1;
10150
10151    return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10152                       DAG.getConstant(SRAIntrinsicsID, MVT::i32),
10153                       Tmp1, ShAmt);
10154  }
10155
10156  return SDValue();
10157}
10158
10159
10160SDValue X86TargetLowering::LowerMEMBARRIER(SDValue Op, SelectionDAG &DAG) const{
10161  DebugLoc dl = Op.getDebugLoc();
10162
10163  // Go ahead and emit the fence on x86-64 even if we asked for no-sse2.
10164  // There isn't any reason to disable it if the target processor supports it.
10165  if (!Subtarget->hasXMMInt() && !Subtarget->is64Bit()) {
10166    SDValue Chain = Op.getOperand(0);
10167    SDValue Zero = DAG.getConstant(0, MVT::i32);
10168    SDValue Ops[] = {
10169      DAG.getRegister(X86::ESP, MVT::i32), // Base
10170      DAG.getTargetConstant(1, MVT::i8),   // Scale
10171      DAG.getRegister(0, MVT::i32),        // Index
10172      DAG.getTargetConstant(0, MVT::i32),  // Disp
10173      DAG.getRegister(0, MVT::i32),        // Segment.
10174      Zero,
10175      Chain
10176    };
10177    SDNode *Res =
10178      DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops,
10179                          array_lengthof(Ops));
10180    return SDValue(Res, 0);
10181  }
10182
10183  unsigned isDev = cast<ConstantSDNode>(Op.getOperand(5))->getZExtValue();
10184  if (!isDev)
10185    return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
10186
10187  unsigned Op1 = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10188  unsigned Op2 = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
10189  unsigned Op3 = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue();
10190  unsigned Op4 = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
10191
10192  // def : Pat<(membarrier (i8 0), (i8 0), (i8 0), (i8 1), (i8 1)), (SFENCE)>;
10193  if (!Op1 && !Op2 && !Op3 && Op4)
10194    return DAG.getNode(X86ISD::SFENCE, dl, MVT::Other, Op.getOperand(0));
10195
10196  // def : Pat<(membarrier (i8 1), (i8 0), (i8 0), (i8 0), (i8 1)), (LFENCE)>;
10197  if (Op1 && !Op2 && !Op3 && !Op4)
10198    return DAG.getNode(X86ISD::LFENCE, dl, MVT::Other, Op.getOperand(0));
10199
10200  // def : Pat<(membarrier (i8 imm), (i8 imm), (i8 imm), (i8 imm), (i8 1)),
10201  //           (MFENCE)>;
10202  return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
10203}
10204
10205SDValue X86TargetLowering::LowerATOMIC_FENCE(SDValue Op,
10206                                             SelectionDAG &DAG) const {
10207  DebugLoc dl = Op.getDebugLoc();
10208  AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
10209    cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
10210  SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
10211    cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
10212
10213  // The only fence that needs an instruction is a sequentially-consistent
10214  // cross-thread fence.
10215  if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
10216    // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
10217    // no-sse2). There isn't any reason to disable it if the target processor
10218    // supports it.
10219    if (Subtarget->hasXMMInt() || Subtarget->is64Bit())
10220      return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
10221
10222    SDValue Chain = Op.getOperand(0);
10223    SDValue Zero = DAG.getConstant(0, MVT::i32);
10224    SDValue Ops[] = {
10225      DAG.getRegister(X86::ESP, MVT::i32), // Base
10226      DAG.getTargetConstant(1, MVT::i8),   // Scale
10227      DAG.getRegister(0, MVT::i32),        // Index
10228      DAG.getTargetConstant(0, MVT::i32),  // Disp
10229      DAG.getRegister(0, MVT::i32),        // Segment.
10230      Zero,
10231      Chain
10232    };
10233    SDNode *Res =
10234      DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops,
10235                         array_lengthof(Ops));
10236    return SDValue(Res, 0);
10237  }
10238
10239  // MEMBARRIER is a compiler barrier; it codegens to a no-op.
10240  return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
10241}
10242
10243
10244SDValue X86TargetLowering::LowerCMP_SWAP(SDValue Op, SelectionDAG &DAG) const {
10245  EVT T = Op.getValueType();
10246  DebugLoc DL = Op.getDebugLoc();
10247  unsigned Reg = 0;
10248  unsigned size = 0;
10249  switch(T.getSimpleVT().SimpleTy) {
10250  default:
10251    assert(false && "Invalid value type!");
10252  case MVT::i8:  Reg = X86::AL;  size = 1; break;
10253  case MVT::i16: Reg = X86::AX;  size = 2; break;
10254  case MVT::i32: Reg = X86::EAX; size = 4; break;
10255  case MVT::i64:
10256    assert(Subtarget->is64Bit() && "Node not type legal!");
10257    Reg = X86::RAX; size = 8;
10258    break;
10259  }
10260  SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
10261                                    Op.getOperand(2), SDValue());
10262  SDValue Ops[] = { cpIn.getValue(0),
10263                    Op.getOperand(1),
10264                    Op.getOperand(3),
10265                    DAG.getTargetConstant(size, MVT::i8),
10266                    cpIn.getValue(1) };
10267  SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
10268  MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
10269  SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
10270                                           Ops, 5, T, MMO);
10271  SDValue cpOut =
10272    DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
10273  return cpOut;
10274}
10275
10276SDValue X86TargetLowering::LowerREADCYCLECOUNTER(SDValue Op,
10277                                                 SelectionDAG &DAG) const {
10278  assert(Subtarget->is64Bit() && "Result not type legalized?");
10279  SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
10280  SDValue TheChain = Op.getOperand(0);
10281  DebugLoc dl = Op.getDebugLoc();
10282  SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
10283  SDValue rax = DAG.getCopyFromReg(rd, dl, X86::RAX, MVT::i64, rd.getValue(1));
10284  SDValue rdx = DAG.getCopyFromReg(rax.getValue(1), dl, X86::RDX, MVT::i64,
10285                                   rax.getValue(2));
10286  SDValue Tmp = DAG.getNode(ISD::SHL, dl, MVT::i64, rdx,
10287                            DAG.getConstant(32, MVT::i8));
10288  SDValue Ops[] = {
10289    DAG.getNode(ISD::OR, dl, MVT::i64, rax, Tmp),
10290    rdx.getValue(1)
10291  };
10292  return DAG.getMergeValues(Ops, 2, dl);
10293}
10294
10295SDValue X86TargetLowering::LowerBITCAST(SDValue Op,
10296                                            SelectionDAG &DAG) const {
10297  EVT SrcVT = Op.getOperand(0).getValueType();
10298  EVT DstVT = Op.getValueType();
10299  assert(Subtarget->is64Bit() && !Subtarget->hasXMMInt() &&
10300         Subtarget->hasMMX() && "Unexpected custom BITCAST");
10301  assert((DstVT == MVT::i64 ||
10302          (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
10303         "Unexpected custom BITCAST");
10304  // i64 <=> MMX conversions are Legal.
10305  if (SrcVT==MVT::i64 && DstVT.isVector())
10306    return Op;
10307  if (DstVT==MVT::i64 && SrcVT.isVector())
10308    return Op;
10309  // MMX <=> MMX conversions are Legal.
10310  if (SrcVT.isVector() && DstVT.isVector())
10311    return Op;
10312  // All other conversions need to be expanded.
10313  return SDValue();
10314}
10315
10316SDValue X86TargetLowering::LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) const {
10317  SDNode *Node = Op.getNode();
10318  DebugLoc dl = Node->getDebugLoc();
10319  EVT T = Node->getValueType(0);
10320  SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
10321                              DAG.getConstant(0, T), Node->getOperand(2));
10322  return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
10323                       cast<AtomicSDNode>(Node)->getMemoryVT(),
10324                       Node->getOperand(0),
10325                       Node->getOperand(1), negOp,
10326                       cast<AtomicSDNode>(Node)->getSrcValue(),
10327                       cast<AtomicSDNode>(Node)->getAlignment(),
10328                       cast<AtomicSDNode>(Node)->getOrdering(),
10329                       cast<AtomicSDNode>(Node)->getSynchScope());
10330}
10331
10332static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
10333  SDNode *Node = Op.getNode();
10334  DebugLoc dl = Node->getDebugLoc();
10335  EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
10336
10337  // Convert seq_cst store -> xchg
10338  // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
10339  // FIXME: On 32-bit, store -> fist or movq would be more efficient
10340  //        (The only way to get a 16-byte store is cmpxchg16b)
10341  // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
10342  if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
10343      !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
10344    SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
10345                                 cast<AtomicSDNode>(Node)->getMemoryVT(),
10346                                 Node->getOperand(0),
10347                                 Node->getOperand(1), Node->getOperand(2),
10348                                 cast<AtomicSDNode>(Node)->getMemOperand(),
10349                                 cast<AtomicSDNode>(Node)->getOrdering(),
10350                                 cast<AtomicSDNode>(Node)->getSynchScope());
10351    return Swap.getValue(1);
10352  }
10353  // Other atomic stores have a simple pattern.
10354  return Op;
10355}
10356
10357static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
10358  EVT VT = Op.getNode()->getValueType(0);
10359
10360  // Let legalize expand this if it isn't a legal type yet.
10361  if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
10362    return SDValue();
10363
10364  SDVTList VTs = DAG.getVTList(VT, MVT::i32);
10365
10366  unsigned Opc;
10367  bool ExtraOp = false;
10368  switch (Op.getOpcode()) {
10369  default: assert(0 && "Invalid code");
10370  case ISD::ADDC: Opc = X86ISD::ADD; break;
10371  case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
10372  case ISD::SUBC: Opc = X86ISD::SUB; break;
10373  case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
10374  }
10375
10376  if (!ExtraOp)
10377    return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
10378                       Op.getOperand(1));
10379  return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
10380                     Op.getOperand(1), Op.getOperand(2));
10381}
10382
10383/// LowerOperation - Provide custom lowering hooks for some operations.
10384///
10385SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
10386  switch (Op.getOpcode()) {
10387  default: llvm_unreachable("Should not custom lower this!");
10388  case ISD::SIGN_EXTEND_INREG:  return LowerSIGN_EXTEND_INREG(Op,DAG);
10389  case ISD::MEMBARRIER:         return LowerMEMBARRIER(Op,DAG);
10390  case ISD::ATOMIC_FENCE:       return LowerATOMIC_FENCE(Op,DAG);
10391  case ISD::ATOMIC_CMP_SWAP:    return LowerCMP_SWAP(Op,DAG);
10392  case ISD::ATOMIC_LOAD_SUB:    return LowerLOAD_SUB(Op,DAG);
10393  case ISD::ATOMIC_STORE:       return LowerATOMIC_STORE(Op,DAG);
10394  case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
10395  case ISD::CONCAT_VECTORS:     return LowerCONCAT_VECTORS(Op, DAG);
10396  case ISD::VECTOR_SHUFFLE:     return LowerVECTOR_SHUFFLE(Op, DAG);
10397  case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
10398  case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
10399  case ISD::EXTRACT_SUBVECTOR:  return LowerEXTRACT_SUBVECTOR(Op, DAG);
10400  case ISD::INSERT_SUBVECTOR:   return LowerINSERT_SUBVECTOR(Op, DAG);
10401  case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
10402  case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
10403  case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
10404  case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
10405  case ISD::ExternalSymbol:     return LowerExternalSymbol(Op, DAG);
10406  case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
10407  case ISD::SHL_PARTS:
10408  case ISD::SRA_PARTS:
10409  case ISD::SRL_PARTS:          return LowerShiftParts(Op, DAG);
10410  case ISD::SINT_TO_FP:         return LowerSINT_TO_FP(Op, DAG);
10411  case ISD::UINT_TO_FP:         return LowerUINT_TO_FP(Op, DAG);
10412  case ISD::FP_TO_SINT:         return LowerFP_TO_SINT(Op, DAG);
10413  case ISD::FP_TO_UINT:         return LowerFP_TO_UINT(Op, DAG);
10414  case ISD::FABS:               return LowerFABS(Op, DAG);
10415  case ISD::FNEG:               return LowerFNEG(Op, DAG);
10416  case ISD::FCOPYSIGN:          return LowerFCOPYSIGN(Op, DAG);
10417  case ISD::FGETSIGN:           return LowerFGETSIGN(Op, DAG);
10418  case ISD::SETCC:              return LowerSETCC(Op, DAG);
10419  case ISD::SELECT:             return LowerSELECT(Op, DAG);
10420  case ISD::BRCOND:             return LowerBRCOND(Op, DAG);
10421  case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
10422  case ISD::VASTART:            return LowerVASTART(Op, DAG);
10423  case ISD::VAARG:              return LowerVAARG(Op, DAG);
10424  case ISD::VACOPY:             return LowerVACOPY(Op, DAG);
10425  case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
10426  case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
10427  case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
10428  case ISD::FRAME_TO_ARGS_OFFSET:
10429                                return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
10430  case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
10431  case ISD::EH_RETURN:          return LowerEH_RETURN(Op, DAG);
10432  case ISD::INIT_TRAMPOLINE:    return LowerINIT_TRAMPOLINE(Op, DAG);
10433  case ISD::ADJUST_TRAMPOLINE:  return LowerADJUST_TRAMPOLINE(Op, DAG);
10434  case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
10435  case ISD::CTLZ:               return LowerCTLZ(Op, DAG);
10436  case ISD::CTTZ:               return LowerCTTZ(Op, DAG);
10437  case ISD::MUL:                return LowerMUL(Op, DAG);
10438  case ISD::SRA:
10439  case ISD::SRL:
10440  case ISD::SHL:                return LowerShift(Op, DAG);
10441  case ISD::SADDO:
10442  case ISD::UADDO:
10443  case ISD::SSUBO:
10444  case ISD::USUBO:
10445  case ISD::SMULO:
10446  case ISD::UMULO:              return LowerXALUO(Op, DAG);
10447  case ISD::READCYCLECOUNTER:   return LowerREADCYCLECOUNTER(Op, DAG);
10448  case ISD::BITCAST:            return LowerBITCAST(Op, DAG);
10449  case ISD::ADDC:
10450  case ISD::ADDE:
10451  case ISD::SUBC:
10452  case ISD::SUBE:               return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
10453  case ISD::ADD:                return LowerADD(Op, DAG);
10454  case ISD::SUB:                return LowerSUB(Op, DAG);
10455  }
10456}
10457
10458static void ReplaceATOMIC_LOAD(SDNode *Node,
10459                                  SmallVectorImpl<SDValue> &Results,
10460                                  SelectionDAG &DAG) {
10461  DebugLoc dl = Node->getDebugLoc();
10462  EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
10463
10464  // Convert wide load -> cmpxchg8b/cmpxchg16b
10465  // FIXME: On 32-bit, load -> fild or movq would be more efficient
10466  //        (The only way to get a 16-byte load is cmpxchg16b)
10467  // FIXME: 16-byte ATOMIC_CMP_SWAP isn't actually hooked up at the moment.
10468  SDValue Zero = DAG.getConstant(0, VT);
10469  SDValue Swap = DAG.getAtomic(ISD::ATOMIC_CMP_SWAP, dl, VT,
10470                               Node->getOperand(0),
10471                               Node->getOperand(1), Zero, Zero,
10472                               cast<AtomicSDNode>(Node)->getMemOperand(),
10473                               cast<AtomicSDNode>(Node)->getOrdering(),
10474                               cast<AtomicSDNode>(Node)->getSynchScope());
10475  Results.push_back(Swap.getValue(0));
10476  Results.push_back(Swap.getValue(1));
10477}
10478
10479void X86TargetLowering::
10480ReplaceATOMIC_BINARY_64(SDNode *Node, SmallVectorImpl<SDValue>&Results,
10481                        SelectionDAG &DAG, unsigned NewOp) const {
10482  DebugLoc dl = Node->getDebugLoc();
10483  assert (Node->getValueType(0) == MVT::i64 &&
10484          "Only know how to expand i64 atomics");
10485
10486  SDValue Chain = Node->getOperand(0);
10487  SDValue In1 = Node->getOperand(1);
10488  SDValue In2L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
10489                             Node->getOperand(2), DAG.getIntPtrConstant(0));
10490  SDValue In2H = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
10491                             Node->getOperand(2), DAG.getIntPtrConstant(1));
10492  SDValue Ops[] = { Chain, In1, In2L, In2H };
10493  SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
10494  SDValue Result =
10495    DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops, 4, MVT::i64,
10496                            cast<MemSDNode>(Node)->getMemOperand());
10497  SDValue OpsF[] = { Result.getValue(0), Result.getValue(1)};
10498  Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
10499  Results.push_back(Result.getValue(2));
10500}
10501
10502/// ReplaceNodeResults - Replace a node with an illegal result type
10503/// with a new node built out of custom code.
10504void X86TargetLowering::ReplaceNodeResults(SDNode *N,
10505                                           SmallVectorImpl<SDValue>&Results,
10506                                           SelectionDAG &DAG) const {
10507  DebugLoc dl = N->getDebugLoc();
10508  switch (N->getOpcode()) {
10509  default:
10510    assert(false && "Do not know how to custom type legalize this operation!");
10511    return;
10512  case ISD::SIGN_EXTEND_INREG:
10513  case ISD::ADDC:
10514  case ISD::ADDE:
10515  case ISD::SUBC:
10516  case ISD::SUBE:
10517    // We don't want to expand or promote these.
10518    return;
10519  case ISD::FP_TO_SINT: {
10520    std::pair<SDValue,SDValue> Vals =
10521        FP_TO_INTHelper(SDValue(N, 0), DAG, true);
10522    SDValue FIST = Vals.first, StackSlot = Vals.second;
10523    if (FIST.getNode() != 0) {
10524      EVT VT = N->getValueType(0);
10525      // Return a load from the stack slot.
10526      Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
10527                                    MachinePointerInfo(), false, false, 0));
10528    }
10529    return;
10530  }
10531  case ISD::READCYCLECOUNTER: {
10532    SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
10533    SDValue TheChain = N->getOperand(0);
10534    SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
10535    SDValue eax = DAG.getCopyFromReg(rd, dl, X86::EAX, MVT::i32,
10536                                     rd.getValue(1));
10537    SDValue edx = DAG.getCopyFromReg(eax.getValue(1), dl, X86::EDX, MVT::i32,
10538                                     eax.getValue(2));
10539    // Use a buildpair to merge the two 32-bit values into a 64-bit one.
10540    SDValue Ops[] = { eax, edx };
10541    Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Ops, 2));
10542    Results.push_back(edx.getValue(1));
10543    return;
10544  }
10545  case ISD::ATOMIC_CMP_SWAP: {
10546    EVT T = N->getValueType(0);
10547    assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
10548    bool Regs64bit = T == MVT::i128;
10549    EVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
10550    SDValue cpInL, cpInH;
10551    cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
10552                        DAG.getConstant(0, HalfT));
10553    cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
10554                        DAG.getConstant(1, HalfT));
10555    cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
10556                             Regs64bit ? X86::RAX : X86::EAX,
10557                             cpInL, SDValue());
10558    cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
10559                             Regs64bit ? X86::RDX : X86::EDX,
10560                             cpInH, cpInL.getValue(1));
10561    SDValue swapInL, swapInH;
10562    swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
10563                          DAG.getConstant(0, HalfT));
10564    swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
10565                          DAG.getConstant(1, HalfT));
10566    swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
10567                               Regs64bit ? X86::RBX : X86::EBX,
10568                               swapInL, cpInH.getValue(1));
10569    swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
10570                               Regs64bit ? X86::RCX : X86::ECX,
10571                               swapInH, swapInL.getValue(1));
10572    SDValue Ops[] = { swapInH.getValue(0),
10573                      N->getOperand(1),
10574                      swapInH.getValue(1) };
10575    SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
10576    MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
10577    unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
10578                                  X86ISD::LCMPXCHG8_DAG;
10579    SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys,
10580                                             Ops, 3, T, MMO);
10581    SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
10582                                        Regs64bit ? X86::RAX : X86::EAX,
10583                                        HalfT, Result.getValue(1));
10584    SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
10585                                        Regs64bit ? X86::RDX : X86::EDX,
10586                                        HalfT, cpOutL.getValue(2));
10587    SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
10588    Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF, 2));
10589    Results.push_back(cpOutH.getValue(1));
10590    return;
10591  }
10592  case ISD::ATOMIC_LOAD_ADD:
10593    ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMADD64_DAG);
10594    return;
10595  case ISD::ATOMIC_LOAD_AND:
10596    ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMAND64_DAG);
10597    return;
10598  case ISD::ATOMIC_LOAD_NAND:
10599    ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMNAND64_DAG);
10600    return;
10601  case ISD::ATOMIC_LOAD_OR:
10602    ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMOR64_DAG);
10603    return;
10604  case ISD::ATOMIC_LOAD_SUB:
10605    ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSUB64_DAG);
10606    return;
10607  case ISD::ATOMIC_LOAD_XOR:
10608    ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMXOR64_DAG);
10609    return;
10610  case ISD::ATOMIC_SWAP:
10611    ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSWAP64_DAG);
10612    return;
10613  case ISD::ATOMIC_LOAD:
10614    ReplaceATOMIC_LOAD(N, Results, DAG);
10615  }
10616}
10617
10618const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
10619  switch (Opcode) {
10620  default: return NULL;
10621  case X86ISD::BSF:                return "X86ISD::BSF";
10622  case X86ISD::BSR:                return "X86ISD::BSR";
10623  case X86ISD::SHLD:               return "X86ISD::SHLD";
10624  case X86ISD::SHRD:               return "X86ISD::SHRD";
10625  case X86ISD::FAND:               return "X86ISD::FAND";
10626  case X86ISD::FOR:                return "X86ISD::FOR";
10627  case X86ISD::FXOR:               return "X86ISD::FXOR";
10628  case X86ISD::FSRL:               return "X86ISD::FSRL";
10629  case X86ISD::FILD:               return "X86ISD::FILD";
10630  case X86ISD::FILD_FLAG:          return "X86ISD::FILD_FLAG";
10631  case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
10632  case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
10633  case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
10634  case X86ISD::FLD:                return "X86ISD::FLD";
10635  case X86ISD::FST:                return "X86ISD::FST";
10636  case X86ISD::CALL:               return "X86ISD::CALL";
10637  case X86ISD::RDTSC_DAG:          return "X86ISD::RDTSC_DAG";
10638  case X86ISD::BT:                 return "X86ISD::BT";
10639  case X86ISD::CMP:                return "X86ISD::CMP";
10640  case X86ISD::COMI:               return "X86ISD::COMI";
10641  case X86ISD::UCOMI:              return "X86ISD::UCOMI";
10642  case X86ISD::SETCC:              return "X86ISD::SETCC";
10643  case X86ISD::SETCC_CARRY:        return "X86ISD::SETCC_CARRY";
10644  case X86ISD::FSETCCsd:           return "X86ISD::FSETCCsd";
10645  case X86ISD::FSETCCss:           return "X86ISD::FSETCCss";
10646  case X86ISD::CMOV:               return "X86ISD::CMOV";
10647  case X86ISD::BRCOND:             return "X86ISD::BRCOND";
10648  case X86ISD::RET_FLAG:           return "X86ISD::RET_FLAG";
10649  case X86ISD::REP_STOS:           return "X86ISD::REP_STOS";
10650  case X86ISD::REP_MOVS:           return "X86ISD::REP_MOVS";
10651  case X86ISD::GlobalBaseReg:      return "X86ISD::GlobalBaseReg";
10652  case X86ISD::Wrapper:            return "X86ISD::Wrapper";
10653  case X86ISD::WrapperRIP:         return "X86ISD::WrapperRIP";
10654  case X86ISD::PEXTRB:             return "X86ISD::PEXTRB";
10655  case X86ISD::PEXTRW:             return "X86ISD::PEXTRW";
10656  case X86ISD::INSERTPS:           return "X86ISD::INSERTPS";
10657  case X86ISD::PINSRB:             return "X86ISD::PINSRB";
10658  case X86ISD::PINSRW:             return "X86ISD::PINSRW";
10659  case X86ISD::PSHUFB:             return "X86ISD::PSHUFB";
10660  case X86ISD::ANDNP:              return "X86ISD::ANDNP";
10661  case X86ISD::PSIGNB:             return "X86ISD::PSIGNB";
10662  case X86ISD::PSIGNW:             return "X86ISD::PSIGNW";
10663  case X86ISD::PSIGND:             return "X86ISD::PSIGND";
10664  case X86ISD::FMAX:               return "X86ISD::FMAX";
10665  case X86ISD::FMIN:               return "X86ISD::FMIN";
10666  case X86ISD::FRSQRT:             return "X86ISD::FRSQRT";
10667  case X86ISD::FRCP:               return "X86ISD::FRCP";
10668  case X86ISD::FHADD:              return "X86ISD::FHADD";
10669  case X86ISD::FHSUB:              return "X86ISD::FHSUB";
10670  case X86ISD::TLSADDR:            return "X86ISD::TLSADDR";
10671  case X86ISD::TLSCALL:            return "X86ISD::TLSCALL";
10672  case X86ISD::EH_RETURN:          return "X86ISD::EH_RETURN";
10673  case X86ISD::TC_RETURN:          return "X86ISD::TC_RETURN";
10674  case X86ISD::FNSTCW16m:          return "X86ISD::FNSTCW16m";
10675  case X86ISD::LCMPXCHG_DAG:       return "X86ISD::LCMPXCHG_DAG";
10676  case X86ISD::LCMPXCHG8_DAG:      return "X86ISD::LCMPXCHG8_DAG";
10677  case X86ISD::ATOMADD64_DAG:      return "X86ISD::ATOMADD64_DAG";
10678  case X86ISD::ATOMSUB64_DAG:      return "X86ISD::ATOMSUB64_DAG";
10679  case X86ISD::ATOMOR64_DAG:       return "X86ISD::ATOMOR64_DAG";
10680  case X86ISD::ATOMXOR64_DAG:      return "X86ISD::ATOMXOR64_DAG";
10681  case X86ISD::ATOMAND64_DAG:      return "X86ISD::ATOMAND64_DAG";
10682  case X86ISD::ATOMNAND64_DAG:     return "X86ISD::ATOMNAND64_DAG";
10683  case X86ISD::VZEXT_MOVL:         return "X86ISD::VZEXT_MOVL";
10684  case X86ISD::VZEXT_LOAD:         return "X86ISD::VZEXT_LOAD";
10685  case X86ISD::VSHL:               return "X86ISD::VSHL";
10686  case X86ISD::VSRL:               return "X86ISD::VSRL";
10687  case X86ISD::CMPPD:              return "X86ISD::CMPPD";
10688  case X86ISD::CMPPS:              return "X86ISD::CMPPS";
10689  case X86ISD::PCMPEQB:            return "X86ISD::PCMPEQB";
10690  case X86ISD::PCMPEQW:            return "X86ISD::PCMPEQW";
10691  case X86ISD::PCMPEQD:            return "X86ISD::PCMPEQD";
10692  case X86ISD::PCMPEQQ:            return "X86ISD::PCMPEQQ";
10693  case X86ISD::PCMPGTB:            return "X86ISD::PCMPGTB";
10694  case X86ISD::PCMPGTW:            return "X86ISD::PCMPGTW";
10695  case X86ISD::PCMPGTD:            return "X86ISD::PCMPGTD";
10696  case X86ISD::PCMPGTQ:            return "X86ISD::PCMPGTQ";
10697  case X86ISD::ADD:                return "X86ISD::ADD";
10698  case X86ISD::SUB:                return "X86ISD::SUB";
10699  case X86ISD::ADC:                return "X86ISD::ADC";
10700  case X86ISD::SBB:                return "X86ISD::SBB";
10701  case X86ISD::SMUL:               return "X86ISD::SMUL";
10702  case X86ISD::UMUL:               return "X86ISD::UMUL";
10703  case X86ISD::INC:                return "X86ISD::INC";
10704  case X86ISD::DEC:                return "X86ISD::DEC";
10705  case X86ISD::OR:                 return "X86ISD::OR";
10706  case X86ISD::XOR:                return "X86ISD::XOR";
10707  case X86ISD::AND:                return "X86ISD::AND";
10708  case X86ISD::ANDN:               return "X86ISD::ANDN";
10709  case X86ISD::MUL_IMM:            return "X86ISD::MUL_IMM";
10710  case X86ISD::PTEST:              return "X86ISD::PTEST";
10711  case X86ISD::TESTP:              return "X86ISD::TESTP";
10712  case X86ISD::PALIGN:             return "X86ISD::PALIGN";
10713  case X86ISD::PSHUFD:             return "X86ISD::PSHUFD";
10714  case X86ISD::PSHUFHW:            return "X86ISD::PSHUFHW";
10715  case X86ISD::PSHUFHW_LD:         return "X86ISD::PSHUFHW_LD";
10716  case X86ISD::PSHUFLW:            return "X86ISD::PSHUFLW";
10717  case X86ISD::PSHUFLW_LD:         return "X86ISD::PSHUFLW_LD";
10718  case X86ISD::SHUFPS:             return "X86ISD::SHUFPS";
10719  case X86ISD::SHUFPD:             return "X86ISD::SHUFPD";
10720  case X86ISD::MOVLHPS:            return "X86ISD::MOVLHPS";
10721  case X86ISD::MOVLHPD:            return "X86ISD::MOVLHPD";
10722  case X86ISD::MOVHLPS:            return "X86ISD::MOVHLPS";
10723  case X86ISD::MOVHLPD:            return "X86ISD::MOVHLPD";
10724  case X86ISD::MOVLPS:             return "X86ISD::MOVLPS";
10725  case X86ISD::MOVLPD:             return "X86ISD::MOVLPD";
10726  case X86ISD::MOVDDUP:            return "X86ISD::MOVDDUP";
10727  case X86ISD::MOVSHDUP:           return "X86ISD::MOVSHDUP";
10728  case X86ISD::MOVSLDUP:           return "X86ISD::MOVSLDUP";
10729  case X86ISD::MOVSHDUP_LD:        return "X86ISD::MOVSHDUP_LD";
10730  case X86ISD::MOVSLDUP_LD:        return "X86ISD::MOVSLDUP_LD";
10731  case X86ISD::MOVSD:              return "X86ISD::MOVSD";
10732  case X86ISD::MOVSS:              return "X86ISD::MOVSS";
10733  case X86ISD::UNPCKLPS:           return "X86ISD::UNPCKLPS";
10734  case X86ISD::UNPCKLPD:           return "X86ISD::UNPCKLPD";
10735  case X86ISD::VUNPCKLPDY:         return "X86ISD::VUNPCKLPDY";
10736  case X86ISD::UNPCKHPS:           return "X86ISD::UNPCKHPS";
10737  case X86ISD::UNPCKHPD:           return "X86ISD::UNPCKHPD";
10738  case X86ISD::PUNPCKLBW:          return "X86ISD::PUNPCKLBW";
10739  case X86ISD::PUNPCKLWD:          return "X86ISD::PUNPCKLWD";
10740  case X86ISD::PUNPCKLDQ:          return "X86ISD::PUNPCKLDQ";
10741  case X86ISD::PUNPCKLQDQ:         return "X86ISD::PUNPCKLQDQ";
10742  case X86ISD::PUNPCKHBW:          return "X86ISD::PUNPCKHBW";
10743  case X86ISD::PUNPCKHWD:          return "X86ISD::PUNPCKHWD";
10744  case X86ISD::PUNPCKHDQ:          return "X86ISD::PUNPCKHDQ";
10745  case X86ISD::PUNPCKHQDQ:         return "X86ISD::PUNPCKHQDQ";
10746  case X86ISD::VBROADCAST:         return "X86ISD::VBROADCAST";
10747  case X86ISD::VPERMILPS:          return "X86ISD::VPERMILPS";
10748  case X86ISD::VPERMILPSY:         return "X86ISD::VPERMILPSY";
10749  case X86ISD::VPERMILPD:          return "X86ISD::VPERMILPD";
10750  case X86ISD::VPERMILPDY:         return "X86ISD::VPERMILPDY";
10751  case X86ISD::VPERM2F128:         return "X86ISD::VPERM2F128";
10752  case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
10753  case X86ISD::VAARG_64:           return "X86ISD::VAARG_64";
10754  case X86ISD::WIN_ALLOCA:         return "X86ISD::WIN_ALLOCA";
10755  case X86ISD::MEMBARRIER:         return "X86ISD::MEMBARRIER";
10756  case X86ISD::SEG_ALLOCA:         return "X86ISD::SEG_ALLOCA";
10757  }
10758}
10759
10760// isLegalAddressingMode - Return true if the addressing mode represented
10761// by AM is legal for this target, for a load/store of the specified type.
10762bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
10763                                              Type *Ty) const {
10764  // X86 supports extremely general addressing modes.
10765  CodeModel::Model M = getTargetMachine().getCodeModel();
10766  Reloc::Model R = getTargetMachine().getRelocationModel();
10767
10768  // X86 allows a sign-extended 32-bit immediate field as a displacement.
10769  if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != NULL))
10770    return false;
10771
10772  if (AM.BaseGV) {
10773    unsigned GVFlags =
10774      Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
10775
10776    // If a reference to this global requires an extra load, we can't fold it.
10777    if (isGlobalStubReference(GVFlags))
10778      return false;
10779
10780    // If BaseGV requires a register for the PIC base, we cannot also have a
10781    // BaseReg specified.
10782    if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
10783      return false;
10784
10785    // If lower 4G is not available, then we must use rip-relative addressing.
10786    if ((M != CodeModel::Small || R != Reloc::Static) &&
10787        Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
10788      return false;
10789  }
10790
10791  switch (AM.Scale) {
10792  case 0:
10793  case 1:
10794  case 2:
10795  case 4:
10796  case 8:
10797    // These scales always work.
10798    break;
10799  case 3:
10800  case 5:
10801  case 9:
10802    // These scales are formed with basereg+scalereg.  Only accept if there is
10803    // no basereg yet.
10804    if (AM.HasBaseReg)
10805      return false;
10806    break;
10807  default:  // Other stuff never works.
10808    return false;
10809  }
10810
10811  return true;
10812}
10813
10814
10815bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
10816  if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
10817    return false;
10818  unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
10819  unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
10820  if (NumBits1 <= NumBits2)
10821    return false;
10822  return true;
10823}
10824
10825bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
10826  if (!VT1.isInteger() || !VT2.isInteger())
10827    return false;
10828  unsigned NumBits1 = VT1.getSizeInBits();
10829  unsigned NumBits2 = VT2.getSizeInBits();
10830  if (NumBits1 <= NumBits2)
10831    return false;
10832  return true;
10833}
10834
10835bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
10836  // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
10837  return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
10838}
10839
10840bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
10841  // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
10842  return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
10843}
10844
10845bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
10846  // i16 instructions are longer (0x66 prefix) and potentially slower.
10847  return !(VT1 == MVT::i32 && VT2 == MVT::i16);
10848}
10849
10850/// isShuffleMaskLegal - Targets can use this to indicate that they only
10851/// support *some* VECTOR_SHUFFLE operations, those with specific masks.
10852/// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
10853/// are assumed to be legal.
10854bool
10855X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
10856                                      EVT VT) const {
10857  // Very little shuffling can be done for 64-bit vectors right now.
10858  if (VT.getSizeInBits() == 64)
10859    return isPALIGNRMask(M, VT, Subtarget->hasSSSE3() || Subtarget->hasAVX());
10860
10861  // FIXME: pshufb, blends, shifts.
10862  return (VT.getVectorNumElements() == 2 ||
10863          ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
10864          isMOVLMask(M, VT) ||
10865          isSHUFPMask(M, VT) ||
10866          isPSHUFDMask(M, VT) ||
10867          isPSHUFHWMask(M, VT) ||
10868          isPSHUFLWMask(M, VT) ||
10869          isPALIGNRMask(M, VT, Subtarget->hasSSSE3() || Subtarget->hasAVX()) ||
10870          isUNPCKLMask(M, VT) ||
10871          isUNPCKHMask(M, VT) ||
10872          isUNPCKL_v_undef_Mask(M, VT) ||
10873          isUNPCKH_v_undef_Mask(M, VT));
10874}
10875
10876bool
10877X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
10878                                          EVT VT) const {
10879  unsigned NumElts = VT.getVectorNumElements();
10880  // FIXME: This collection of masks seems suspect.
10881  if (NumElts == 2)
10882    return true;
10883  if (NumElts == 4 && VT.getSizeInBits() == 128) {
10884    return (isMOVLMask(Mask, VT)  ||
10885            isCommutedMOVLMask(Mask, VT, true) ||
10886            isSHUFPMask(Mask, VT) ||
10887            isCommutedSHUFPMask(Mask, VT));
10888  }
10889  return false;
10890}
10891
10892//===----------------------------------------------------------------------===//
10893//                           X86 Scheduler Hooks
10894//===----------------------------------------------------------------------===//
10895
10896// private utility function
10897MachineBasicBlock *
10898X86TargetLowering::EmitAtomicBitwiseWithCustomInserter(MachineInstr *bInstr,
10899                                                       MachineBasicBlock *MBB,
10900                                                       unsigned regOpc,
10901                                                       unsigned immOpc,
10902                                                       unsigned LoadOpc,
10903                                                       unsigned CXchgOpc,
10904                                                       unsigned notOpc,
10905                                                       unsigned EAXreg,
10906                                                       TargetRegisterClass *RC,
10907                                                       bool invSrc) const {
10908  // For the atomic bitwise operator, we generate
10909  //   thisMBB:
10910  //   newMBB:
10911  //     ld  t1 = [bitinstr.addr]
10912  //     op  t2 = t1, [bitinstr.val]
10913  //     mov EAX = t1
10914  //     lcs dest = [bitinstr.addr], t2  [EAX is implicit]
10915  //     bz  newMBB
10916  //     fallthrough -->nextMBB
10917  const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
10918  const BasicBlock *LLVM_BB = MBB->getBasicBlock();
10919  MachineFunction::iterator MBBIter = MBB;
10920  ++MBBIter;
10921
10922  /// First build the CFG
10923  MachineFunction *F = MBB->getParent();
10924  MachineBasicBlock *thisMBB = MBB;
10925  MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
10926  MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
10927  F->insert(MBBIter, newMBB);
10928  F->insert(MBBIter, nextMBB);
10929
10930  // Transfer the remainder of thisMBB and its successor edges to nextMBB.
10931  nextMBB->splice(nextMBB->begin(), thisMBB,
10932                  llvm::next(MachineBasicBlock::iterator(bInstr)),
10933                  thisMBB->end());
10934  nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
10935
10936  // Update thisMBB to fall through to newMBB
10937  thisMBB->addSuccessor(newMBB);
10938
10939  // newMBB jumps to itself and fall through to nextMBB
10940  newMBB->addSuccessor(nextMBB);
10941  newMBB->addSuccessor(newMBB);
10942
10943  // Insert instructions into newMBB based on incoming instruction
10944  assert(bInstr->getNumOperands() < X86::AddrNumOperands + 4 &&
10945         "unexpected number of operands");
10946  DebugLoc dl = bInstr->getDebugLoc();
10947  MachineOperand& destOper = bInstr->getOperand(0);
10948  MachineOperand* argOpers[2 + X86::AddrNumOperands];
10949  int numArgs = bInstr->getNumOperands() - 1;
10950  for (int i=0; i < numArgs; ++i)
10951    argOpers[i] = &bInstr->getOperand(i+1);
10952
10953  // x86 address has 4 operands: base, index, scale, and displacement
10954  int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
10955  int valArgIndx = lastAddrIndx + 1;
10956
10957  unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
10958  MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(LoadOpc), t1);
10959  for (int i=0; i <= lastAddrIndx; ++i)
10960    (*MIB).addOperand(*argOpers[i]);
10961
10962  unsigned tt = F->getRegInfo().createVirtualRegister(RC);
10963  if (invSrc) {
10964    MIB = BuildMI(newMBB, dl, TII->get(notOpc), tt).addReg(t1);
10965  }
10966  else
10967    tt = t1;
10968
10969  unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
10970  assert((argOpers[valArgIndx]->isReg() ||
10971          argOpers[valArgIndx]->isImm()) &&
10972         "invalid operand");
10973  if (argOpers[valArgIndx]->isReg())
10974    MIB = BuildMI(newMBB, dl, TII->get(regOpc), t2);
10975  else
10976    MIB = BuildMI(newMBB, dl, TII->get(immOpc), t2);
10977  MIB.addReg(tt);
10978  (*MIB).addOperand(*argOpers[valArgIndx]);
10979
10980  MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), EAXreg);
10981  MIB.addReg(t1);
10982
10983  MIB = BuildMI(newMBB, dl, TII->get(CXchgOpc));
10984  for (int i=0; i <= lastAddrIndx; ++i)
10985    (*MIB).addOperand(*argOpers[i]);
10986  MIB.addReg(t2);
10987  assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
10988  (*MIB).setMemRefs(bInstr->memoperands_begin(),
10989                    bInstr->memoperands_end());
10990
10991  MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), destOper.getReg());
10992  MIB.addReg(EAXreg);
10993
10994  // insert branch
10995  BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
10996
10997  bInstr->eraseFromParent();   // The pseudo instruction is gone now.
10998  return nextMBB;
10999}
11000
11001// private utility function:  64 bit atomics on 32 bit host.
11002MachineBasicBlock *
11003X86TargetLowering::EmitAtomicBit6432WithCustomInserter(MachineInstr *bInstr,
11004                                                       MachineBasicBlock *MBB,
11005                                                       unsigned regOpcL,
11006                                                       unsigned regOpcH,
11007                                                       unsigned immOpcL,
11008                                                       unsigned immOpcH,
11009                                                       bool invSrc) const {
11010  // For the atomic bitwise operator, we generate
11011  //   thisMBB (instructions are in pairs, except cmpxchg8b)
11012  //     ld t1,t2 = [bitinstr.addr]
11013  //   newMBB:
11014  //     out1, out2 = phi (thisMBB, t1/t2) (newMBB, t3/t4)
11015  //     op  t5, t6 <- out1, out2, [bitinstr.val]
11016  //      (for SWAP, substitute:  mov t5, t6 <- [bitinstr.val])
11017  //     mov ECX, EBX <- t5, t6
11018  //     mov EAX, EDX <- t1, t2
11019  //     cmpxchg8b [bitinstr.addr]  [EAX, EDX, EBX, ECX implicit]
11020  //     mov t3, t4 <- EAX, EDX
11021  //     bz  newMBB
11022  //     result in out1, out2
11023  //     fallthrough -->nextMBB
11024
11025  const TargetRegisterClass *RC = X86::GR32RegisterClass;
11026  const unsigned LoadOpc = X86::MOV32rm;
11027  const unsigned NotOpc = X86::NOT32r;
11028  const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11029  const BasicBlock *LLVM_BB = MBB->getBasicBlock();
11030  MachineFunction::iterator MBBIter = MBB;
11031  ++MBBIter;
11032
11033  /// First build the CFG
11034  MachineFunction *F = MBB->getParent();
11035  MachineBasicBlock *thisMBB = MBB;
11036  MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
11037  MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
11038  F->insert(MBBIter, newMBB);
11039  F->insert(MBBIter, nextMBB);
11040
11041  // Transfer the remainder of thisMBB and its successor edges to nextMBB.
11042  nextMBB->splice(nextMBB->begin(), thisMBB,
11043                  llvm::next(MachineBasicBlock::iterator(bInstr)),
11044                  thisMBB->end());
11045  nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
11046
11047  // Update thisMBB to fall through to newMBB
11048  thisMBB->addSuccessor(newMBB);
11049
11050  // newMBB jumps to itself and fall through to nextMBB
11051  newMBB->addSuccessor(nextMBB);
11052  newMBB->addSuccessor(newMBB);
11053
11054  DebugLoc dl = bInstr->getDebugLoc();
11055  // Insert instructions into newMBB based on incoming instruction
11056  // There are 8 "real" operands plus 9 implicit def/uses, ignored here.
11057  assert(bInstr->getNumOperands() < X86::AddrNumOperands + 14 &&
11058         "unexpected number of operands");
11059  MachineOperand& dest1Oper = bInstr->getOperand(0);
11060  MachineOperand& dest2Oper = bInstr->getOperand(1);
11061  MachineOperand* argOpers[2 + X86::AddrNumOperands];
11062  for (int i=0; i < 2 + X86::AddrNumOperands; ++i) {
11063    argOpers[i] = &bInstr->getOperand(i+2);
11064
11065    // We use some of the operands multiple times, so conservatively just
11066    // clear any kill flags that might be present.
11067    if (argOpers[i]->isReg() && argOpers[i]->isUse())
11068      argOpers[i]->setIsKill(false);
11069  }
11070
11071  // x86 address has 5 operands: base, index, scale, displacement, and segment.
11072  int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
11073
11074  unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
11075  MachineInstrBuilder MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t1);
11076  for (int i=0; i <= lastAddrIndx; ++i)
11077    (*MIB).addOperand(*argOpers[i]);
11078  unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
11079  MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t2);
11080  // add 4 to displacement.
11081  for (int i=0; i <= lastAddrIndx-2; ++i)
11082    (*MIB).addOperand(*argOpers[i]);
11083  MachineOperand newOp3 = *(argOpers[3]);
11084  if (newOp3.isImm())
11085    newOp3.setImm(newOp3.getImm()+4);
11086  else
11087    newOp3.setOffset(newOp3.getOffset()+4);
11088  (*MIB).addOperand(newOp3);
11089  (*MIB).addOperand(*argOpers[lastAddrIndx]);
11090
11091  // t3/4 are defined later, at the bottom of the loop
11092  unsigned t3 = F->getRegInfo().createVirtualRegister(RC);
11093  unsigned t4 = F->getRegInfo().createVirtualRegister(RC);
11094  BuildMI(newMBB, dl, TII->get(X86::PHI), dest1Oper.getReg())
11095    .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(newMBB);
11096  BuildMI(newMBB, dl, TII->get(X86::PHI), dest2Oper.getReg())
11097    .addReg(t2).addMBB(thisMBB).addReg(t4).addMBB(newMBB);
11098
11099  // The subsequent operations should be using the destination registers of
11100  //the PHI instructions.
11101  if (invSrc) {
11102    t1 = F->getRegInfo().createVirtualRegister(RC);
11103    t2 = F->getRegInfo().createVirtualRegister(RC);
11104    MIB = BuildMI(newMBB, dl, TII->get(NotOpc), t1).addReg(dest1Oper.getReg());
11105    MIB = BuildMI(newMBB, dl, TII->get(NotOpc), t2).addReg(dest2Oper.getReg());
11106  } else {
11107    t1 = dest1Oper.getReg();
11108    t2 = dest2Oper.getReg();
11109  }
11110
11111  int valArgIndx = lastAddrIndx + 1;
11112  assert((argOpers[valArgIndx]->isReg() ||
11113          argOpers[valArgIndx]->isImm()) &&
11114         "invalid operand");
11115  unsigned t5 = F->getRegInfo().createVirtualRegister(RC);
11116  unsigned t6 = F->getRegInfo().createVirtualRegister(RC);
11117  if (argOpers[valArgIndx]->isReg())
11118    MIB = BuildMI(newMBB, dl, TII->get(regOpcL), t5);
11119  else
11120    MIB = BuildMI(newMBB, dl, TII->get(immOpcL), t5);
11121  if (regOpcL != X86::MOV32rr)
11122    MIB.addReg(t1);
11123  (*MIB).addOperand(*argOpers[valArgIndx]);
11124  assert(argOpers[valArgIndx + 1]->isReg() ==
11125         argOpers[valArgIndx]->isReg());
11126  assert(argOpers[valArgIndx + 1]->isImm() ==
11127         argOpers[valArgIndx]->isImm());
11128  if (argOpers[valArgIndx + 1]->isReg())
11129    MIB = BuildMI(newMBB, dl, TII->get(regOpcH), t6);
11130  else
11131    MIB = BuildMI(newMBB, dl, TII->get(immOpcH), t6);
11132  if (regOpcH != X86::MOV32rr)
11133    MIB.addReg(t2);
11134  (*MIB).addOperand(*argOpers[valArgIndx + 1]);
11135
11136  MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EAX);
11137  MIB.addReg(t1);
11138  MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EDX);
11139  MIB.addReg(t2);
11140
11141  MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EBX);
11142  MIB.addReg(t5);
11143  MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::ECX);
11144  MIB.addReg(t6);
11145
11146  MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG8B));
11147  for (int i=0; i <= lastAddrIndx; ++i)
11148    (*MIB).addOperand(*argOpers[i]);
11149
11150  assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
11151  (*MIB).setMemRefs(bInstr->memoperands_begin(),
11152                    bInstr->memoperands_end());
11153
11154  MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t3);
11155  MIB.addReg(X86::EAX);
11156  MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t4);
11157  MIB.addReg(X86::EDX);
11158
11159  // insert branch
11160  BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
11161
11162  bInstr->eraseFromParent();   // The pseudo instruction is gone now.
11163  return nextMBB;
11164}
11165
11166// private utility function
11167MachineBasicBlock *
11168X86TargetLowering::EmitAtomicMinMaxWithCustomInserter(MachineInstr *mInstr,
11169                                                      MachineBasicBlock *MBB,
11170                                                      unsigned cmovOpc) const {
11171  // For the atomic min/max operator, we generate
11172  //   thisMBB:
11173  //   newMBB:
11174  //     ld t1 = [min/max.addr]
11175  //     mov t2 = [min/max.val]
11176  //     cmp  t1, t2
11177  //     cmov[cond] t2 = t1
11178  //     mov EAX = t1
11179  //     lcs dest = [bitinstr.addr], t2  [EAX is implicit]
11180  //     bz   newMBB
11181  //     fallthrough -->nextMBB
11182  //
11183  const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11184  const BasicBlock *LLVM_BB = MBB->getBasicBlock();
11185  MachineFunction::iterator MBBIter = MBB;
11186  ++MBBIter;
11187
11188  /// First build the CFG
11189  MachineFunction *F = MBB->getParent();
11190  MachineBasicBlock *thisMBB = MBB;
11191  MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
11192  MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
11193  F->insert(MBBIter, newMBB);
11194  F->insert(MBBIter, nextMBB);
11195
11196  // Transfer the remainder of thisMBB and its successor edges to nextMBB.
11197  nextMBB->splice(nextMBB->begin(), thisMBB,
11198                  llvm::next(MachineBasicBlock::iterator(mInstr)),
11199                  thisMBB->end());
11200  nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
11201
11202  // Update thisMBB to fall through to newMBB
11203  thisMBB->addSuccessor(newMBB);
11204
11205  // newMBB jumps to newMBB and fall through to nextMBB
11206  newMBB->addSuccessor(nextMBB);
11207  newMBB->addSuccessor(newMBB);
11208
11209  DebugLoc dl = mInstr->getDebugLoc();
11210  // Insert instructions into newMBB based on incoming instruction
11211  assert(mInstr->getNumOperands() < X86::AddrNumOperands + 4 &&
11212         "unexpected number of operands");
11213  MachineOperand& destOper = mInstr->getOperand(0);
11214  MachineOperand* argOpers[2 + X86::AddrNumOperands];
11215  int numArgs = mInstr->getNumOperands() - 1;
11216  for (int i=0; i < numArgs; ++i)
11217    argOpers[i] = &mInstr->getOperand(i+1);
11218
11219  // x86 address has 4 operands: base, index, scale, and displacement
11220  int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
11221  int valArgIndx = lastAddrIndx + 1;
11222
11223  unsigned t1 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
11224  MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rm), t1);
11225  for (int i=0; i <= lastAddrIndx; ++i)
11226    (*MIB).addOperand(*argOpers[i]);
11227
11228  // We only support register and immediate values
11229  assert((argOpers[valArgIndx]->isReg() ||
11230          argOpers[valArgIndx]->isImm()) &&
11231         "invalid operand");
11232
11233  unsigned t2 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
11234  if (argOpers[valArgIndx]->isReg())
11235    MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t2);
11236  else
11237    MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rr), t2);
11238  (*MIB).addOperand(*argOpers[valArgIndx]);
11239
11240  MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EAX);
11241  MIB.addReg(t1);
11242
11243  MIB = BuildMI(newMBB, dl, TII->get(X86::CMP32rr));
11244  MIB.addReg(t1);
11245  MIB.addReg(t2);
11246
11247  // Generate movc
11248  unsigned t3 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
11249  MIB = BuildMI(newMBB, dl, TII->get(cmovOpc),t3);
11250  MIB.addReg(t2);
11251  MIB.addReg(t1);
11252
11253  // Cmp and exchange if none has modified the memory location
11254  MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG32));
11255  for (int i=0; i <= lastAddrIndx; ++i)
11256    (*MIB).addOperand(*argOpers[i]);
11257  MIB.addReg(t3);
11258  assert(mInstr->hasOneMemOperand() && "Unexpected number of memoperand");
11259  (*MIB).setMemRefs(mInstr->memoperands_begin(),
11260                    mInstr->memoperands_end());
11261
11262  MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), destOper.getReg());
11263  MIB.addReg(X86::EAX);
11264
11265  // insert branch
11266  BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
11267
11268  mInstr->eraseFromParent();   // The pseudo instruction is gone now.
11269  return nextMBB;
11270}
11271
11272// FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
11273// or XMM0_V32I8 in AVX all of this code can be replaced with that
11274// in the .td file.
11275MachineBasicBlock *
11276X86TargetLowering::EmitPCMP(MachineInstr *MI, MachineBasicBlock *BB,
11277                            unsigned numArgs, bool memArg) const {
11278  assert((Subtarget->hasSSE42() || Subtarget->hasAVX()) &&
11279         "Target must have SSE4.2 or AVX features enabled");
11280
11281  DebugLoc dl = MI->getDebugLoc();
11282  const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11283  unsigned Opc;
11284  if (!Subtarget->hasAVX()) {
11285    if (memArg)
11286      Opc = numArgs == 3 ? X86::PCMPISTRM128rm : X86::PCMPESTRM128rm;
11287    else
11288      Opc = numArgs == 3 ? X86::PCMPISTRM128rr : X86::PCMPESTRM128rr;
11289  } else {
11290    if (memArg)
11291      Opc = numArgs == 3 ? X86::VPCMPISTRM128rm : X86::VPCMPESTRM128rm;
11292    else
11293      Opc = numArgs == 3 ? X86::VPCMPISTRM128rr : X86::VPCMPESTRM128rr;
11294  }
11295
11296  MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
11297  for (unsigned i = 0; i < numArgs; ++i) {
11298    MachineOperand &Op = MI->getOperand(i+1);
11299    if (!(Op.isReg() && Op.isImplicit()))
11300      MIB.addOperand(Op);
11301  }
11302  BuildMI(*BB, MI, dl,
11303    TII->get(Subtarget->hasAVX() ? X86::VMOVAPSrr : X86::MOVAPSrr),
11304             MI->getOperand(0).getReg())
11305    .addReg(X86::XMM0);
11306
11307  MI->eraseFromParent();
11308  return BB;
11309}
11310
11311MachineBasicBlock *
11312X86TargetLowering::EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB) const {
11313  DebugLoc dl = MI->getDebugLoc();
11314  const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11315
11316  // Address into RAX/EAX, other two args into ECX, EDX.
11317  unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
11318  unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
11319  MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
11320  for (int i = 0; i < X86::AddrNumOperands; ++i)
11321    MIB.addOperand(MI->getOperand(i));
11322
11323  unsigned ValOps = X86::AddrNumOperands;
11324  BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
11325    .addReg(MI->getOperand(ValOps).getReg());
11326  BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
11327    .addReg(MI->getOperand(ValOps+1).getReg());
11328
11329  // The instruction doesn't actually take any operands though.
11330  BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
11331
11332  MI->eraseFromParent(); // The pseudo is gone now.
11333  return BB;
11334}
11335
11336MachineBasicBlock *
11337X86TargetLowering::EmitMwait(MachineInstr *MI, MachineBasicBlock *BB) const {
11338  DebugLoc dl = MI->getDebugLoc();
11339  const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11340
11341  // First arg in ECX, the second in EAX.
11342  BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
11343    .addReg(MI->getOperand(0).getReg());
11344  BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EAX)
11345    .addReg(MI->getOperand(1).getReg());
11346
11347  // The instruction doesn't actually take any operands though.
11348  BuildMI(*BB, MI, dl, TII->get(X86::MWAITrr));
11349
11350  MI->eraseFromParent(); // The pseudo is gone now.
11351  return BB;
11352}
11353
11354MachineBasicBlock *
11355X86TargetLowering::EmitVAARG64WithCustomInserter(
11356                   MachineInstr *MI,
11357                   MachineBasicBlock *MBB) const {
11358  // Emit va_arg instruction on X86-64.
11359
11360  // Operands to this pseudo-instruction:
11361  // 0  ) Output        : destination address (reg)
11362  // 1-5) Input         : va_list address (addr, i64mem)
11363  // 6  ) ArgSize       : Size (in bytes) of vararg type
11364  // 7  ) ArgMode       : 0=overflow only, 1=use gp_offset, 2=use fp_offset
11365  // 8  ) Align         : Alignment of type
11366  // 9  ) EFLAGS (implicit-def)
11367
11368  assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
11369  assert(X86::AddrNumOperands == 5 && "VAARG_64 assumes 5 address operands");
11370
11371  unsigned DestReg = MI->getOperand(0).getReg();
11372  MachineOperand &Base = MI->getOperand(1);
11373  MachineOperand &Scale = MI->getOperand(2);
11374  MachineOperand &Index = MI->getOperand(3);
11375  MachineOperand &Disp = MI->getOperand(4);
11376  MachineOperand &Segment = MI->getOperand(5);
11377  unsigned ArgSize = MI->getOperand(6).getImm();
11378  unsigned ArgMode = MI->getOperand(7).getImm();
11379  unsigned Align = MI->getOperand(8).getImm();
11380
11381  // Memory Reference
11382  assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
11383  MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
11384  MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
11385
11386  // Machine Information
11387  const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11388  MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
11389  const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
11390  const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
11391  DebugLoc DL = MI->getDebugLoc();
11392
11393  // struct va_list {
11394  //   i32   gp_offset
11395  //   i32   fp_offset
11396  //   i64   overflow_area (address)
11397  //   i64   reg_save_area (address)
11398  // }
11399  // sizeof(va_list) = 24
11400  // alignment(va_list) = 8
11401
11402  unsigned TotalNumIntRegs = 6;
11403  unsigned TotalNumXMMRegs = 8;
11404  bool UseGPOffset = (ArgMode == 1);
11405  bool UseFPOffset = (ArgMode == 2);
11406  unsigned MaxOffset = TotalNumIntRegs * 8 +
11407                       (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
11408
11409  /* Align ArgSize to a multiple of 8 */
11410  unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
11411  bool NeedsAlign = (Align > 8);
11412
11413  MachineBasicBlock *thisMBB = MBB;
11414  MachineBasicBlock *overflowMBB;
11415  MachineBasicBlock *offsetMBB;
11416  MachineBasicBlock *endMBB;
11417
11418  unsigned OffsetDestReg = 0;    // Argument address computed by offsetMBB
11419  unsigned OverflowDestReg = 0;  // Argument address computed by overflowMBB
11420  unsigned OffsetReg = 0;
11421
11422  if (!UseGPOffset && !UseFPOffset) {
11423    // If we only pull from the overflow region, we don't create a branch.
11424    // We don't need to alter control flow.
11425    OffsetDestReg = 0; // unused
11426    OverflowDestReg = DestReg;
11427
11428    offsetMBB = NULL;
11429    overflowMBB = thisMBB;
11430    endMBB = thisMBB;
11431  } else {
11432    // First emit code to check if gp_offset (or fp_offset) is below the bound.
11433    // If so, pull the argument from reg_save_area. (branch to offsetMBB)
11434    // If not, pull from overflow_area. (branch to overflowMBB)
11435    //
11436    //       thisMBB
11437    //         |     .
11438    //         |        .
11439    //     offsetMBB   overflowMBB
11440    //         |        .
11441    //         |     .
11442    //        endMBB
11443
11444    // Registers for the PHI in endMBB
11445    OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
11446    OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
11447
11448    const BasicBlock *LLVM_BB = MBB->getBasicBlock();
11449    MachineFunction *MF = MBB->getParent();
11450    overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
11451    offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
11452    endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
11453
11454    MachineFunction::iterator MBBIter = MBB;
11455    ++MBBIter;
11456
11457    // Insert the new basic blocks
11458    MF->insert(MBBIter, offsetMBB);
11459    MF->insert(MBBIter, overflowMBB);
11460    MF->insert(MBBIter, endMBB);
11461
11462    // Transfer the remainder of MBB and its successor edges to endMBB.
11463    endMBB->splice(endMBB->begin(), thisMBB,
11464                    llvm::next(MachineBasicBlock::iterator(MI)),
11465                    thisMBB->end());
11466    endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
11467
11468    // Make offsetMBB and overflowMBB successors of thisMBB
11469    thisMBB->addSuccessor(offsetMBB);
11470    thisMBB->addSuccessor(overflowMBB);
11471
11472    // endMBB is a successor of both offsetMBB and overflowMBB
11473    offsetMBB->addSuccessor(endMBB);
11474    overflowMBB->addSuccessor(endMBB);
11475
11476    // Load the offset value into a register
11477    OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
11478    BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
11479      .addOperand(Base)
11480      .addOperand(Scale)
11481      .addOperand(Index)
11482      .addDisp(Disp, UseFPOffset ? 4 : 0)
11483      .addOperand(Segment)
11484      .setMemRefs(MMOBegin, MMOEnd);
11485
11486    // Check if there is enough room left to pull this argument.
11487    BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
11488      .addReg(OffsetReg)
11489      .addImm(MaxOffset + 8 - ArgSizeA8);
11490
11491    // Branch to "overflowMBB" if offset >= max
11492    // Fall through to "offsetMBB" otherwise
11493    BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
11494      .addMBB(overflowMBB);
11495  }
11496
11497  // In offsetMBB, emit code to use the reg_save_area.
11498  if (offsetMBB) {
11499    assert(OffsetReg != 0);
11500
11501    // Read the reg_save_area address.
11502    unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
11503    BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
11504      .addOperand(Base)
11505      .addOperand(Scale)
11506      .addOperand(Index)
11507      .addDisp(Disp, 16)
11508      .addOperand(Segment)
11509      .setMemRefs(MMOBegin, MMOEnd);
11510
11511    // Zero-extend the offset
11512    unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
11513      BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
11514        .addImm(0)
11515        .addReg(OffsetReg)
11516        .addImm(X86::sub_32bit);
11517
11518    // Add the offset to the reg_save_area to get the final address.
11519    BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
11520      .addReg(OffsetReg64)
11521      .addReg(RegSaveReg);
11522
11523    // Compute the offset for the next argument
11524    unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
11525    BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
11526      .addReg(OffsetReg)
11527      .addImm(UseFPOffset ? 16 : 8);
11528
11529    // Store it back into the va_list.
11530    BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
11531      .addOperand(Base)
11532      .addOperand(Scale)
11533      .addOperand(Index)
11534      .addDisp(Disp, UseFPOffset ? 4 : 0)
11535      .addOperand(Segment)
11536      .addReg(NextOffsetReg)
11537      .setMemRefs(MMOBegin, MMOEnd);
11538
11539    // Jump to endMBB
11540    BuildMI(offsetMBB, DL, TII->get(X86::JMP_4))
11541      .addMBB(endMBB);
11542  }
11543
11544  //
11545  // Emit code to use overflow area
11546  //
11547
11548  // Load the overflow_area address into a register.
11549  unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
11550  BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
11551    .addOperand(Base)
11552    .addOperand(Scale)
11553    .addOperand(Index)
11554    .addDisp(Disp, 8)
11555    .addOperand(Segment)
11556    .setMemRefs(MMOBegin, MMOEnd);
11557
11558  // If we need to align it, do so. Otherwise, just copy the address
11559  // to OverflowDestReg.
11560  if (NeedsAlign) {
11561    // Align the overflow address
11562    assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
11563    unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
11564
11565    // aligned_addr = (addr + (align-1)) & ~(align-1)
11566    BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
11567      .addReg(OverflowAddrReg)
11568      .addImm(Align-1);
11569
11570    BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
11571      .addReg(TmpReg)
11572      .addImm(~(uint64_t)(Align-1));
11573  } else {
11574    BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
11575      .addReg(OverflowAddrReg);
11576  }
11577
11578  // Compute the next overflow address after this argument.
11579  // (the overflow address should be kept 8-byte aligned)
11580  unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
11581  BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
11582    .addReg(OverflowDestReg)
11583    .addImm(ArgSizeA8);
11584
11585  // Store the new overflow address.
11586  BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
11587    .addOperand(Base)
11588    .addOperand(Scale)
11589    .addOperand(Index)
11590    .addDisp(Disp, 8)
11591    .addOperand(Segment)
11592    .addReg(NextAddrReg)
11593    .setMemRefs(MMOBegin, MMOEnd);
11594
11595  // If we branched, emit the PHI to the front of endMBB.
11596  if (offsetMBB) {
11597    BuildMI(*endMBB, endMBB->begin(), DL,
11598            TII->get(X86::PHI), DestReg)
11599      .addReg(OffsetDestReg).addMBB(offsetMBB)
11600      .addReg(OverflowDestReg).addMBB(overflowMBB);
11601  }
11602
11603  // Erase the pseudo instruction
11604  MI->eraseFromParent();
11605
11606  return endMBB;
11607}
11608
11609MachineBasicBlock *
11610X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
11611                                                 MachineInstr *MI,
11612                                                 MachineBasicBlock *MBB) const {
11613  // Emit code to save XMM registers to the stack. The ABI says that the
11614  // number of registers to save is given in %al, so it's theoretically
11615  // possible to do an indirect jump trick to avoid saving all of them,
11616  // however this code takes a simpler approach and just executes all
11617  // of the stores if %al is non-zero. It's less code, and it's probably
11618  // easier on the hardware branch predictor, and stores aren't all that
11619  // expensive anyway.
11620
11621  // Create the new basic blocks. One block contains all the XMM stores,
11622  // and one block is the final destination regardless of whether any
11623  // stores were performed.
11624  const BasicBlock *LLVM_BB = MBB->getBasicBlock();
11625  MachineFunction *F = MBB->getParent();
11626  MachineFunction::iterator MBBIter = MBB;
11627  ++MBBIter;
11628  MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
11629  MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
11630  F->insert(MBBIter, XMMSaveMBB);
11631  F->insert(MBBIter, EndMBB);
11632
11633  // Transfer the remainder of MBB and its successor edges to EndMBB.
11634  EndMBB->splice(EndMBB->begin(), MBB,
11635                 llvm::next(MachineBasicBlock::iterator(MI)),
11636                 MBB->end());
11637  EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
11638
11639  // The original block will now fall through to the XMM save block.
11640  MBB->addSuccessor(XMMSaveMBB);
11641  // The XMMSaveMBB will fall through to the end block.
11642  XMMSaveMBB->addSuccessor(EndMBB);
11643
11644  // Now add the instructions.
11645  const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11646  DebugLoc DL = MI->getDebugLoc();
11647
11648  unsigned CountReg = MI->getOperand(0).getReg();
11649  int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
11650  int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
11651
11652  if (!Subtarget->isTargetWin64()) {
11653    // If %al is 0, branch around the XMM save block.
11654    BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
11655    BuildMI(MBB, DL, TII->get(X86::JE_4)).addMBB(EndMBB);
11656    MBB->addSuccessor(EndMBB);
11657  }
11658
11659  unsigned MOVOpc = Subtarget->hasAVX() ? X86::VMOVAPSmr : X86::MOVAPSmr;
11660  // In the XMM save block, save all the XMM argument registers.
11661  for (int i = 3, e = MI->getNumOperands(); i != e; ++i) {
11662    int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
11663    MachineMemOperand *MMO =
11664      F->getMachineMemOperand(
11665          MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
11666        MachineMemOperand::MOStore,
11667        /*Size=*/16, /*Align=*/16);
11668    BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
11669      .addFrameIndex(RegSaveFrameIndex)
11670      .addImm(/*Scale=*/1)
11671      .addReg(/*IndexReg=*/0)
11672      .addImm(/*Disp=*/Offset)
11673      .addReg(/*Segment=*/0)
11674      .addReg(MI->getOperand(i).getReg())
11675      .addMemOperand(MMO);
11676  }
11677
11678  MI->eraseFromParent();   // The pseudo instruction is gone now.
11679
11680  return EndMBB;
11681}
11682
11683MachineBasicBlock *
11684X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
11685                                     MachineBasicBlock *BB) const {
11686  const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11687  DebugLoc DL = MI->getDebugLoc();
11688
11689  // To "insert" a SELECT_CC instruction, we actually have to insert the
11690  // diamond control-flow pattern.  The incoming instruction knows the
11691  // destination vreg to set, the condition code register to branch on, the
11692  // true/false values to select between, and a branch opcode to use.
11693  const BasicBlock *LLVM_BB = BB->getBasicBlock();
11694  MachineFunction::iterator It = BB;
11695  ++It;
11696
11697  //  thisMBB:
11698  //  ...
11699  //   TrueVal = ...
11700  //   cmpTY ccX, r1, r2
11701  //   bCC copy1MBB
11702  //   fallthrough --> copy0MBB
11703  MachineBasicBlock *thisMBB = BB;
11704  MachineFunction *F = BB->getParent();
11705  MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
11706  MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
11707  F->insert(It, copy0MBB);
11708  F->insert(It, sinkMBB);
11709
11710  // If the EFLAGS register isn't dead in the terminator, then claim that it's
11711  // live into the sink and copy blocks.
11712  if (!MI->killsRegister(X86::EFLAGS)) {
11713    copy0MBB->addLiveIn(X86::EFLAGS);
11714    sinkMBB->addLiveIn(X86::EFLAGS);
11715  }
11716
11717  // Transfer the remainder of BB and its successor edges to sinkMBB.
11718  sinkMBB->splice(sinkMBB->begin(), BB,
11719                  llvm::next(MachineBasicBlock::iterator(MI)),
11720                  BB->end());
11721  sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
11722
11723  // Add the true and fallthrough blocks as its successors.
11724  BB->addSuccessor(copy0MBB);
11725  BB->addSuccessor(sinkMBB);
11726
11727  // Create the conditional branch instruction.
11728  unsigned Opc =
11729    X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
11730  BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
11731
11732  //  copy0MBB:
11733  //   %FalseValue = ...
11734  //   # fallthrough to sinkMBB
11735  copy0MBB->addSuccessor(sinkMBB);
11736
11737  //  sinkMBB:
11738  //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
11739  //  ...
11740  BuildMI(*sinkMBB, sinkMBB->begin(), DL,
11741          TII->get(X86::PHI), MI->getOperand(0).getReg())
11742    .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
11743    .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
11744
11745  MI->eraseFromParent();   // The pseudo instruction is gone now.
11746  return sinkMBB;
11747}
11748
11749MachineBasicBlock *
11750X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI, MachineBasicBlock *BB,
11751                                        bool Is64Bit) const {
11752  const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11753  DebugLoc DL = MI->getDebugLoc();
11754  MachineFunction *MF = BB->getParent();
11755  const BasicBlock *LLVM_BB = BB->getBasicBlock();
11756
11757  assert(EnableSegmentedStacks);
11758
11759  unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
11760  unsigned TlsOffset = Is64Bit ? 0x70 : 0x30;
11761
11762  // BB:
11763  //  ... [Till the alloca]
11764  // If stacklet is not large enough, jump to mallocMBB
11765  //
11766  // bumpMBB:
11767  //  Allocate by subtracting from RSP
11768  //  Jump to continueMBB
11769  //
11770  // mallocMBB:
11771  //  Allocate by call to runtime
11772  //
11773  // continueMBB:
11774  //  ...
11775  //  [rest of original BB]
11776  //
11777
11778  MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
11779  MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
11780  MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
11781
11782  MachineRegisterInfo &MRI = MF->getRegInfo();
11783  const TargetRegisterClass *AddrRegClass =
11784    getRegClassFor(Is64Bit ? MVT::i64:MVT::i32);
11785
11786  unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
11787    bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
11788    tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
11789    sizeVReg = MI->getOperand(1).getReg(),
11790    physSPReg = Is64Bit ? X86::RSP : X86::ESP;
11791
11792  MachineFunction::iterator MBBIter = BB;
11793  ++MBBIter;
11794
11795  MF->insert(MBBIter, bumpMBB);
11796  MF->insert(MBBIter, mallocMBB);
11797  MF->insert(MBBIter, continueMBB);
11798
11799  continueMBB->splice(continueMBB->begin(), BB, llvm::next
11800                      (MachineBasicBlock::iterator(MI)), BB->end());
11801  continueMBB->transferSuccessorsAndUpdatePHIs(BB);
11802
11803  // Add code to the main basic block to check if the stack limit has been hit,
11804  // and if so, jump to mallocMBB otherwise to bumpMBB.
11805  BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
11806  BuildMI(BB, DL, TII->get(Is64Bit ? X86::SUB64rr:X86::SUB32rr), tmpSPVReg)
11807    .addReg(tmpSPVReg).addReg(sizeVReg);
11808  BuildMI(BB, DL, TII->get(Is64Bit ? X86::CMP64mr:X86::CMP32mr))
11809    .addReg(0).addImm(0).addReg(0).addImm(TlsOffset).addReg(TlsReg)
11810    .addReg(tmpSPVReg);
11811  BuildMI(BB, DL, TII->get(X86::JG_4)).addMBB(mallocMBB);
11812
11813  // bumpMBB simply decreases the stack pointer, since we know the current
11814  // stacklet has enough space.
11815  BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
11816    .addReg(tmpSPVReg);
11817  BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
11818    .addReg(tmpSPVReg);
11819  BuildMI(bumpMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
11820
11821  // Calls into a routine in libgcc to allocate more space from the heap.
11822  if (Is64Bit) {
11823    BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
11824      .addReg(sizeVReg);
11825    BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
11826    .addExternalSymbol("__morestack_allocate_stack_space").addReg(X86::RDI);
11827  } else {
11828    BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
11829      .addImm(12);
11830    BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
11831    BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
11832      .addExternalSymbol("__morestack_allocate_stack_space");
11833  }
11834
11835  if (!Is64Bit)
11836    BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
11837      .addImm(16);
11838
11839  BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
11840    .addReg(Is64Bit ? X86::RAX : X86::EAX);
11841  BuildMI(mallocMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
11842
11843  // Set up the CFG correctly.
11844  BB->addSuccessor(bumpMBB);
11845  BB->addSuccessor(mallocMBB);
11846  mallocMBB->addSuccessor(continueMBB);
11847  bumpMBB->addSuccessor(continueMBB);
11848
11849  // Take care of the PHI nodes.
11850  BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
11851          MI->getOperand(0).getReg())
11852    .addReg(mallocPtrVReg).addMBB(mallocMBB)
11853    .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
11854
11855  // Delete the original pseudo instruction.
11856  MI->eraseFromParent();
11857
11858  // And we're done.
11859  return continueMBB;
11860}
11861
11862MachineBasicBlock *
11863X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
11864                                          MachineBasicBlock *BB) const {
11865  const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11866  DebugLoc DL = MI->getDebugLoc();
11867
11868  assert(!Subtarget->isTargetEnvMacho());
11869
11870  // The lowering is pretty easy: we're just emitting the call to _alloca.  The
11871  // non-trivial part is impdef of ESP.
11872
11873  if (Subtarget->isTargetWin64()) {
11874    if (Subtarget->isTargetCygMing()) {
11875      // ___chkstk(Mingw64):
11876      // Clobbers R10, R11, RAX and EFLAGS.
11877      // Updates RSP.
11878      BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
11879        .addExternalSymbol("___chkstk")
11880        .addReg(X86::RAX, RegState::Implicit)
11881        .addReg(X86::RSP, RegState::Implicit)
11882        .addReg(X86::RAX, RegState::Define | RegState::Implicit)
11883        .addReg(X86::RSP, RegState::Define | RegState::Implicit)
11884        .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
11885    } else {
11886      // __chkstk(MSVCRT): does not update stack pointer.
11887      // Clobbers R10, R11 and EFLAGS.
11888      // FIXME: RAX(allocated size) might be reused and not killed.
11889      BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
11890        .addExternalSymbol("__chkstk")
11891        .addReg(X86::RAX, RegState::Implicit)
11892        .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
11893      // RAX has the offset to subtracted from RSP.
11894      BuildMI(*BB, MI, DL, TII->get(X86::SUB64rr), X86::RSP)
11895        .addReg(X86::RSP)
11896        .addReg(X86::RAX);
11897    }
11898  } else {
11899    const char *StackProbeSymbol =
11900      Subtarget->isTargetWindows() ? "_chkstk" : "_alloca";
11901
11902    BuildMI(*BB, MI, DL, TII->get(X86::CALLpcrel32))
11903      .addExternalSymbol(StackProbeSymbol)
11904      .addReg(X86::EAX, RegState::Implicit)
11905      .addReg(X86::ESP, RegState::Implicit)
11906      .addReg(X86::EAX, RegState::Define | RegState::Implicit)
11907      .addReg(X86::ESP, RegState::Define | RegState::Implicit)
11908      .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
11909  }
11910
11911  MI->eraseFromParent();   // The pseudo instruction is gone now.
11912  return BB;
11913}
11914
11915MachineBasicBlock *
11916X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
11917                                      MachineBasicBlock *BB) const {
11918  // This is pretty easy.  We're taking the value that we received from
11919  // our load from the relocation, sticking it in either RDI (x86-64)
11920  // or EAX and doing an indirect call.  The return value will then
11921  // be in the normal return register.
11922  const X86InstrInfo *TII
11923    = static_cast<const X86InstrInfo*>(getTargetMachine().getInstrInfo());
11924  DebugLoc DL = MI->getDebugLoc();
11925  MachineFunction *F = BB->getParent();
11926
11927  assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
11928  assert(MI->getOperand(3).isGlobal() && "This should be a global");
11929
11930  if (Subtarget->is64Bit()) {
11931    MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
11932                                      TII->get(X86::MOV64rm), X86::RDI)
11933    .addReg(X86::RIP)
11934    .addImm(0).addReg(0)
11935    .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
11936                      MI->getOperand(3).getTargetFlags())
11937    .addReg(0);
11938    MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
11939    addDirectMem(MIB, X86::RDI);
11940  } else if (getTargetMachine().getRelocationModel() != Reloc::PIC_) {
11941    MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
11942                                      TII->get(X86::MOV32rm), X86::EAX)
11943    .addReg(0)
11944    .addImm(0).addReg(0)
11945    .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
11946                      MI->getOperand(3).getTargetFlags())
11947    .addReg(0);
11948    MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
11949    addDirectMem(MIB, X86::EAX);
11950  } else {
11951    MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
11952                                      TII->get(X86::MOV32rm), X86::EAX)
11953    .addReg(TII->getGlobalBaseReg(F))
11954    .addImm(0).addReg(0)
11955    .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
11956                      MI->getOperand(3).getTargetFlags())
11957    .addReg(0);
11958    MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
11959    addDirectMem(MIB, X86::EAX);
11960  }
11961
11962  MI->eraseFromParent(); // The pseudo instruction is gone now.
11963  return BB;
11964}
11965
11966MachineBasicBlock *
11967X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
11968                                               MachineBasicBlock *BB) const {
11969  switch (MI->getOpcode()) {
11970  default: assert(0 && "Unexpected instr type to insert");
11971  case X86::TAILJMPd64:
11972  case X86::TAILJMPr64:
11973  case X86::TAILJMPm64:
11974    assert(0 && "TAILJMP64 would not be touched here.");
11975  case X86::TCRETURNdi64:
11976  case X86::TCRETURNri64:
11977  case X86::TCRETURNmi64:
11978    // Defs of TCRETURNxx64 has Win64's callee-saved registers, as subset.
11979    // On AMD64, additional defs should be added before register allocation.
11980    if (!Subtarget->isTargetWin64()) {
11981      MI->addRegisterDefined(X86::RSI);
11982      MI->addRegisterDefined(X86::RDI);
11983      MI->addRegisterDefined(X86::XMM6);
11984      MI->addRegisterDefined(X86::XMM7);
11985      MI->addRegisterDefined(X86::XMM8);
11986      MI->addRegisterDefined(X86::XMM9);
11987      MI->addRegisterDefined(X86::XMM10);
11988      MI->addRegisterDefined(X86::XMM11);
11989      MI->addRegisterDefined(X86::XMM12);
11990      MI->addRegisterDefined(X86::XMM13);
11991      MI->addRegisterDefined(X86::XMM14);
11992      MI->addRegisterDefined(X86::XMM15);
11993    }
11994    return BB;
11995  case X86::WIN_ALLOCA:
11996    return EmitLoweredWinAlloca(MI, BB);
11997  case X86::SEG_ALLOCA_32:
11998    return EmitLoweredSegAlloca(MI, BB, false);
11999  case X86::SEG_ALLOCA_64:
12000    return EmitLoweredSegAlloca(MI, BB, true);
12001  case X86::TLSCall_32:
12002  case X86::TLSCall_64:
12003    return EmitLoweredTLSCall(MI, BB);
12004  case X86::CMOV_GR8:
12005  case X86::CMOV_FR32:
12006  case X86::CMOV_FR64:
12007  case X86::CMOV_V4F32:
12008  case X86::CMOV_V2F64:
12009  case X86::CMOV_V2I64:
12010  case X86::CMOV_V8F32:
12011  case X86::CMOV_V4F64:
12012  case X86::CMOV_V4I64:
12013  case X86::CMOV_GR16:
12014  case X86::CMOV_GR32:
12015  case X86::CMOV_RFP32:
12016  case X86::CMOV_RFP64:
12017  case X86::CMOV_RFP80:
12018    return EmitLoweredSelect(MI, BB);
12019
12020  case X86::FP32_TO_INT16_IN_MEM:
12021  case X86::FP32_TO_INT32_IN_MEM:
12022  case X86::FP32_TO_INT64_IN_MEM:
12023  case X86::FP64_TO_INT16_IN_MEM:
12024  case X86::FP64_TO_INT32_IN_MEM:
12025  case X86::FP64_TO_INT64_IN_MEM:
12026  case X86::FP80_TO_INT16_IN_MEM:
12027  case X86::FP80_TO_INT32_IN_MEM:
12028  case X86::FP80_TO_INT64_IN_MEM: {
12029    const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12030    DebugLoc DL = MI->getDebugLoc();
12031
12032    // Change the floating point control register to use "round towards zero"
12033    // mode when truncating to an integer value.
12034    MachineFunction *F = BB->getParent();
12035    int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
12036    addFrameReference(BuildMI(*BB, MI, DL,
12037                              TII->get(X86::FNSTCW16m)), CWFrameIdx);
12038
12039    // Load the old value of the high byte of the control word...
12040    unsigned OldCW =
12041      F->getRegInfo().createVirtualRegister(X86::GR16RegisterClass);
12042    addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
12043                      CWFrameIdx);
12044
12045    // Set the high part to be round to zero...
12046    addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
12047      .addImm(0xC7F);
12048
12049    // Reload the modified control word now...
12050    addFrameReference(BuildMI(*BB, MI, DL,
12051                              TII->get(X86::FLDCW16m)), CWFrameIdx);
12052
12053    // Restore the memory image of control word to original value
12054    addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
12055      .addReg(OldCW);
12056
12057    // Get the X86 opcode to use.
12058    unsigned Opc;
12059    switch (MI->getOpcode()) {
12060    default: llvm_unreachable("illegal opcode!");
12061    case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
12062    case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
12063    case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
12064    case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
12065    case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
12066    case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
12067    case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
12068    case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
12069    case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
12070    }
12071
12072    X86AddressMode AM;
12073    MachineOperand &Op = MI->getOperand(0);
12074    if (Op.isReg()) {
12075      AM.BaseType = X86AddressMode::RegBase;
12076      AM.Base.Reg = Op.getReg();
12077    } else {
12078      AM.BaseType = X86AddressMode::FrameIndexBase;
12079      AM.Base.FrameIndex = Op.getIndex();
12080    }
12081    Op = MI->getOperand(1);
12082    if (Op.isImm())
12083      AM.Scale = Op.getImm();
12084    Op = MI->getOperand(2);
12085    if (Op.isImm())
12086      AM.IndexReg = Op.getImm();
12087    Op = MI->getOperand(3);
12088    if (Op.isGlobal()) {
12089      AM.GV = Op.getGlobal();
12090    } else {
12091      AM.Disp = Op.getImm();
12092    }
12093    addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
12094                      .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
12095
12096    // Reload the original control word now.
12097    addFrameReference(BuildMI(*BB, MI, DL,
12098                              TII->get(X86::FLDCW16m)), CWFrameIdx);
12099
12100    MI->eraseFromParent();   // The pseudo instruction is gone now.
12101    return BB;
12102  }
12103    // String/text processing lowering.
12104  case X86::PCMPISTRM128REG:
12105  case X86::VPCMPISTRM128REG:
12106    return EmitPCMP(MI, BB, 3, false /* in-mem */);
12107  case X86::PCMPISTRM128MEM:
12108  case X86::VPCMPISTRM128MEM:
12109    return EmitPCMP(MI, BB, 3, true /* in-mem */);
12110  case X86::PCMPESTRM128REG:
12111  case X86::VPCMPESTRM128REG:
12112    return EmitPCMP(MI, BB, 5, false /* in mem */);
12113  case X86::PCMPESTRM128MEM:
12114  case X86::VPCMPESTRM128MEM:
12115    return EmitPCMP(MI, BB, 5, true /* in mem */);
12116
12117    // Thread synchronization.
12118  case X86::MONITOR:
12119    return EmitMonitor(MI, BB);
12120  case X86::MWAIT:
12121    return EmitMwait(MI, BB);
12122
12123    // Atomic Lowering.
12124  case X86::ATOMAND32:
12125    return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
12126                                               X86::AND32ri, X86::MOV32rm,
12127                                               X86::LCMPXCHG32,
12128                                               X86::NOT32r, X86::EAX,
12129                                               X86::GR32RegisterClass);
12130  case X86::ATOMOR32:
12131    return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR32rr,
12132                                               X86::OR32ri, X86::MOV32rm,
12133                                               X86::LCMPXCHG32,
12134                                               X86::NOT32r, X86::EAX,
12135                                               X86::GR32RegisterClass);
12136  case X86::ATOMXOR32:
12137    return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR32rr,
12138                                               X86::XOR32ri, X86::MOV32rm,
12139                                               X86::LCMPXCHG32,
12140                                               X86::NOT32r, X86::EAX,
12141                                               X86::GR32RegisterClass);
12142  case X86::ATOMNAND32:
12143    return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
12144                                               X86::AND32ri, X86::MOV32rm,
12145                                               X86::LCMPXCHG32,
12146                                               X86::NOT32r, X86::EAX,
12147                                               X86::GR32RegisterClass, true);
12148  case X86::ATOMMIN32:
12149    return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL32rr);
12150  case X86::ATOMMAX32:
12151    return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG32rr);
12152  case X86::ATOMUMIN32:
12153    return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB32rr);
12154  case X86::ATOMUMAX32:
12155    return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA32rr);
12156
12157  case X86::ATOMAND16:
12158    return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
12159                                               X86::AND16ri, X86::MOV16rm,
12160                                               X86::LCMPXCHG16,
12161                                               X86::NOT16r, X86::AX,
12162                                               X86::GR16RegisterClass);
12163  case X86::ATOMOR16:
12164    return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR16rr,
12165                                               X86::OR16ri, X86::MOV16rm,
12166                                               X86::LCMPXCHG16,
12167                                               X86::NOT16r, X86::AX,
12168                                               X86::GR16RegisterClass);
12169  case X86::ATOMXOR16:
12170    return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR16rr,
12171                                               X86::XOR16ri, X86::MOV16rm,
12172                                               X86::LCMPXCHG16,
12173                                               X86::NOT16r, X86::AX,
12174                                               X86::GR16RegisterClass);
12175  case X86::ATOMNAND16:
12176    return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
12177                                               X86::AND16ri, X86::MOV16rm,
12178                                               X86::LCMPXCHG16,
12179                                               X86::NOT16r, X86::AX,
12180                                               X86::GR16RegisterClass, true);
12181  case X86::ATOMMIN16:
12182    return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL16rr);
12183  case X86::ATOMMAX16:
12184    return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG16rr);
12185  case X86::ATOMUMIN16:
12186    return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB16rr);
12187  case X86::ATOMUMAX16:
12188    return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA16rr);
12189
12190  case X86::ATOMAND8:
12191    return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
12192                                               X86::AND8ri, X86::MOV8rm,
12193                                               X86::LCMPXCHG8,
12194                                               X86::NOT8r, X86::AL,
12195                                               X86::GR8RegisterClass);
12196  case X86::ATOMOR8:
12197    return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR8rr,
12198                                               X86::OR8ri, X86::MOV8rm,
12199                                               X86::LCMPXCHG8,
12200                                               X86::NOT8r, X86::AL,
12201                                               X86::GR8RegisterClass);
12202  case X86::ATOMXOR8:
12203    return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR8rr,
12204                                               X86::XOR8ri, X86::MOV8rm,
12205                                               X86::LCMPXCHG8,
12206                                               X86::NOT8r, X86::AL,
12207                                               X86::GR8RegisterClass);
12208  case X86::ATOMNAND8:
12209    return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
12210                                               X86::AND8ri, X86::MOV8rm,
12211                                               X86::LCMPXCHG8,
12212                                               X86::NOT8r, X86::AL,
12213                                               X86::GR8RegisterClass, true);
12214  // FIXME: There are no CMOV8 instructions; MIN/MAX need some other way.
12215  // This group is for 64-bit host.
12216  case X86::ATOMAND64:
12217    return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
12218                                               X86::AND64ri32, X86::MOV64rm,
12219                                               X86::LCMPXCHG64,
12220                                               X86::NOT64r, X86::RAX,
12221                                               X86::GR64RegisterClass);
12222  case X86::ATOMOR64:
12223    return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR64rr,
12224                                               X86::OR64ri32, X86::MOV64rm,
12225                                               X86::LCMPXCHG64,
12226                                               X86::NOT64r, X86::RAX,
12227                                               X86::GR64RegisterClass);
12228  case X86::ATOMXOR64:
12229    return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR64rr,
12230                                               X86::XOR64ri32, X86::MOV64rm,
12231                                               X86::LCMPXCHG64,
12232                                               X86::NOT64r, X86::RAX,
12233                                               X86::GR64RegisterClass);
12234  case X86::ATOMNAND64:
12235    return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
12236                                               X86::AND64ri32, X86::MOV64rm,
12237                                               X86::LCMPXCHG64,
12238                                               X86::NOT64r, X86::RAX,
12239                                               X86::GR64RegisterClass, true);
12240  case X86::ATOMMIN64:
12241    return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL64rr);
12242  case X86::ATOMMAX64:
12243    return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG64rr);
12244  case X86::ATOMUMIN64:
12245    return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB64rr);
12246  case X86::ATOMUMAX64:
12247    return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA64rr);
12248
12249  // This group does 64-bit operations on a 32-bit host.
12250  case X86::ATOMAND6432:
12251    return EmitAtomicBit6432WithCustomInserter(MI, BB,
12252                                               X86::AND32rr, X86::AND32rr,
12253                                               X86::AND32ri, X86::AND32ri,
12254                                               false);
12255  case X86::ATOMOR6432:
12256    return EmitAtomicBit6432WithCustomInserter(MI, BB,
12257                                               X86::OR32rr, X86::OR32rr,
12258                                               X86::OR32ri, X86::OR32ri,
12259                                               false);
12260  case X86::ATOMXOR6432:
12261    return EmitAtomicBit6432WithCustomInserter(MI, BB,
12262                                               X86::XOR32rr, X86::XOR32rr,
12263                                               X86::XOR32ri, X86::XOR32ri,
12264                                               false);
12265  case X86::ATOMNAND6432:
12266    return EmitAtomicBit6432WithCustomInserter(MI, BB,
12267                                               X86::AND32rr, X86::AND32rr,
12268                                               X86::AND32ri, X86::AND32ri,
12269                                               true);
12270  case X86::ATOMADD6432:
12271    return EmitAtomicBit6432WithCustomInserter(MI, BB,
12272                                               X86::ADD32rr, X86::ADC32rr,
12273                                               X86::ADD32ri, X86::ADC32ri,
12274                                               false);
12275  case X86::ATOMSUB6432:
12276    return EmitAtomicBit6432WithCustomInserter(MI, BB,
12277                                               X86::SUB32rr, X86::SBB32rr,
12278                                               X86::SUB32ri, X86::SBB32ri,
12279                                               false);
12280  case X86::ATOMSWAP6432:
12281    return EmitAtomicBit6432WithCustomInserter(MI, BB,
12282                                               X86::MOV32rr, X86::MOV32rr,
12283                                               X86::MOV32ri, X86::MOV32ri,
12284                                               false);
12285  case X86::VASTART_SAVE_XMM_REGS:
12286    return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
12287
12288  case X86::VAARG_64:
12289    return EmitVAARG64WithCustomInserter(MI, BB);
12290  }
12291}
12292
12293//===----------------------------------------------------------------------===//
12294//                           X86 Optimization Hooks
12295//===----------------------------------------------------------------------===//
12296
12297void X86TargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
12298                                                       const APInt &Mask,
12299                                                       APInt &KnownZero,
12300                                                       APInt &KnownOne,
12301                                                       const SelectionDAG &DAG,
12302                                                       unsigned Depth) const {
12303  unsigned Opc = Op.getOpcode();
12304  assert((Opc >= ISD::BUILTIN_OP_END ||
12305          Opc == ISD::INTRINSIC_WO_CHAIN ||
12306          Opc == ISD::INTRINSIC_W_CHAIN ||
12307          Opc == ISD::INTRINSIC_VOID) &&
12308         "Should use MaskedValueIsZero if you don't know whether Op"
12309         " is a target node!");
12310
12311  KnownZero = KnownOne = APInt(Mask.getBitWidth(), 0);   // Don't know anything.
12312  switch (Opc) {
12313  default: break;
12314  case X86ISD::ADD:
12315  case X86ISD::SUB:
12316  case X86ISD::ADC:
12317  case X86ISD::SBB:
12318  case X86ISD::SMUL:
12319  case X86ISD::UMUL:
12320  case X86ISD::INC:
12321  case X86ISD::DEC:
12322  case X86ISD::OR:
12323  case X86ISD::XOR:
12324  case X86ISD::AND:
12325    // These nodes' second result is a boolean.
12326    if (Op.getResNo() == 0)
12327      break;
12328    // Fallthrough
12329  case X86ISD::SETCC:
12330    KnownZero |= APInt::getHighBitsSet(Mask.getBitWidth(),
12331                                       Mask.getBitWidth() - 1);
12332    break;
12333  case ISD::INTRINSIC_WO_CHAIN: {
12334    unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
12335    unsigned NumLoBits = 0;
12336    switch (IntId) {
12337    default: break;
12338    case Intrinsic::x86_sse_movmsk_ps:
12339    case Intrinsic::x86_avx_movmsk_ps_256:
12340    case Intrinsic::x86_sse2_movmsk_pd:
12341    case Intrinsic::x86_avx_movmsk_pd_256:
12342    case Intrinsic::x86_mmx_pmovmskb:
12343    case Intrinsic::x86_sse2_pmovmskb_128: {
12344      // High bits of movmskp{s|d}, pmovmskb are known zero.
12345      switch (IntId) {
12346        case Intrinsic::x86_sse_movmsk_ps:      NumLoBits = 4; break;
12347        case Intrinsic::x86_avx_movmsk_ps_256:  NumLoBits = 8; break;
12348        case Intrinsic::x86_sse2_movmsk_pd:     NumLoBits = 2; break;
12349        case Intrinsic::x86_avx_movmsk_pd_256:  NumLoBits = 4; break;
12350        case Intrinsic::x86_mmx_pmovmskb:       NumLoBits = 8; break;
12351        case Intrinsic::x86_sse2_pmovmskb_128:  NumLoBits = 16; break;
12352      }
12353      KnownZero = APInt::getHighBitsSet(Mask.getBitWidth(),
12354                                        Mask.getBitWidth() - NumLoBits);
12355      break;
12356    }
12357    }
12358    break;
12359  }
12360  }
12361}
12362
12363unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(SDValue Op,
12364                                                         unsigned Depth) const {
12365  // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
12366  if (Op.getOpcode() == X86ISD::SETCC_CARRY)
12367    return Op.getValueType().getScalarType().getSizeInBits();
12368
12369  // Fallback case.
12370  return 1;
12371}
12372
12373/// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
12374/// node is a GlobalAddress + offset.
12375bool X86TargetLowering::isGAPlusOffset(SDNode *N,
12376                                       const GlobalValue* &GA,
12377                                       int64_t &Offset) const {
12378  if (N->getOpcode() == X86ISD::Wrapper) {
12379    if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
12380      GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
12381      Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
12382      return true;
12383    }
12384  }
12385  return TargetLowering::isGAPlusOffset(N, GA, Offset);
12386}
12387
12388/// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the
12389/// same as extracting the high 128-bit part of 256-bit vector and then
12390/// inserting the result into the low part of a new 256-bit vector
12391static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) {
12392  EVT VT = SVOp->getValueType(0);
12393  int NumElems = VT.getVectorNumElements();
12394
12395  // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
12396  for (int i = 0, j = NumElems/2; i < NumElems/2; ++i, ++j)
12397    if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
12398        SVOp->getMaskElt(j) >= 0)
12399      return false;
12400
12401  return true;
12402}
12403
12404/// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the
12405/// same as extracting the low 128-bit part of 256-bit vector and then
12406/// inserting the result into the high part of a new 256-bit vector
12407static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) {
12408  EVT VT = SVOp->getValueType(0);
12409  int NumElems = VT.getVectorNumElements();
12410
12411  // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
12412  for (int i = NumElems/2, j = 0; i < NumElems; ++i, ++j)
12413    if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
12414        SVOp->getMaskElt(j) >= 0)
12415      return false;
12416
12417  return true;
12418}
12419
12420/// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
12421static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
12422                                        TargetLowering::DAGCombinerInfo &DCI) {
12423  DebugLoc dl = N->getDebugLoc();
12424  ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
12425  SDValue V1 = SVOp->getOperand(0);
12426  SDValue V2 = SVOp->getOperand(1);
12427  EVT VT = SVOp->getValueType(0);
12428  int NumElems = VT.getVectorNumElements();
12429
12430  if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
12431      V2.getOpcode() == ISD::CONCAT_VECTORS) {
12432    //
12433    //                   0,0,0,...
12434    //                      |
12435    //    V      UNDEF    BUILD_VECTOR    UNDEF
12436    //     \      /           \           /
12437    //  CONCAT_VECTOR         CONCAT_VECTOR
12438    //         \                  /
12439    //          \                /
12440    //          RESULT: V + zero extended
12441    //
12442    if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
12443        V2.getOperand(1).getOpcode() != ISD::UNDEF ||
12444        V1.getOperand(1).getOpcode() != ISD::UNDEF)
12445      return SDValue();
12446
12447    if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
12448      return SDValue();
12449
12450    // To match the shuffle mask, the first half of the mask should
12451    // be exactly the first vector, and all the rest a splat with the
12452    // first element of the second one.
12453    for (int i = 0; i < NumElems/2; ++i)
12454      if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
12455          !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
12456        return SDValue();
12457
12458    // Emit a zeroed vector and insert the desired subvector on its
12459    // first half.
12460    SDValue Zeros = getZeroVector(VT, true /* HasXMMInt */, DAG, dl);
12461    SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0),
12462                         DAG.getConstant(0, MVT::i32), DAG, dl);
12463    return DCI.CombineTo(N, InsV);
12464  }
12465
12466  //===--------------------------------------------------------------------===//
12467  // Combine some shuffles into subvector extracts and inserts:
12468  //
12469
12470  // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
12471  if (isShuffleHigh128VectorInsertLow(SVOp)) {
12472    SDValue V = Extract128BitVector(V1, DAG.getConstant(NumElems/2, MVT::i32),
12473                                    DAG, dl);
12474    SDValue InsV = Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, VT),
12475                                      V, DAG.getConstant(0, MVT::i32), DAG, dl);
12476    return DCI.CombineTo(N, InsV);
12477  }
12478
12479  // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
12480  if (isShuffleLow128VectorInsertHigh(SVOp)) {
12481    SDValue V = Extract128BitVector(V1, DAG.getConstant(0, MVT::i32), DAG, dl);
12482    SDValue InsV = Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, VT),
12483                             V, DAG.getConstant(NumElems/2, MVT::i32), DAG, dl);
12484    return DCI.CombineTo(N, InsV);
12485  }
12486
12487  return SDValue();
12488}
12489
12490/// PerformShuffleCombine - Performs several different shuffle combines.
12491static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
12492                                     TargetLowering::DAGCombinerInfo &DCI,
12493                                     const X86Subtarget *Subtarget) {
12494  DebugLoc dl = N->getDebugLoc();
12495  EVT VT = N->getValueType(0);
12496
12497  // Don't create instructions with illegal types after legalize types has run.
12498  const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12499  if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
12500    return SDValue();
12501
12502  // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
12503  if (Subtarget->hasAVX() && VT.getSizeInBits() == 256 &&
12504      N->getOpcode() == ISD::VECTOR_SHUFFLE)
12505    return PerformShuffleCombine256(N, DAG, DCI);
12506
12507  // Only handle 128 wide vector from here on.
12508  if (VT.getSizeInBits() != 128)
12509    return SDValue();
12510
12511  // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
12512  // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
12513  // consecutive, non-overlapping, and in the right order.
12514  SmallVector<SDValue, 16> Elts;
12515  for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
12516    Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
12517
12518  return EltsFromConsecutiveLoads(VT, Elts, dl, DAG);
12519}
12520
12521/// \brief Detect bitcasts between i32 to x86mmx low word. Since MMX types are
12522/// special and don't usually play with other vector types, it's better to
12523/// handle them early to be sure we emit efficient code by avoiding
12524/// store-load conversions.
12525static SDValue PerformBITCASTCombine(SDNode *N, SelectionDAG &DAG) {
12526  if (N->getValueType(0) != MVT::x86mmx ||
12527      N->getOperand(0)->getOpcode() != ISD::BUILD_VECTOR ||
12528      N->getOperand(0)->getValueType(0) != MVT::v2i32)
12529    return SDValue();
12530
12531  SDValue V = N->getOperand(0);
12532  ConstantSDNode *C = dyn_cast<ConstantSDNode>(V.getOperand(1));
12533  if (C && C->getZExtValue() == 0 && V.getOperand(0).getValueType() == MVT::i32)
12534    return DAG.getNode(X86ISD::MMX_MOVW2D, V.getOperand(0).getDebugLoc(),
12535                       N->getValueType(0), V.getOperand(0));
12536
12537  return SDValue();
12538}
12539
12540/// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
12541/// generation and convert it from being a bunch of shuffles and extracts
12542/// to a simple store and scalar loads to extract the elements.
12543static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
12544                                                const TargetLowering &TLI) {
12545  SDValue InputVector = N->getOperand(0);
12546  // Detect whether we are trying to convert from mmx to i32 and the bitcast
12547  // from mmx to v2i32 has a single usage.
12548  if (InputVector.getNode()->getOpcode() == llvm::ISD::BITCAST &&
12549      InputVector.getNode()->getOperand(0).getValueType() == MVT::x86mmx &&
12550      InputVector.hasOneUse() && N->getValueType(0) == MVT::i32)
12551    return DAG.getNode(X86ISD::MMX_MOVD2W, InputVector.getDebugLoc(),
12552                       N->getValueType(0),
12553                       InputVector.getNode()->getOperand(0));
12554
12555  // Only operate on vectors of 4 elements, where the alternative shuffling
12556  // gets to be more expensive.
12557  if (InputVector.getValueType() != MVT::v4i32)
12558    return SDValue();
12559
12560  // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
12561  // single use which is a sign-extend or zero-extend, and all elements are
12562  // used.
12563  SmallVector<SDNode *, 4> Uses;
12564  unsigned ExtractedElements = 0;
12565  for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
12566       UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
12567    if (UI.getUse().getResNo() != InputVector.getResNo())
12568      return SDValue();
12569
12570    SDNode *Extract = *UI;
12571    if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
12572      return SDValue();
12573
12574    if (Extract->getValueType(0) != MVT::i32)
12575      return SDValue();
12576    if (!Extract->hasOneUse())
12577      return SDValue();
12578    if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
12579        Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
12580      return SDValue();
12581    if (!isa<ConstantSDNode>(Extract->getOperand(1)))
12582      return SDValue();
12583
12584    // Record which element was extracted.
12585    ExtractedElements |=
12586      1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
12587
12588    Uses.push_back(Extract);
12589  }
12590
12591  // If not all the elements were used, this may not be worthwhile.
12592  if (ExtractedElements != 15)
12593    return SDValue();
12594
12595  // Ok, we've now decided to do the transformation.
12596  DebugLoc dl = InputVector.getDebugLoc();
12597
12598  // Store the value to a temporary stack slot.
12599  SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
12600  SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
12601                            MachinePointerInfo(), false, false, 0);
12602
12603  // Replace each use (extract) with a load of the appropriate element.
12604  for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
12605       UE = Uses.end(); UI != UE; ++UI) {
12606    SDNode *Extract = *UI;
12607
12608    // cOMpute the element's address.
12609    SDValue Idx = Extract->getOperand(1);
12610    unsigned EltSize =
12611        InputVector.getValueType().getVectorElementType().getSizeInBits()/8;
12612    uint64_t Offset = EltSize * cast<ConstantSDNode>(Idx)->getZExtValue();
12613    SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy());
12614
12615    SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(),
12616                                     StackPtr, OffsetVal);
12617
12618    // Load the scalar.
12619    SDValue LoadScalar = DAG.getLoad(Extract->getValueType(0), dl, Ch,
12620                                     ScalarAddr, MachinePointerInfo(),
12621                                     false, false, 0);
12622
12623    // Replace the exact with the load.
12624    DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), LoadScalar);
12625  }
12626
12627  // The replacement was made in place; don't return anything.
12628  return SDValue();
12629}
12630
12631/// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
12632/// nodes.
12633static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
12634                                    const X86Subtarget *Subtarget) {
12635  DebugLoc DL = N->getDebugLoc();
12636  SDValue Cond = N->getOperand(0);
12637  // Get the LHS/RHS of the select.
12638  SDValue LHS = N->getOperand(1);
12639  SDValue RHS = N->getOperand(2);
12640  EVT VT = LHS.getValueType();
12641
12642  // If we have SSE[12] support, try to form min/max nodes. SSE min/max
12643  // instructions match the semantics of the common C idiom x<y?x:y but not
12644  // x<=y?x:y, because of how they handle negative zero (which can be
12645  // ignored in unsafe-math mode).
12646  if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
12647      VT != MVT::f80 && DAG.getTargetLoweringInfo().isTypeLegal(VT) &&
12648      (Subtarget->hasXMMInt() ||
12649       (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
12650    ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
12651
12652    unsigned Opcode = 0;
12653    // Check for x CC y ? x : y.
12654    if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
12655        DAG.isEqualTo(RHS, Cond.getOperand(1))) {
12656      switch (CC) {
12657      default: break;
12658      case ISD::SETULT:
12659        // Converting this to a min would handle NaNs incorrectly, and swapping
12660        // the operands would cause it to handle comparisons between positive
12661        // and negative zero incorrectly.
12662        if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
12663          if (!UnsafeFPMath &&
12664              !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
12665            break;
12666          std::swap(LHS, RHS);
12667        }
12668        Opcode = X86ISD::FMIN;
12669        break;
12670      case ISD::SETOLE:
12671        // Converting this to a min would handle comparisons between positive
12672        // and negative zero incorrectly.
12673        if (!UnsafeFPMath &&
12674            !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
12675          break;
12676        Opcode = X86ISD::FMIN;
12677        break;
12678      case ISD::SETULE:
12679        // Converting this to a min would handle both negative zeros and NaNs
12680        // incorrectly, but we can swap the operands to fix both.
12681        std::swap(LHS, RHS);
12682      case ISD::SETOLT:
12683      case ISD::SETLT:
12684      case ISD::SETLE:
12685        Opcode = X86ISD::FMIN;
12686        break;
12687
12688      case ISD::SETOGE:
12689        // Converting this to a max would handle comparisons between positive
12690        // and negative zero incorrectly.
12691        if (!UnsafeFPMath &&
12692            !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
12693          break;
12694        Opcode = X86ISD::FMAX;
12695        break;
12696      case ISD::SETUGT:
12697        // Converting this to a max would handle NaNs incorrectly, and swapping
12698        // the operands would cause it to handle comparisons between positive
12699        // and negative zero incorrectly.
12700        if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
12701          if (!UnsafeFPMath &&
12702              !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
12703            break;
12704          std::swap(LHS, RHS);
12705        }
12706        Opcode = X86ISD::FMAX;
12707        break;
12708      case ISD::SETUGE:
12709        // Converting this to a max would handle both negative zeros and NaNs
12710        // incorrectly, but we can swap the operands to fix both.
12711        std::swap(LHS, RHS);
12712      case ISD::SETOGT:
12713      case ISD::SETGT:
12714      case ISD::SETGE:
12715        Opcode = X86ISD::FMAX;
12716        break;
12717      }
12718    // Check for x CC y ? y : x -- a min/max with reversed arms.
12719    } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
12720               DAG.isEqualTo(RHS, Cond.getOperand(0))) {
12721      switch (CC) {
12722      default: break;
12723      case ISD::SETOGE:
12724        // Converting this to a min would handle comparisons between positive
12725        // and negative zero incorrectly, and swapping the operands would
12726        // cause it to handle NaNs incorrectly.
12727        if (!UnsafeFPMath &&
12728            !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
12729          if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
12730            break;
12731          std::swap(LHS, RHS);
12732        }
12733        Opcode = X86ISD::FMIN;
12734        break;
12735      case ISD::SETUGT:
12736        // Converting this to a min would handle NaNs incorrectly.
12737        if (!UnsafeFPMath &&
12738            (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
12739          break;
12740        Opcode = X86ISD::FMIN;
12741        break;
12742      case ISD::SETUGE:
12743        // Converting this to a min would handle both negative zeros and NaNs
12744        // incorrectly, but we can swap the operands to fix both.
12745        std::swap(LHS, RHS);
12746      case ISD::SETOGT:
12747      case ISD::SETGT:
12748      case ISD::SETGE:
12749        Opcode = X86ISD::FMIN;
12750        break;
12751
12752      case ISD::SETULT:
12753        // Converting this to a max would handle NaNs incorrectly.
12754        if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
12755          break;
12756        Opcode = X86ISD::FMAX;
12757        break;
12758      case ISD::SETOLE:
12759        // Converting this to a max would handle comparisons between positive
12760        // and negative zero incorrectly, and swapping the operands would
12761        // cause it to handle NaNs incorrectly.
12762        if (!UnsafeFPMath &&
12763            !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
12764          if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
12765            break;
12766          std::swap(LHS, RHS);
12767        }
12768        Opcode = X86ISD::FMAX;
12769        break;
12770      case ISD::SETULE:
12771        // Converting this to a max would handle both negative zeros and NaNs
12772        // incorrectly, but we can swap the operands to fix both.
12773        std::swap(LHS, RHS);
12774      case ISD::SETOLT:
12775      case ISD::SETLT:
12776      case ISD::SETLE:
12777        Opcode = X86ISD::FMAX;
12778        break;
12779      }
12780    }
12781
12782    if (Opcode)
12783      return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
12784  }
12785
12786  // If this is a select between two integer constants, try to do some
12787  // optimizations.
12788  if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
12789    if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
12790      // Don't do this for crazy integer types.
12791      if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
12792        // If this is efficiently invertible, canonicalize the LHSC/RHSC values
12793        // so that TrueC (the true value) is larger than FalseC.
12794        bool NeedsCondInvert = false;
12795
12796        if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
12797            // Efficiently invertible.
12798            (Cond.getOpcode() == ISD::SETCC ||  // setcc -> invertible.
12799             (Cond.getOpcode() == ISD::XOR &&   // xor(X, C) -> invertible.
12800              isa<ConstantSDNode>(Cond.getOperand(1))))) {
12801          NeedsCondInvert = true;
12802          std::swap(TrueC, FalseC);
12803        }
12804
12805        // Optimize C ? 8 : 0 -> zext(C) << 3.  Likewise for any pow2/0.
12806        if (FalseC->getAPIntValue() == 0 &&
12807            TrueC->getAPIntValue().isPowerOf2()) {
12808          if (NeedsCondInvert) // Invert the condition if needed.
12809            Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
12810                               DAG.getConstant(1, Cond.getValueType()));
12811
12812          // Zero extend the condition if needed.
12813          Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
12814
12815          unsigned ShAmt = TrueC->getAPIntValue().logBase2();
12816          return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
12817                             DAG.getConstant(ShAmt, MVT::i8));
12818        }
12819
12820        // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
12821        if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
12822          if (NeedsCondInvert) // Invert the condition if needed.
12823            Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
12824                               DAG.getConstant(1, Cond.getValueType()));
12825
12826          // Zero extend the condition if needed.
12827          Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
12828                             FalseC->getValueType(0), Cond);
12829          return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
12830                             SDValue(FalseC, 0));
12831        }
12832
12833        // Optimize cases that will turn into an LEA instruction.  This requires
12834        // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
12835        if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
12836          uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
12837          if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
12838
12839          bool isFastMultiplier = false;
12840          if (Diff < 10) {
12841            switch ((unsigned char)Diff) {
12842              default: break;
12843              case 1:  // result = add base, cond
12844              case 2:  // result = lea base(    , cond*2)
12845              case 3:  // result = lea base(cond, cond*2)
12846              case 4:  // result = lea base(    , cond*4)
12847              case 5:  // result = lea base(cond, cond*4)
12848              case 8:  // result = lea base(    , cond*8)
12849              case 9:  // result = lea base(cond, cond*8)
12850                isFastMultiplier = true;
12851                break;
12852            }
12853          }
12854
12855          if (isFastMultiplier) {
12856            APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
12857            if (NeedsCondInvert) // Invert the condition if needed.
12858              Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
12859                                 DAG.getConstant(1, Cond.getValueType()));
12860
12861            // Zero extend the condition if needed.
12862            Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
12863                               Cond);
12864            // Scale the condition by the difference.
12865            if (Diff != 1)
12866              Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
12867                                 DAG.getConstant(Diff, Cond.getValueType()));
12868
12869            // Add the base if non-zero.
12870            if (FalseC->getAPIntValue() != 0)
12871              Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
12872                                 SDValue(FalseC, 0));
12873            return Cond;
12874          }
12875        }
12876      }
12877  }
12878
12879  return SDValue();
12880}
12881
12882/// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
12883static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
12884                                  TargetLowering::DAGCombinerInfo &DCI) {
12885  DebugLoc DL = N->getDebugLoc();
12886
12887  // If the flag operand isn't dead, don't touch this CMOV.
12888  if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
12889    return SDValue();
12890
12891  SDValue FalseOp = N->getOperand(0);
12892  SDValue TrueOp = N->getOperand(1);
12893  X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
12894  SDValue Cond = N->getOperand(3);
12895  if (CC == X86::COND_E || CC == X86::COND_NE) {
12896    switch (Cond.getOpcode()) {
12897    default: break;
12898    case X86ISD::BSR:
12899    case X86ISD::BSF:
12900      // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
12901      if (DAG.isKnownNeverZero(Cond.getOperand(0)))
12902        return (CC == X86::COND_E) ? FalseOp : TrueOp;
12903    }
12904  }
12905
12906  // If this is a select between two integer constants, try to do some
12907  // optimizations.  Note that the operands are ordered the opposite of SELECT
12908  // operands.
12909  if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
12910    if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
12911      // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
12912      // larger than FalseC (the false value).
12913      if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
12914        CC = X86::GetOppositeBranchCondition(CC);
12915        std::swap(TrueC, FalseC);
12916      }
12917
12918      // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3.  Likewise for any pow2/0.
12919      // This is efficient for any integer data type (including i8/i16) and
12920      // shift amount.
12921      if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
12922        Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
12923                           DAG.getConstant(CC, MVT::i8), Cond);
12924
12925        // Zero extend the condition if needed.
12926        Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
12927
12928        unsigned ShAmt = TrueC->getAPIntValue().logBase2();
12929        Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
12930                           DAG.getConstant(ShAmt, MVT::i8));
12931        if (N->getNumValues() == 2)  // Dead flag value?
12932          return DCI.CombineTo(N, Cond, SDValue());
12933        return Cond;
12934      }
12935
12936      // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.  This is efficient
12937      // for any integer data type, including i8/i16.
12938      if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
12939        Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
12940                           DAG.getConstant(CC, MVT::i8), Cond);
12941
12942        // Zero extend the condition if needed.
12943        Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
12944                           FalseC->getValueType(0), Cond);
12945        Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
12946                           SDValue(FalseC, 0));
12947
12948        if (N->getNumValues() == 2)  // Dead flag value?
12949          return DCI.CombineTo(N, Cond, SDValue());
12950        return Cond;
12951      }
12952
12953      // Optimize cases that will turn into an LEA instruction.  This requires
12954      // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
12955      if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
12956        uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
12957        if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
12958
12959        bool isFastMultiplier = false;
12960        if (Diff < 10) {
12961          switch ((unsigned char)Diff) {
12962          default: break;
12963          case 1:  // result = add base, cond
12964          case 2:  // result = lea base(    , cond*2)
12965          case 3:  // result = lea base(cond, cond*2)
12966          case 4:  // result = lea base(    , cond*4)
12967          case 5:  // result = lea base(cond, cond*4)
12968          case 8:  // result = lea base(    , cond*8)
12969          case 9:  // result = lea base(cond, cond*8)
12970            isFastMultiplier = true;
12971            break;
12972          }
12973        }
12974
12975        if (isFastMultiplier) {
12976          APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
12977          Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
12978                             DAG.getConstant(CC, MVT::i8), Cond);
12979          // Zero extend the condition if needed.
12980          Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
12981                             Cond);
12982          // Scale the condition by the difference.
12983          if (Diff != 1)
12984            Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
12985                               DAG.getConstant(Diff, Cond.getValueType()));
12986
12987          // Add the base if non-zero.
12988          if (FalseC->getAPIntValue() != 0)
12989            Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
12990                               SDValue(FalseC, 0));
12991          if (N->getNumValues() == 2)  // Dead flag value?
12992            return DCI.CombineTo(N, Cond, SDValue());
12993          return Cond;
12994        }
12995      }
12996    }
12997  }
12998  return SDValue();
12999}
13000
13001
13002/// PerformMulCombine - Optimize a single multiply with constant into two
13003/// in order to implement it with two cheaper instructions, e.g.
13004/// LEA + SHL, LEA + LEA.
13005static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
13006                                 TargetLowering::DAGCombinerInfo &DCI) {
13007  if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
13008    return SDValue();
13009
13010  EVT VT = N->getValueType(0);
13011  if (VT != MVT::i64)
13012    return SDValue();
13013
13014  ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
13015  if (!C)
13016    return SDValue();
13017  uint64_t MulAmt = C->getZExtValue();
13018  if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
13019    return SDValue();
13020
13021  uint64_t MulAmt1 = 0;
13022  uint64_t MulAmt2 = 0;
13023  if ((MulAmt % 9) == 0) {
13024    MulAmt1 = 9;
13025    MulAmt2 = MulAmt / 9;
13026  } else if ((MulAmt % 5) == 0) {
13027    MulAmt1 = 5;
13028    MulAmt2 = MulAmt / 5;
13029  } else if ((MulAmt % 3) == 0) {
13030    MulAmt1 = 3;
13031    MulAmt2 = MulAmt / 3;
13032  }
13033  if (MulAmt2 &&
13034      (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
13035    DebugLoc DL = N->getDebugLoc();
13036
13037    if (isPowerOf2_64(MulAmt2) &&
13038        !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
13039      // If second multiplifer is pow2, issue it first. We want the multiply by
13040      // 3, 5, or 9 to be folded into the addressing mode unless the lone use
13041      // is an add.
13042      std::swap(MulAmt1, MulAmt2);
13043
13044    SDValue NewMul;
13045    if (isPowerOf2_64(MulAmt1))
13046      NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
13047                           DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
13048    else
13049      NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
13050                           DAG.getConstant(MulAmt1, VT));
13051
13052    if (isPowerOf2_64(MulAmt2))
13053      NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
13054                           DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
13055    else
13056      NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
13057                           DAG.getConstant(MulAmt2, VT));
13058
13059    // Do not add new nodes to DAG combiner worklist.
13060    DCI.CombineTo(N, NewMul, false);
13061  }
13062  return SDValue();
13063}
13064
13065static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
13066  SDValue N0 = N->getOperand(0);
13067  SDValue N1 = N->getOperand(1);
13068  ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
13069  EVT VT = N0.getValueType();
13070
13071  // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
13072  // since the result of setcc_c is all zero's or all ones.
13073  if (N1C && N0.getOpcode() == ISD::AND &&
13074      N0.getOperand(1).getOpcode() == ISD::Constant) {
13075    SDValue N00 = N0.getOperand(0);
13076    if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
13077        ((N00.getOpcode() == ISD::ANY_EXTEND ||
13078          N00.getOpcode() == ISD::ZERO_EXTEND) &&
13079         N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
13080      APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
13081      APInt ShAmt = N1C->getAPIntValue();
13082      Mask = Mask.shl(ShAmt);
13083      if (Mask != 0)
13084        return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
13085                           N00, DAG.getConstant(Mask, VT));
13086    }
13087  }
13088
13089  return SDValue();
13090}
13091
13092/// PerformShiftCombine - Transforms vector shift nodes to use vector shifts
13093///                       when possible.
13094static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
13095                                   const X86Subtarget *Subtarget) {
13096  EVT VT = N->getValueType(0);
13097  if (!VT.isVector() && VT.isInteger() &&
13098      N->getOpcode() == ISD::SHL)
13099    return PerformSHLCombine(N, DAG);
13100
13101  // On X86 with SSE2 support, we can transform this to a vector shift if
13102  // all elements are shifted by the same amount.  We can't do this in legalize
13103  // because the a constant vector is typically transformed to a constant pool
13104  // so we have no knowledge of the shift amount.
13105  if (!Subtarget->hasXMMInt())
13106    return SDValue();
13107
13108  if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16)
13109    return SDValue();
13110
13111  SDValue ShAmtOp = N->getOperand(1);
13112  EVT EltVT = VT.getVectorElementType();
13113  DebugLoc DL = N->getDebugLoc();
13114  SDValue BaseShAmt = SDValue();
13115  if (ShAmtOp.getOpcode() == ISD::BUILD_VECTOR) {
13116    unsigned NumElts = VT.getVectorNumElements();
13117    unsigned i = 0;
13118    for (; i != NumElts; ++i) {
13119      SDValue Arg = ShAmtOp.getOperand(i);
13120      if (Arg.getOpcode() == ISD::UNDEF) continue;
13121      BaseShAmt = Arg;
13122      break;
13123    }
13124    for (; i != NumElts; ++i) {
13125      SDValue Arg = ShAmtOp.getOperand(i);
13126      if (Arg.getOpcode() == ISD::UNDEF) continue;
13127      if (Arg != BaseShAmt) {
13128        return SDValue();
13129      }
13130    }
13131  } else if (ShAmtOp.getOpcode() == ISD::VECTOR_SHUFFLE &&
13132             cast<ShuffleVectorSDNode>(ShAmtOp)->isSplat()) {
13133    SDValue InVec = ShAmtOp.getOperand(0);
13134    if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
13135      unsigned NumElts = InVec.getValueType().getVectorNumElements();
13136      unsigned i = 0;
13137      for (; i != NumElts; ++i) {
13138        SDValue Arg = InVec.getOperand(i);
13139        if (Arg.getOpcode() == ISD::UNDEF) continue;
13140        BaseShAmt = Arg;
13141        break;
13142      }
13143    } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
13144       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
13145         unsigned SplatIdx= cast<ShuffleVectorSDNode>(ShAmtOp)->getSplatIndex();
13146         if (C->getZExtValue() == SplatIdx)
13147           BaseShAmt = InVec.getOperand(1);
13148       }
13149    }
13150    if (BaseShAmt.getNode() == 0)
13151      BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, ShAmtOp,
13152                              DAG.getIntPtrConstant(0));
13153  } else
13154    return SDValue();
13155
13156  // The shift amount is an i32.
13157  if (EltVT.bitsGT(MVT::i32))
13158    BaseShAmt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, BaseShAmt);
13159  else if (EltVT.bitsLT(MVT::i32))
13160    BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, BaseShAmt);
13161
13162  // The shift amount is identical so we can do a vector shift.
13163  SDValue  ValOp = N->getOperand(0);
13164  switch (N->getOpcode()) {
13165  default:
13166    llvm_unreachable("Unknown shift opcode!");
13167    break;
13168  case ISD::SHL:
13169    if (VT == MVT::v2i64)
13170      return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13171                         DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
13172                         ValOp, BaseShAmt);
13173    if (VT == MVT::v4i32)
13174      return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13175                         DAG.getConstant(Intrinsic::x86_sse2_pslli_d, MVT::i32),
13176                         ValOp, BaseShAmt);
13177    if (VT == MVT::v8i16)
13178      return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13179                         DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32),
13180                         ValOp, BaseShAmt);
13181    break;
13182  case ISD::SRA:
13183    if (VT == MVT::v4i32)
13184      return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13185                         DAG.getConstant(Intrinsic::x86_sse2_psrai_d, MVT::i32),
13186                         ValOp, BaseShAmt);
13187    if (VT == MVT::v8i16)
13188      return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13189                         DAG.getConstant(Intrinsic::x86_sse2_psrai_w, MVT::i32),
13190                         ValOp, BaseShAmt);
13191    break;
13192  case ISD::SRL:
13193    if (VT == MVT::v2i64)
13194      return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13195                         DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
13196                         ValOp, BaseShAmt);
13197    if (VT == MVT::v4i32)
13198      return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13199                         DAG.getConstant(Intrinsic::x86_sse2_psrli_d, MVT::i32),
13200                         ValOp, BaseShAmt);
13201    if (VT ==  MVT::v8i16)
13202      return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13203                         DAG.getConstant(Intrinsic::x86_sse2_psrli_w, MVT::i32),
13204                         ValOp, BaseShAmt);
13205    break;
13206  }
13207  return SDValue();
13208}
13209
13210
13211// CMPEQCombine - Recognize the distinctive  (AND (setcc ...) (setcc ..))
13212// where both setccs reference the same FP CMP, and rewrite for CMPEQSS
13213// and friends.  Likewise for OR -> CMPNEQSS.
13214static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
13215                            TargetLowering::DAGCombinerInfo &DCI,
13216                            const X86Subtarget *Subtarget) {
13217  unsigned opcode;
13218
13219  // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
13220  // we're requiring SSE2 for both.
13221  if (Subtarget->hasXMMInt() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
13222    SDValue N0 = N->getOperand(0);
13223    SDValue N1 = N->getOperand(1);
13224    SDValue CMP0 = N0->getOperand(1);
13225    SDValue CMP1 = N1->getOperand(1);
13226    DebugLoc DL = N->getDebugLoc();
13227
13228    // The SETCCs should both refer to the same CMP.
13229    if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
13230      return SDValue();
13231
13232    SDValue CMP00 = CMP0->getOperand(0);
13233    SDValue CMP01 = CMP0->getOperand(1);
13234    EVT     VT    = CMP00.getValueType();
13235
13236    if (VT == MVT::f32 || VT == MVT::f64) {
13237      bool ExpectingFlags = false;
13238      // Check for any users that want flags:
13239      for (SDNode::use_iterator UI = N->use_begin(),
13240             UE = N->use_end();
13241           !ExpectingFlags && UI != UE; ++UI)
13242        switch (UI->getOpcode()) {
13243        default:
13244        case ISD::BR_CC:
13245        case ISD::BRCOND:
13246        case ISD::SELECT:
13247          ExpectingFlags = true;
13248          break;
13249        case ISD::CopyToReg:
13250        case ISD::SIGN_EXTEND:
13251        case ISD::ZERO_EXTEND:
13252        case ISD::ANY_EXTEND:
13253          break;
13254        }
13255
13256      if (!ExpectingFlags) {
13257        enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
13258        enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
13259
13260        if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
13261          X86::CondCode tmp = cc0;
13262          cc0 = cc1;
13263          cc1 = tmp;
13264        }
13265
13266        if ((cc0 == X86::COND_E  && cc1 == X86::COND_NP) ||
13267            (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
13268          bool is64BitFP = (CMP00.getValueType() == MVT::f64);
13269          X86ISD::NodeType NTOperator = is64BitFP ?
13270            X86ISD::FSETCCsd : X86ISD::FSETCCss;
13271          // FIXME: need symbolic constants for these magic numbers.
13272          // See X86ATTInstPrinter.cpp:printSSECC().
13273          unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
13274          SDValue OnesOrZeroesF = DAG.getNode(NTOperator, DL, MVT::f32, CMP00, CMP01,
13275                                              DAG.getConstant(x86cc, MVT::i8));
13276          SDValue OnesOrZeroesI = DAG.getNode(ISD::BITCAST, DL, MVT::i32,
13277                                              OnesOrZeroesF);
13278          SDValue ANDed = DAG.getNode(ISD::AND, DL, MVT::i32, OnesOrZeroesI,
13279                                      DAG.getConstant(1, MVT::i32));
13280          SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8, ANDed);
13281          return OneBitOfTruth;
13282        }
13283      }
13284    }
13285  }
13286  return SDValue();
13287}
13288
13289/// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
13290/// so it can be folded inside ANDNP.
13291static bool CanFoldXORWithAllOnes(const SDNode *N) {
13292  EVT VT = N->getValueType(0);
13293
13294  // Match direct AllOnes for 128 and 256-bit vectors
13295  if (ISD::isBuildVectorAllOnes(N))
13296    return true;
13297
13298  // Look through a bit convert.
13299  if (N->getOpcode() == ISD::BITCAST)
13300    N = N->getOperand(0).getNode();
13301
13302  // Sometimes the operand may come from a insert_subvector building a 256-bit
13303  // allones vector
13304  if (VT.getSizeInBits() == 256 &&
13305      N->getOpcode() == ISD::INSERT_SUBVECTOR) {
13306    SDValue V1 = N->getOperand(0);
13307    SDValue V2 = N->getOperand(1);
13308
13309    if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
13310        V1.getOperand(0).getOpcode() == ISD::UNDEF &&
13311        ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
13312        ISD::isBuildVectorAllOnes(V2.getNode()))
13313      return true;
13314  }
13315
13316  return false;
13317}
13318
13319static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
13320                                 TargetLowering::DAGCombinerInfo &DCI,
13321                                 const X86Subtarget *Subtarget) {
13322  if (DCI.isBeforeLegalizeOps())
13323    return SDValue();
13324
13325  SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
13326  if (R.getNode())
13327    return R;
13328
13329  EVT VT = N->getValueType(0);
13330
13331  // Create ANDN instructions
13332  if (Subtarget->hasBMI() && (VT == MVT::i32 || VT == MVT::i64)) {
13333    SDValue N0 = N->getOperand(0);
13334    SDValue N1 = N->getOperand(1);
13335    DebugLoc DL = N->getDebugLoc();
13336
13337    // Check LHS for not
13338    if (N0.getOpcode() == ISD::XOR && isAllOnes(N0.getOperand(1)))
13339      return DAG.getNode(X86ISD::ANDN, DL, VT, N0.getOperand(0), N1);
13340    // Check RHS for not
13341    if (N1.getOpcode() == ISD::XOR && isAllOnes(N1.getOperand(1)))
13342      return DAG.getNode(X86ISD::ANDN, DL, VT, N1.getOperand(0), N0);
13343
13344    return SDValue();
13345  }
13346
13347  // Want to form ANDNP nodes:
13348  // 1) In the hopes of then easily combining them with OR and AND nodes
13349  //    to form PBLEND/PSIGN.
13350  // 2) To match ANDN packed intrinsics
13351  if (VT != MVT::v2i64 && VT != MVT::v4i64)
13352    return SDValue();
13353
13354  SDValue N0 = N->getOperand(0);
13355  SDValue N1 = N->getOperand(1);
13356  DebugLoc DL = N->getDebugLoc();
13357
13358  // Check LHS for vnot
13359  if (N0.getOpcode() == ISD::XOR &&
13360      //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
13361      CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
13362    return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
13363
13364  // Check RHS for vnot
13365  if (N1.getOpcode() == ISD::XOR &&
13366      //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
13367      CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
13368    return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
13369
13370  return SDValue();
13371}
13372
13373static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
13374                                TargetLowering::DAGCombinerInfo &DCI,
13375                                const X86Subtarget *Subtarget) {
13376  if (DCI.isBeforeLegalizeOps())
13377    return SDValue();
13378
13379  SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
13380  if (R.getNode())
13381    return R;
13382
13383  EVT VT = N->getValueType(0);
13384  if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64 && VT != MVT::v2i64)
13385    return SDValue();
13386
13387  SDValue N0 = N->getOperand(0);
13388  SDValue N1 = N->getOperand(1);
13389
13390  // look for psign/blend
13391  if (Subtarget->hasSSSE3() || Subtarget->hasAVX()) {
13392    if (VT == MVT::v2i64) {
13393      // Canonicalize pandn to RHS
13394      if (N0.getOpcode() == X86ISD::ANDNP)
13395        std::swap(N0, N1);
13396      // or (and (m, x), (pandn m, y))
13397      if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
13398        SDValue Mask = N1.getOperand(0);
13399        SDValue X    = N1.getOperand(1);
13400        SDValue Y;
13401        if (N0.getOperand(0) == Mask)
13402          Y = N0.getOperand(1);
13403        if (N0.getOperand(1) == Mask)
13404          Y = N0.getOperand(0);
13405
13406        // Check to see if the mask appeared in both the AND and ANDNP and
13407        if (!Y.getNode())
13408          return SDValue();
13409
13410        // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
13411        if (Mask.getOpcode() != ISD::BITCAST ||
13412            X.getOpcode() != ISD::BITCAST ||
13413            Y.getOpcode() != ISD::BITCAST)
13414          return SDValue();
13415
13416        // Look through mask bitcast.
13417        Mask = Mask.getOperand(0);
13418        EVT MaskVT = Mask.getValueType();
13419
13420        // Validate that the Mask operand is a vector sra node.  The sra node
13421        // will be an intrinsic.
13422        if (Mask.getOpcode() != ISD::INTRINSIC_WO_CHAIN)
13423          return SDValue();
13424
13425        // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
13426        // there is no psrai.b
13427        switch (cast<ConstantSDNode>(Mask.getOperand(0))->getZExtValue()) {
13428        case Intrinsic::x86_sse2_psrai_w:
13429        case Intrinsic::x86_sse2_psrai_d:
13430          break;
13431        default: return SDValue();
13432        }
13433
13434        // Check that the SRA is all signbits.
13435        SDValue SraC = Mask.getOperand(2);
13436        unsigned SraAmt  = cast<ConstantSDNode>(SraC)->getZExtValue();
13437        unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
13438        if ((SraAmt + 1) != EltBits)
13439          return SDValue();
13440
13441        DebugLoc DL = N->getDebugLoc();
13442
13443        // Now we know we at least have a plendvb with the mask val.  See if
13444        // we can form a psignb/w/d.
13445        // psign = x.type == y.type == mask.type && y = sub(0, x);
13446        X = X.getOperand(0);
13447        Y = Y.getOperand(0);
13448        if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
13449            ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
13450            X.getValueType() == MaskVT && X.getValueType() == Y.getValueType()){
13451          unsigned Opc = 0;
13452          switch (EltBits) {
13453          case 8: Opc = X86ISD::PSIGNB; break;
13454          case 16: Opc = X86ISD::PSIGNW; break;
13455          case 32: Opc = X86ISD::PSIGND; break;
13456          default: break;
13457          }
13458          if (Opc) {
13459            SDValue Sign = DAG.getNode(Opc, DL, MaskVT, X, Mask.getOperand(1));
13460            return DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, Sign);
13461          }
13462        }
13463        // PBLENDVB only available on SSE 4.1
13464        if (!(Subtarget->hasSSE41() || Subtarget->hasAVX()))
13465          return SDValue();
13466
13467        X = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, X);
13468        Y = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, Y);
13469        Mask = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, Mask);
13470        Mask = DAG.getNode(ISD::VSELECT, DL, MVT::v16i8, Mask, X, Y);
13471        return DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, Mask);
13472      }
13473    }
13474  }
13475
13476  // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
13477  if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
13478    std::swap(N0, N1);
13479  if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
13480    return SDValue();
13481  if (!N0.hasOneUse() || !N1.hasOneUse())
13482    return SDValue();
13483
13484  SDValue ShAmt0 = N0.getOperand(1);
13485  if (ShAmt0.getValueType() != MVT::i8)
13486    return SDValue();
13487  SDValue ShAmt1 = N1.getOperand(1);
13488  if (ShAmt1.getValueType() != MVT::i8)
13489    return SDValue();
13490  if (ShAmt0.getOpcode() == ISD::TRUNCATE)
13491    ShAmt0 = ShAmt0.getOperand(0);
13492  if (ShAmt1.getOpcode() == ISD::TRUNCATE)
13493    ShAmt1 = ShAmt1.getOperand(0);
13494
13495  DebugLoc DL = N->getDebugLoc();
13496  unsigned Opc = X86ISD::SHLD;
13497  SDValue Op0 = N0.getOperand(0);
13498  SDValue Op1 = N1.getOperand(0);
13499  if (ShAmt0.getOpcode() == ISD::SUB) {
13500    Opc = X86ISD::SHRD;
13501    std::swap(Op0, Op1);
13502    std::swap(ShAmt0, ShAmt1);
13503  }
13504
13505  unsigned Bits = VT.getSizeInBits();
13506  if (ShAmt1.getOpcode() == ISD::SUB) {
13507    SDValue Sum = ShAmt1.getOperand(0);
13508    if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
13509      SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
13510      if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
13511        ShAmt1Op1 = ShAmt1Op1.getOperand(0);
13512      if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
13513        return DAG.getNode(Opc, DL, VT,
13514                           Op0, Op1,
13515                           DAG.getNode(ISD::TRUNCATE, DL,
13516                                       MVT::i8, ShAmt0));
13517    }
13518  } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
13519    ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
13520    if (ShAmt0C &&
13521        ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
13522      return DAG.getNode(Opc, DL, VT,
13523                         N0.getOperand(0), N1.getOperand(0),
13524                         DAG.getNode(ISD::TRUNCATE, DL,
13525                                       MVT::i8, ShAmt0));
13526  }
13527
13528  return SDValue();
13529}
13530
13531/// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
13532static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
13533                                   const X86Subtarget *Subtarget) {
13534  LoadSDNode *Ld = cast<LoadSDNode>(N);
13535  EVT RegVT = Ld->getValueType(0);
13536  EVT MemVT = Ld->getMemoryVT();
13537  DebugLoc dl = Ld->getDebugLoc();
13538  const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13539
13540  ISD::LoadExtType Ext = Ld->getExtensionType();
13541
13542  // If this is a vector EXT Load then attempt to optimize it using a
13543  // shuffle. We need SSE4 for the shuffles.
13544  // TODO: It is possible to support ZExt by zeroing the undef values
13545  // during the shuffle phase or after the shuffle.
13546  if (RegVT.isVector() && Ext == ISD::EXTLOAD && Subtarget->hasSSE41()) {
13547    assert(MemVT != RegVT && "Cannot extend to the same type");
13548    assert(MemVT.isVector() && "Must load a vector from memory");
13549
13550    unsigned NumElems = RegVT.getVectorNumElements();
13551    unsigned RegSz = RegVT.getSizeInBits();
13552    unsigned MemSz = MemVT.getSizeInBits();
13553    assert(RegSz > MemSz && "Register size must be greater than the mem size");
13554    // All sizes must be a power of two
13555    if (!isPowerOf2_32(RegSz * MemSz * NumElems)) return SDValue();
13556
13557    // Attempt to load the original value using a single load op.
13558    // Find a scalar type which is equal to the loaded word size.
13559    MVT SclrLoadTy = MVT::i8;
13560    for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
13561         tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
13562      MVT Tp = (MVT::SimpleValueType)tp;
13563      if (TLI.isTypeLegal(Tp) &&  Tp.getSizeInBits() == MemSz) {
13564        SclrLoadTy = Tp;
13565        break;
13566      }
13567    }
13568
13569    // Proceed if a load word is found.
13570    if (SclrLoadTy.getSizeInBits() != MemSz) return SDValue();
13571
13572    EVT LoadUnitVecVT = EVT::getVectorVT(*DAG.getContext(), SclrLoadTy,
13573      RegSz/SclrLoadTy.getSizeInBits());
13574
13575    EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
13576                                  RegSz/MemVT.getScalarType().getSizeInBits());
13577    // Can't shuffle using an illegal type.
13578    if (!TLI.isTypeLegal(WideVecVT)) return SDValue();
13579
13580    // Perform a single load.
13581    SDValue ScalarLoad = DAG.getLoad(SclrLoadTy, dl, Ld->getChain(),
13582                                  Ld->getBasePtr(),
13583                                  Ld->getPointerInfo(), Ld->isVolatile(),
13584                                  Ld->isNonTemporal(), Ld->getAlignment());
13585
13586    // Insert the word loaded into a vector.
13587    SDValue ScalarInVector = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
13588      LoadUnitVecVT, ScalarLoad);
13589
13590    // Bitcast the loaded value to a vector of the original element type, in
13591    // the size of the target vector type.
13592    SDValue SlicedVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, ScalarInVector);
13593    unsigned SizeRatio = RegSz/MemSz;
13594
13595    // Redistribute the loaded elements into the different locations.
13596    SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
13597    for (unsigned i = 0; i < NumElems; i++) ShuffleVec[i*SizeRatio] = i;
13598
13599    SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
13600                                DAG.getUNDEF(SlicedVec.getValueType()),
13601                                ShuffleVec.data());
13602
13603    // Bitcast to the requested type.
13604    Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
13605    // Replace the original load with the new sequence
13606    // and return the new chain.
13607    DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Shuff);
13608    return SDValue(ScalarLoad.getNode(), 1);
13609  }
13610
13611  return SDValue();
13612}
13613
13614/// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
13615static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
13616                                   const X86Subtarget *Subtarget) {
13617  StoreSDNode *St = cast<StoreSDNode>(N);
13618  EVT VT = St->getValue().getValueType();
13619  EVT StVT = St->getMemoryVT();
13620  DebugLoc dl = St->getDebugLoc();
13621  SDValue StoredVal = St->getOperand(1);
13622  const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13623
13624  // If we are saving a concatination of two XMM registers, perform two stores.
13625  // This is better in Sandy Bridge cause one 256-bit mem op is done via two
13626  // 128-bit ones. If in the future the cost becomes only one memory access the
13627  // first version would be better.
13628  if (VT.getSizeInBits() == 256 &&
13629    StoredVal.getNode()->getOpcode() == ISD::CONCAT_VECTORS &&
13630    StoredVal.getNumOperands() == 2) {
13631
13632    SDValue Value0 = StoredVal.getOperand(0);
13633    SDValue Value1 = StoredVal.getOperand(1);
13634
13635    SDValue Stride = DAG.getConstant(16, TLI.getPointerTy());
13636    SDValue Ptr0 = St->getBasePtr();
13637    SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
13638
13639    SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
13640                                St->getPointerInfo(), St->isVolatile(),
13641                                St->isNonTemporal(), St->getAlignment());
13642    SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
13643                                St->getPointerInfo(), St->isVolatile(),
13644                                St->isNonTemporal(), St->getAlignment());
13645    return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
13646  }
13647
13648  // Optimize trunc store (of multiple scalars) to shuffle and store.
13649  // First, pack all of the elements in one place. Next, store to memory
13650  // in fewer chunks.
13651  if (St->isTruncatingStore() && VT.isVector()) {
13652    const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13653    unsigned NumElems = VT.getVectorNumElements();
13654    assert(StVT != VT && "Cannot truncate to the same type");
13655    unsigned FromSz = VT.getVectorElementType().getSizeInBits();
13656    unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
13657
13658    // From, To sizes and ElemCount must be pow of two
13659    if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
13660    // We are going to use the original vector elt for storing.
13661    // Accumulated smaller vector elements must be a multiple of the store size.
13662    if (0 != (NumElems * FromSz) % ToSz) return SDValue();
13663
13664    unsigned SizeRatio  = FromSz / ToSz;
13665
13666    assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
13667
13668    // Create a type on which we perform the shuffle
13669    EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
13670            StVT.getScalarType(), NumElems*SizeRatio);
13671
13672    assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
13673
13674    SDValue WideVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, St->getValue());
13675    SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
13676    for (unsigned i = 0; i < NumElems; i++ ) ShuffleVec[i] = i * SizeRatio;
13677
13678    // Can't shuffle using an illegal type
13679    if (!TLI.isTypeLegal(WideVecVT)) return SDValue();
13680
13681    SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
13682                                DAG.getUNDEF(WideVec.getValueType()),
13683                                ShuffleVec.data());
13684    // At this point all of the data is stored at the bottom of the
13685    // register. We now need to save it to mem.
13686
13687    // Find the largest store unit
13688    MVT StoreType = MVT::i8;
13689    for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
13690         tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
13691      MVT Tp = (MVT::SimpleValueType)tp;
13692      if (TLI.isTypeLegal(Tp) && StoreType.getSizeInBits() < NumElems * ToSz)
13693        StoreType = Tp;
13694    }
13695
13696    // Bitcast the original vector into a vector of store-size units
13697    EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
13698            StoreType, VT.getSizeInBits()/EVT(StoreType).getSizeInBits());
13699    assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
13700    SDValue ShuffWide = DAG.getNode(ISD::BITCAST, dl, StoreVecVT, Shuff);
13701    SmallVector<SDValue, 8> Chains;
13702    SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
13703                                        TLI.getPointerTy());
13704    SDValue Ptr = St->getBasePtr();
13705
13706    // Perform one or more big stores into memory.
13707    for (unsigned i = 0; i < (ToSz*NumElems)/StoreType.getSizeInBits() ; i++) {
13708      SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
13709                                   StoreType, ShuffWide,
13710                                   DAG.getIntPtrConstant(i));
13711      SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
13712                                St->getPointerInfo(), St->isVolatile(),
13713                                St->isNonTemporal(), St->getAlignment());
13714      Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
13715      Chains.push_back(Ch);
13716    }
13717
13718    return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Chains[0],
13719                               Chains.size());
13720  }
13721
13722
13723  // Turn load->store of MMX types into GPR load/stores.  This avoids clobbering
13724  // the FP state in cases where an emms may be missing.
13725  // A preferable solution to the general problem is to figure out the right
13726  // places to insert EMMS.  This qualifies as a quick hack.
13727
13728  // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
13729  if (VT.getSizeInBits() != 64)
13730    return SDValue();
13731
13732  const Function *F = DAG.getMachineFunction().getFunction();
13733  bool NoImplicitFloatOps = F->hasFnAttr(Attribute::NoImplicitFloat);
13734  bool F64IsLegal = !UseSoftFloat && !NoImplicitFloatOps
13735                     && Subtarget->hasXMMInt();
13736  if ((VT.isVector() ||
13737       (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
13738      isa<LoadSDNode>(St->getValue()) &&
13739      !cast<LoadSDNode>(St->getValue())->isVolatile() &&
13740      St->getChain().hasOneUse() && !St->isVolatile()) {
13741    SDNode* LdVal = St->getValue().getNode();
13742    LoadSDNode *Ld = 0;
13743    int TokenFactorIndex = -1;
13744    SmallVector<SDValue, 8> Ops;
13745    SDNode* ChainVal = St->getChain().getNode();
13746    // Must be a store of a load.  We currently handle two cases:  the load
13747    // is a direct child, and it's under an intervening TokenFactor.  It is
13748    // possible to dig deeper under nested TokenFactors.
13749    if (ChainVal == LdVal)
13750      Ld = cast<LoadSDNode>(St->getChain());
13751    else if (St->getValue().hasOneUse() &&
13752             ChainVal->getOpcode() == ISD::TokenFactor) {
13753      for (unsigned i=0, e = ChainVal->getNumOperands(); i != e; ++i) {
13754        if (ChainVal->getOperand(i).getNode() == LdVal) {
13755          TokenFactorIndex = i;
13756          Ld = cast<LoadSDNode>(St->getValue());
13757        } else
13758          Ops.push_back(ChainVal->getOperand(i));
13759      }
13760    }
13761
13762    if (!Ld || !ISD::isNormalLoad(Ld))
13763      return SDValue();
13764
13765    // If this is not the MMX case, i.e. we are just turning i64 load/store
13766    // into f64 load/store, avoid the transformation if there are multiple
13767    // uses of the loaded value.
13768    if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
13769      return SDValue();
13770
13771    DebugLoc LdDL = Ld->getDebugLoc();
13772    DebugLoc StDL = N->getDebugLoc();
13773    // If we are a 64-bit capable x86, lower to a single movq load/store pair.
13774    // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
13775    // pair instead.
13776    if (Subtarget->is64Bit() || F64IsLegal) {
13777      EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
13778      SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
13779                                  Ld->getPointerInfo(), Ld->isVolatile(),
13780                                  Ld->isNonTemporal(), Ld->getAlignment());
13781      SDValue NewChain = NewLd.getValue(1);
13782      if (TokenFactorIndex != -1) {
13783        Ops.push_back(NewChain);
13784        NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
13785                               Ops.size());
13786      }
13787      return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
13788                          St->getPointerInfo(),
13789                          St->isVolatile(), St->isNonTemporal(),
13790                          St->getAlignment());
13791    }
13792
13793    // Otherwise, lower to two pairs of 32-bit loads / stores.
13794    SDValue LoAddr = Ld->getBasePtr();
13795    SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
13796                                 DAG.getConstant(4, MVT::i32));
13797
13798    SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
13799                               Ld->getPointerInfo(),
13800                               Ld->isVolatile(), Ld->isNonTemporal(),
13801                               Ld->getAlignment());
13802    SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
13803                               Ld->getPointerInfo().getWithOffset(4),
13804                               Ld->isVolatile(), Ld->isNonTemporal(),
13805                               MinAlign(Ld->getAlignment(), 4));
13806
13807    SDValue NewChain = LoLd.getValue(1);
13808    if (TokenFactorIndex != -1) {
13809      Ops.push_back(LoLd);
13810      Ops.push_back(HiLd);
13811      NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
13812                             Ops.size());
13813    }
13814
13815    LoAddr = St->getBasePtr();
13816    HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
13817                         DAG.getConstant(4, MVT::i32));
13818
13819    SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
13820                                St->getPointerInfo(),
13821                                St->isVolatile(), St->isNonTemporal(),
13822                                St->getAlignment());
13823    SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
13824                                St->getPointerInfo().getWithOffset(4),
13825                                St->isVolatile(),
13826                                St->isNonTemporal(),
13827                                MinAlign(St->getAlignment(), 4));
13828    return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
13829  }
13830  return SDValue();
13831}
13832
13833/// isHorizontalBinOp - Return 'true' if this vector operation is "horizontal"
13834/// and return the operands for the horizontal operation in LHS and RHS.  A
13835/// horizontal operation performs the binary operation on successive elements
13836/// of its first operand, then on successive elements of its second operand,
13837/// returning the resulting values in a vector.  For example, if
13838///   A = < float a0, float a1, float a2, float a3 >
13839/// and
13840///   B = < float b0, float b1, float b2, float b3 >
13841/// then the result of doing a horizontal operation on A and B is
13842///   A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
13843/// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
13844/// A horizontal-op B, for some already available A and B, and if so then LHS is
13845/// set to A, RHS to B, and the routine returns 'true'.
13846/// Note that the binary operation should have the property that if one of the
13847/// operands is UNDEF then the result is UNDEF.
13848static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool isCommutative) {
13849  // Look for the following pattern: if
13850  //   A = < float a0, float a1, float a2, float a3 >
13851  //   B = < float b0, float b1, float b2, float b3 >
13852  // and
13853  //   LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
13854  //   RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
13855  // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
13856  // which is A horizontal-op B.
13857
13858  // At least one of the operands should be a vector shuffle.
13859  if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
13860      RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
13861    return false;
13862
13863  EVT VT = LHS.getValueType();
13864  unsigned N = VT.getVectorNumElements();
13865
13866  // View LHS in the form
13867  //   LHS = VECTOR_SHUFFLE A, B, LMask
13868  // If LHS is not a shuffle then pretend it is the shuffle
13869  //   LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
13870  // NOTE: in what follows a default initialized SDValue represents an UNDEF of
13871  // type VT.
13872  SDValue A, B;
13873  SmallVector<int, 8> LMask(N);
13874  if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
13875    if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
13876      A = LHS.getOperand(0);
13877    if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
13878      B = LHS.getOperand(1);
13879    cast<ShuffleVectorSDNode>(LHS.getNode())->getMask(LMask);
13880  } else {
13881    if (LHS.getOpcode() != ISD::UNDEF)
13882      A = LHS;
13883    for (unsigned i = 0; i != N; ++i)
13884      LMask[i] = i;
13885  }
13886
13887  // Likewise, view RHS in the form
13888  //   RHS = VECTOR_SHUFFLE C, D, RMask
13889  SDValue C, D;
13890  SmallVector<int, 8> RMask(N);
13891  if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
13892    if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
13893      C = RHS.getOperand(0);
13894    if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
13895      D = RHS.getOperand(1);
13896    cast<ShuffleVectorSDNode>(RHS.getNode())->getMask(RMask);
13897  } else {
13898    if (RHS.getOpcode() != ISD::UNDEF)
13899      C = RHS;
13900    for (unsigned i = 0; i != N; ++i)
13901      RMask[i] = i;
13902  }
13903
13904  // Check that the shuffles are both shuffling the same vectors.
13905  if (!(A == C && B == D) && !(A == D && B == C))
13906    return false;
13907
13908  // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
13909  if (!A.getNode() && !B.getNode())
13910    return false;
13911
13912  // If A and B occur in reverse order in RHS, then "swap" them (which means
13913  // rewriting the mask).
13914  if (A != C)
13915    for (unsigned i = 0; i != N; ++i) {
13916      unsigned Idx = RMask[i];
13917      if (Idx < N)
13918        RMask[i] += N;
13919      else if (Idx < 2*N)
13920        RMask[i] -= N;
13921    }
13922
13923  // At this point LHS and RHS are equivalent to
13924  //   LHS = VECTOR_SHUFFLE A, B, LMask
13925  //   RHS = VECTOR_SHUFFLE A, B, RMask
13926  // Check that the masks correspond to performing a horizontal operation.
13927  for (unsigned i = 0; i != N; ++i) {
13928    unsigned LIdx = LMask[i], RIdx = RMask[i];
13929
13930    // Ignore any UNDEF components.
13931    if (LIdx >= 2*N || RIdx >= 2*N || (!A.getNode() && (LIdx < N || RIdx < N))
13932        || (!B.getNode() && (LIdx >= N || RIdx >= N)))
13933      continue;
13934
13935    // Check that successive elements are being operated on.  If not, this is
13936    // not a horizontal operation.
13937    if (!(LIdx == 2*i && RIdx == 2*i + 1) &&
13938        !(isCommutative && LIdx == 2*i + 1 && RIdx == 2*i))
13939      return false;
13940  }
13941
13942  LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
13943  RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
13944  return true;
13945}
13946
13947/// PerformFADDCombine - Do target-specific dag combines on floating point adds.
13948static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
13949                                  const X86Subtarget *Subtarget) {
13950  EVT VT = N->getValueType(0);
13951  SDValue LHS = N->getOperand(0);
13952  SDValue RHS = N->getOperand(1);
13953
13954  // Try to synthesize horizontal adds from adds of shuffles.
13955  if ((Subtarget->hasSSE3() || Subtarget->hasAVX()) &&
13956      (VT == MVT::v4f32 || VT == MVT::v2f64) &&
13957      isHorizontalBinOp(LHS, RHS, true))
13958    return DAG.getNode(X86ISD::FHADD, N->getDebugLoc(), VT, LHS, RHS);
13959  return SDValue();
13960}
13961
13962/// PerformFSUBCombine - Do target-specific dag combines on floating point subs.
13963static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
13964                                  const X86Subtarget *Subtarget) {
13965  EVT VT = N->getValueType(0);
13966  SDValue LHS = N->getOperand(0);
13967  SDValue RHS = N->getOperand(1);
13968
13969  // Try to synthesize horizontal subs from subs of shuffles.
13970  if ((Subtarget->hasSSE3() || Subtarget->hasAVX()) &&
13971      (VT == MVT::v4f32 || VT == MVT::v2f64) &&
13972      isHorizontalBinOp(LHS, RHS, false))
13973    return DAG.getNode(X86ISD::FHSUB, N->getDebugLoc(), VT, LHS, RHS);
13974  return SDValue();
13975}
13976
13977/// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
13978/// X86ISD::FXOR nodes.
13979static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
13980  assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
13981  // F[X]OR(0.0, x) -> x
13982  // F[X]OR(x, 0.0) -> x
13983  if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
13984    if (C->getValueAPF().isPosZero())
13985      return N->getOperand(1);
13986  if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
13987    if (C->getValueAPF().isPosZero())
13988      return N->getOperand(0);
13989  return SDValue();
13990}
13991
13992/// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
13993static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
13994  // FAND(0.0, x) -> 0.0
13995  // FAND(x, 0.0) -> 0.0
13996  if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
13997    if (C->getValueAPF().isPosZero())
13998      return N->getOperand(0);
13999  if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
14000    if (C->getValueAPF().isPosZero())
14001      return N->getOperand(1);
14002  return SDValue();
14003}
14004
14005static SDValue PerformBTCombine(SDNode *N,
14006                                SelectionDAG &DAG,
14007                                TargetLowering::DAGCombinerInfo &DCI) {
14008  // BT ignores high bits in the bit index operand.
14009  SDValue Op1 = N->getOperand(1);
14010  if (Op1.hasOneUse()) {
14011    unsigned BitWidth = Op1.getValueSizeInBits();
14012    APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
14013    APInt KnownZero, KnownOne;
14014    TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
14015                                          !DCI.isBeforeLegalizeOps());
14016    const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14017    if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
14018        TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
14019      DCI.CommitTargetLoweringOpt(TLO);
14020  }
14021  return SDValue();
14022}
14023
14024static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
14025  SDValue Op = N->getOperand(0);
14026  if (Op.getOpcode() == ISD::BITCAST)
14027    Op = Op.getOperand(0);
14028  EVT VT = N->getValueType(0), OpVT = Op.getValueType();
14029  if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
14030      VT.getVectorElementType().getSizeInBits() ==
14031      OpVT.getVectorElementType().getSizeInBits()) {
14032    return DAG.getNode(ISD::BITCAST, N->getDebugLoc(), VT, Op);
14033  }
14034  return SDValue();
14035}
14036
14037static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG) {
14038  // (i32 zext (and (i8  x86isd::setcc_carry), 1)) ->
14039  //           (and (i32 x86isd::setcc_carry), 1)
14040  // This eliminates the zext. This transformation is necessary because
14041  // ISD::SETCC is always legalized to i8.
14042  DebugLoc dl = N->getDebugLoc();
14043  SDValue N0 = N->getOperand(0);
14044  EVT VT = N->getValueType(0);
14045  if (N0.getOpcode() == ISD::AND &&
14046      N0.hasOneUse() &&
14047      N0.getOperand(0).hasOneUse()) {
14048    SDValue N00 = N0.getOperand(0);
14049    if (N00.getOpcode() != X86ISD::SETCC_CARRY)
14050      return SDValue();
14051    ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
14052    if (!C || C->getZExtValue() != 1)
14053      return SDValue();
14054    return DAG.getNode(ISD::AND, dl, VT,
14055                       DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
14056                                   N00.getOperand(0), N00.getOperand(1)),
14057                       DAG.getConstant(1, VT));
14058  }
14059
14060  return SDValue();
14061}
14062
14063// Optimize  RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
14064static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG) {
14065  unsigned X86CC = N->getConstantOperandVal(0);
14066  SDValue EFLAG = N->getOperand(1);
14067  DebugLoc DL = N->getDebugLoc();
14068
14069  // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
14070  // a zext and produces an all-ones bit which is more useful than 0/1 in some
14071  // cases.
14072  if (X86CC == X86::COND_B)
14073    return DAG.getNode(ISD::AND, DL, MVT::i8,
14074                       DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
14075                                   DAG.getConstant(X86CC, MVT::i8), EFLAG),
14076                       DAG.getConstant(1, MVT::i8));
14077
14078  return SDValue();
14079}
14080
14081static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
14082                                        const X86TargetLowering *XTLI) {
14083  SDValue Op0 = N->getOperand(0);
14084  // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
14085  // a 32-bit target where SSE doesn't support i64->FP operations.
14086  if (Op0.getOpcode() == ISD::LOAD) {
14087    LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
14088    EVT VT = Ld->getValueType(0);
14089    if (!Ld->isVolatile() && !N->getValueType(0).isVector() &&
14090        ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
14091        !XTLI->getSubtarget()->is64Bit() &&
14092        !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
14093      SDValue FILDChain = XTLI->BuildFILD(SDValue(N, 0), Ld->getValueType(0),
14094                                          Ld->getChain(), Op0, DAG);
14095      DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
14096      return FILDChain;
14097    }
14098  }
14099  return SDValue();
14100}
14101
14102// Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
14103static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
14104                                 X86TargetLowering::DAGCombinerInfo &DCI) {
14105  // If the LHS and RHS of the ADC node are zero, then it can't overflow and
14106  // the result is either zero or one (depending on the input carry bit).
14107  // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
14108  if (X86::isZeroNode(N->getOperand(0)) &&
14109      X86::isZeroNode(N->getOperand(1)) &&
14110      // We don't have a good way to replace an EFLAGS use, so only do this when
14111      // dead right now.
14112      SDValue(N, 1).use_empty()) {
14113    DebugLoc DL = N->getDebugLoc();
14114    EVT VT = N->getValueType(0);
14115    SDValue CarryOut = DAG.getConstant(0, N->getValueType(1));
14116    SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
14117                               DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
14118                                           DAG.getConstant(X86::COND_B,MVT::i8),
14119                                           N->getOperand(2)),
14120                               DAG.getConstant(1, VT));
14121    return DCI.CombineTo(N, Res1, CarryOut);
14122  }
14123
14124  return SDValue();
14125}
14126
14127// fold (add Y, (sete  X, 0)) -> adc  0, Y
14128//      (add Y, (setne X, 0)) -> sbb -1, Y
14129//      (sub (sete  X, 0), Y) -> sbb  0, Y
14130//      (sub (setne X, 0), Y) -> adc -1, Y
14131static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
14132  DebugLoc DL = N->getDebugLoc();
14133
14134  // Look through ZExts.
14135  SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
14136  if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
14137    return SDValue();
14138
14139  SDValue SetCC = Ext.getOperand(0);
14140  if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
14141    return SDValue();
14142
14143  X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
14144  if (CC != X86::COND_E && CC != X86::COND_NE)
14145    return SDValue();
14146
14147  SDValue Cmp = SetCC.getOperand(1);
14148  if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
14149      !X86::isZeroNode(Cmp.getOperand(1)) ||
14150      !Cmp.getOperand(0).getValueType().isInteger())
14151    return SDValue();
14152
14153  SDValue CmpOp0 = Cmp.getOperand(0);
14154  SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
14155                               DAG.getConstant(1, CmpOp0.getValueType()));
14156
14157  SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
14158  if (CC == X86::COND_NE)
14159    return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
14160                       DL, OtherVal.getValueType(), OtherVal,
14161                       DAG.getConstant(-1ULL, OtherVal.getValueType()), NewCmp);
14162  return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
14163                     DL, OtherVal.getValueType(), OtherVal,
14164                     DAG.getConstant(0, OtherVal.getValueType()), NewCmp);
14165}
14166
14167static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG) {
14168  SDValue Op0 = N->getOperand(0);
14169  SDValue Op1 = N->getOperand(1);
14170
14171  // X86 can't encode an immediate LHS of a sub. See if we can push the
14172  // negation into a preceding instruction.
14173  if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
14174    // If the RHS of the sub is a XOR with one use and a constant, invert the
14175    // immediate. Then add one to the LHS of the sub so we can turn
14176    // X-Y -> X+~Y+1, saving one register.
14177    if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
14178        isa<ConstantSDNode>(Op1.getOperand(1))) {
14179      APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
14180      EVT VT = Op0.getValueType();
14181      SDValue NewXor = DAG.getNode(ISD::XOR, Op1.getDebugLoc(), VT,
14182                                   Op1.getOperand(0),
14183                                   DAG.getConstant(~XorC, VT));
14184      return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, NewXor,
14185                         DAG.getConstant(C->getAPIntValue()+1, VT));
14186    }
14187  }
14188
14189  return OptimizeConditionalInDecrement(N, DAG);
14190}
14191
14192SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
14193                                             DAGCombinerInfo &DCI) const {
14194  SelectionDAG &DAG = DCI.DAG;
14195  switch (N->getOpcode()) {
14196  default: break;
14197  case ISD::EXTRACT_VECTOR_ELT:
14198    return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, *this);
14199  case ISD::VSELECT:
14200  case ISD::SELECT:         return PerformSELECTCombine(N, DAG, Subtarget);
14201  case ISD::BITCAST:        return PerformBITCASTCombine(N, DAG);
14202  case X86ISD::CMOV:        return PerformCMOVCombine(N, DAG, DCI);
14203  case ISD::ADD:            return OptimizeConditionalInDecrement(N, DAG);
14204  case ISD::SUB:            return PerformSubCombine(N, DAG);
14205  case X86ISD::ADC:         return PerformADCCombine(N, DAG, DCI);
14206  case ISD::MUL:            return PerformMulCombine(N, DAG, DCI);
14207  case ISD::SHL:
14208  case ISD::SRA:
14209  case ISD::SRL:            return PerformShiftCombine(N, DAG, Subtarget);
14210  case ISD::AND:            return PerformAndCombine(N, DAG, DCI, Subtarget);
14211  case ISD::OR:             return PerformOrCombine(N, DAG, DCI, Subtarget);
14212  case ISD::LOAD:           return PerformLOADCombine(N, DAG, Subtarget);
14213  case ISD::STORE:          return PerformSTORECombine(N, DAG, Subtarget);
14214  case ISD::SINT_TO_FP:     return PerformSINT_TO_FPCombine(N, DAG, this);
14215  case ISD::FADD:           return PerformFADDCombine(N, DAG, Subtarget);
14216  case ISD::FSUB:           return PerformFSUBCombine(N, DAG, Subtarget);
14217  case X86ISD::FXOR:
14218  case X86ISD::FOR:         return PerformFORCombine(N, DAG);
14219  case X86ISD::FAND:        return PerformFANDCombine(N, DAG);
14220  case X86ISD::BT:          return PerformBTCombine(N, DAG, DCI);
14221  case X86ISD::VZEXT_MOVL:  return PerformVZEXT_MOVLCombine(N, DAG);
14222  case ISD::ZERO_EXTEND:    return PerformZExtCombine(N, DAG);
14223  case X86ISD::SETCC:       return PerformSETCCCombine(N, DAG);
14224  case X86ISD::SHUFPS:      // Handle all target specific shuffles
14225  case X86ISD::SHUFPD:
14226  case X86ISD::PALIGN:
14227  case X86ISD::PUNPCKHBW:
14228  case X86ISD::PUNPCKHWD:
14229  case X86ISD::PUNPCKHDQ:
14230  case X86ISD::PUNPCKHQDQ:
14231  case X86ISD::UNPCKHPS:
14232  case X86ISD::UNPCKHPD:
14233  case X86ISD::VUNPCKHPSY:
14234  case X86ISD::VUNPCKHPDY:
14235  case X86ISD::PUNPCKLBW:
14236  case X86ISD::PUNPCKLWD:
14237  case X86ISD::PUNPCKLDQ:
14238  case X86ISD::PUNPCKLQDQ:
14239  case X86ISD::UNPCKLPS:
14240  case X86ISD::UNPCKLPD:
14241  case X86ISD::VUNPCKLPSY:
14242  case X86ISD::VUNPCKLPDY:
14243  case X86ISD::MOVHLPS:
14244  case X86ISD::MOVLHPS:
14245  case X86ISD::PSHUFD:
14246  case X86ISD::PSHUFHW:
14247  case X86ISD::PSHUFLW:
14248  case X86ISD::MOVSS:
14249  case X86ISD::MOVSD:
14250  case X86ISD::VPERMILPS:
14251  case X86ISD::VPERMILPSY:
14252  case X86ISD::VPERMILPD:
14253  case X86ISD::VPERMILPDY:
14254  case X86ISD::VPERM2F128:
14255  case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
14256  }
14257
14258  return SDValue();
14259}
14260
14261/// isTypeDesirableForOp - Return true if the target has native support for
14262/// the specified value type and it is 'desirable' to use the type for the
14263/// given node type. e.g. On x86 i16 is legal, but undesirable since i16
14264/// instruction encodings are longer and some i16 instructions are slow.
14265bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
14266  if (!isTypeLegal(VT))
14267    return false;
14268  if (VT != MVT::i16)
14269    return true;
14270
14271  switch (Opc) {
14272  default:
14273    return true;
14274  case ISD::LOAD:
14275  case ISD::SIGN_EXTEND:
14276  case ISD::ZERO_EXTEND:
14277  case ISD::ANY_EXTEND:
14278  case ISD::SHL:
14279  case ISD::SRL:
14280  case ISD::SUB:
14281  case ISD::ADD:
14282  case ISD::MUL:
14283  case ISD::AND:
14284  case ISD::OR:
14285  case ISD::XOR:
14286    return false;
14287  }
14288}
14289
14290/// IsDesirableToPromoteOp - This method query the target whether it is
14291/// beneficial for dag combiner to promote the specified node. If true, it
14292/// should return the desired promotion type by reference.
14293bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
14294  EVT VT = Op.getValueType();
14295  if (VT != MVT::i16)
14296    return false;
14297
14298  bool Promote = false;
14299  bool Commute = false;
14300  switch (Op.getOpcode()) {
14301  default: break;
14302  case ISD::LOAD: {
14303    LoadSDNode *LD = cast<LoadSDNode>(Op);
14304    // If the non-extending load has a single use and it's not live out, then it
14305    // might be folded.
14306    if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
14307                                                     Op.hasOneUse()*/) {
14308      for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
14309             UE = Op.getNode()->use_end(); UI != UE; ++UI) {
14310        // The only case where we'd want to promote LOAD (rather then it being
14311        // promoted as an operand is when it's only use is liveout.
14312        if (UI->getOpcode() != ISD::CopyToReg)
14313          return false;
14314      }
14315    }
14316    Promote = true;
14317    break;
14318  }
14319  case ISD::SIGN_EXTEND:
14320  case ISD::ZERO_EXTEND:
14321  case ISD::ANY_EXTEND:
14322    Promote = true;
14323    break;
14324  case ISD::SHL:
14325  case ISD::SRL: {
14326    SDValue N0 = Op.getOperand(0);
14327    // Look out for (store (shl (load), x)).
14328    if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
14329      return false;
14330    Promote = true;
14331    break;
14332  }
14333  case ISD::ADD:
14334  case ISD::MUL:
14335  case ISD::AND:
14336  case ISD::OR:
14337  case ISD::XOR:
14338    Commute = true;
14339    // fallthrough
14340  case ISD::SUB: {
14341    SDValue N0 = Op.getOperand(0);
14342    SDValue N1 = Op.getOperand(1);
14343    if (!Commute && MayFoldLoad(N1))
14344      return false;
14345    // Avoid disabling potential load folding opportunities.
14346    if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
14347      return false;
14348    if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
14349      return false;
14350    Promote = true;
14351  }
14352  }
14353
14354  PVT = MVT::i32;
14355  return Promote;
14356}
14357
14358//===----------------------------------------------------------------------===//
14359//                           X86 Inline Assembly Support
14360//===----------------------------------------------------------------------===//
14361
14362bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
14363  InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
14364
14365  std::string AsmStr = IA->getAsmString();
14366
14367  // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
14368  SmallVector<StringRef, 4> AsmPieces;
14369  SplitString(AsmStr, AsmPieces, ";\n");
14370
14371  switch (AsmPieces.size()) {
14372  default: return false;
14373  case 1:
14374    AsmStr = AsmPieces[0];
14375    AsmPieces.clear();
14376    SplitString(AsmStr, AsmPieces, " \t");  // Split with whitespace.
14377
14378    // FIXME: this should verify that we are targeting a 486 or better.  If not,
14379    // we will turn this bswap into something that will be lowered to logical ops
14380    // instead of emitting the bswap asm.  For now, we don't support 486 or lower
14381    // so don't worry about this.
14382    // bswap $0
14383    if (AsmPieces.size() == 2 &&
14384        (AsmPieces[0] == "bswap" ||
14385         AsmPieces[0] == "bswapq" ||
14386         AsmPieces[0] == "bswapl") &&
14387        (AsmPieces[1] == "$0" ||
14388         AsmPieces[1] == "${0:q}")) {
14389      // No need to check constraints, nothing other than the equivalent of
14390      // "=r,0" would be valid here.
14391      IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
14392      if (!Ty || Ty->getBitWidth() % 16 != 0)
14393        return false;
14394      return IntrinsicLowering::LowerToByteSwap(CI);
14395    }
14396    // rorw $$8, ${0:w}  -->  llvm.bswap.i16
14397    if (CI->getType()->isIntegerTy(16) &&
14398        AsmPieces.size() == 3 &&
14399        (AsmPieces[0] == "rorw" || AsmPieces[0] == "rolw") &&
14400        AsmPieces[1] == "$$8," &&
14401        AsmPieces[2] == "${0:w}" &&
14402        IA->getConstraintString().compare(0, 5, "=r,0,") == 0) {
14403      AsmPieces.clear();
14404      const std::string &ConstraintsStr = IA->getConstraintString();
14405      SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
14406      std::sort(AsmPieces.begin(), AsmPieces.end());
14407      if (AsmPieces.size() == 4 &&
14408          AsmPieces[0] == "~{cc}" &&
14409          AsmPieces[1] == "~{dirflag}" &&
14410          AsmPieces[2] == "~{flags}" &&
14411          AsmPieces[3] == "~{fpsr}") {
14412        IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
14413        if (!Ty || Ty->getBitWidth() % 16 != 0)
14414          return false;
14415        return IntrinsicLowering::LowerToByteSwap(CI);
14416      }
14417    }
14418    break;
14419  case 3:
14420    if (CI->getType()->isIntegerTy(32) &&
14421        IA->getConstraintString().compare(0, 5, "=r,0,") == 0) {
14422      SmallVector<StringRef, 4> Words;
14423      SplitString(AsmPieces[0], Words, " \t,");
14424      if (Words.size() == 3 && Words[0] == "rorw" && Words[1] == "$$8" &&
14425          Words[2] == "${0:w}") {
14426        Words.clear();
14427        SplitString(AsmPieces[1], Words, " \t,");
14428        if (Words.size() == 3 && Words[0] == "rorl" && Words[1] == "$$16" &&
14429            Words[2] == "$0") {
14430          Words.clear();
14431          SplitString(AsmPieces[2], Words, " \t,");
14432          if (Words.size() == 3 && Words[0] == "rorw" && Words[1] == "$$8" &&
14433              Words[2] == "${0:w}") {
14434            AsmPieces.clear();
14435            const std::string &ConstraintsStr = IA->getConstraintString();
14436            SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
14437            std::sort(AsmPieces.begin(), AsmPieces.end());
14438            if (AsmPieces.size() == 4 &&
14439                AsmPieces[0] == "~{cc}" &&
14440                AsmPieces[1] == "~{dirflag}" &&
14441                AsmPieces[2] == "~{flags}" &&
14442                AsmPieces[3] == "~{fpsr}") {
14443              IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
14444              if (!Ty || Ty->getBitWidth() % 16 != 0)
14445                return false;
14446              return IntrinsicLowering::LowerToByteSwap(CI);
14447            }
14448          }
14449        }
14450      }
14451    }
14452
14453    if (CI->getType()->isIntegerTy(64)) {
14454      InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
14455      if (Constraints.size() >= 2 &&
14456          Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
14457          Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
14458        // bswap %eax / bswap %edx / xchgl %eax, %edx  -> llvm.bswap.i64
14459        SmallVector<StringRef, 4> Words;
14460        SplitString(AsmPieces[0], Words, " \t");
14461        if (Words.size() == 2 && Words[0] == "bswap" && Words[1] == "%eax") {
14462          Words.clear();
14463          SplitString(AsmPieces[1], Words, " \t");
14464          if (Words.size() == 2 && Words[0] == "bswap" && Words[1] == "%edx") {
14465            Words.clear();
14466            SplitString(AsmPieces[2], Words, " \t,");
14467            if (Words.size() == 3 && Words[0] == "xchgl" && Words[1] == "%eax" &&
14468                Words[2] == "%edx") {
14469              IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
14470              if (!Ty || Ty->getBitWidth() % 16 != 0)
14471                return false;
14472              return IntrinsicLowering::LowerToByteSwap(CI);
14473            }
14474          }
14475        }
14476      }
14477    }
14478    break;
14479  }
14480  return false;
14481}
14482
14483
14484
14485/// getConstraintType - Given a constraint letter, return the type of
14486/// constraint it is for this target.
14487X86TargetLowering::ConstraintType
14488X86TargetLowering::getConstraintType(const std::string &Constraint) const {
14489  if (Constraint.size() == 1) {
14490    switch (Constraint[0]) {
14491    case 'R':
14492    case 'q':
14493    case 'Q':
14494    case 'f':
14495    case 't':
14496    case 'u':
14497    case 'y':
14498    case 'x':
14499    case 'Y':
14500    case 'l':
14501      return C_RegisterClass;
14502    case 'a':
14503    case 'b':
14504    case 'c':
14505    case 'd':
14506    case 'S':
14507    case 'D':
14508    case 'A':
14509      return C_Register;
14510    case 'I':
14511    case 'J':
14512    case 'K':
14513    case 'L':
14514    case 'M':
14515    case 'N':
14516    case 'G':
14517    case 'C':
14518    case 'e':
14519    case 'Z':
14520      return C_Other;
14521    default:
14522      break;
14523    }
14524  }
14525  return TargetLowering::getConstraintType(Constraint);
14526}
14527
14528/// Examine constraint type and operand type and determine a weight value.
14529/// This object must already have been set up with the operand type
14530/// and the current alternative constraint selected.
14531TargetLowering::ConstraintWeight
14532  X86TargetLowering::getSingleConstraintMatchWeight(
14533    AsmOperandInfo &info, const char *constraint) const {
14534  ConstraintWeight weight = CW_Invalid;
14535  Value *CallOperandVal = info.CallOperandVal;
14536    // If we don't have a value, we can't do a match,
14537    // but allow it at the lowest weight.
14538  if (CallOperandVal == NULL)
14539    return CW_Default;
14540  Type *type = CallOperandVal->getType();
14541  // Look at the constraint type.
14542  switch (*constraint) {
14543  default:
14544    weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
14545  case 'R':
14546  case 'q':
14547  case 'Q':
14548  case 'a':
14549  case 'b':
14550  case 'c':
14551  case 'd':
14552  case 'S':
14553  case 'D':
14554  case 'A':
14555    if (CallOperandVal->getType()->isIntegerTy())
14556      weight = CW_SpecificReg;
14557    break;
14558  case 'f':
14559  case 't':
14560  case 'u':
14561      if (type->isFloatingPointTy())
14562        weight = CW_SpecificReg;
14563      break;
14564  case 'y':
14565      if (type->isX86_MMXTy() && Subtarget->hasMMX())
14566        weight = CW_SpecificReg;
14567      break;
14568  case 'x':
14569  case 'Y':
14570    if ((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasXMM())
14571      weight = CW_Register;
14572    break;
14573  case 'I':
14574    if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
14575      if (C->getZExtValue() <= 31)
14576        weight = CW_Constant;
14577    }
14578    break;
14579  case 'J':
14580    if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
14581      if (C->getZExtValue() <= 63)
14582        weight = CW_Constant;
14583    }
14584    break;
14585  case 'K':
14586    if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
14587      if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
14588        weight = CW_Constant;
14589    }
14590    break;
14591  case 'L':
14592    if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
14593      if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
14594        weight = CW_Constant;
14595    }
14596    break;
14597  case 'M':
14598    if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
14599      if (C->getZExtValue() <= 3)
14600        weight = CW_Constant;
14601    }
14602    break;
14603  case 'N':
14604    if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
14605      if (C->getZExtValue() <= 0xff)
14606        weight = CW_Constant;
14607    }
14608    break;
14609  case 'G':
14610  case 'C':
14611    if (dyn_cast<ConstantFP>(CallOperandVal)) {
14612      weight = CW_Constant;
14613    }
14614    break;
14615  case 'e':
14616    if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
14617      if ((C->getSExtValue() >= -0x80000000LL) &&
14618          (C->getSExtValue() <= 0x7fffffffLL))
14619        weight = CW_Constant;
14620    }
14621    break;
14622  case 'Z':
14623    if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
14624      if (C->getZExtValue() <= 0xffffffff)
14625        weight = CW_Constant;
14626    }
14627    break;
14628  }
14629  return weight;
14630}
14631
14632/// LowerXConstraint - try to replace an X constraint, which matches anything,
14633/// with another that has more specific requirements based on the type of the
14634/// corresponding operand.
14635const char *X86TargetLowering::
14636LowerXConstraint(EVT ConstraintVT) const {
14637  // FP X constraints get lowered to SSE1/2 registers if available, otherwise
14638  // 'f' like normal targets.
14639  if (ConstraintVT.isFloatingPoint()) {
14640    if (Subtarget->hasXMMInt())
14641      return "Y";
14642    if (Subtarget->hasXMM())
14643      return "x";
14644  }
14645
14646  return TargetLowering::LowerXConstraint(ConstraintVT);
14647}
14648
14649/// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
14650/// vector.  If it is invalid, don't add anything to Ops.
14651void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
14652                                                     std::string &Constraint,
14653                                                     std::vector<SDValue>&Ops,
14654                                                     SelectionDAG &DAG) const {
14655  SDValue Result(0, 0);
14656
14657  // Only support length 1 constraints for now.
14658  if (Constraint.length() > 1) return;
14659
14660  char ConstraintLetter = Constraint[0];
14661  switch (ConstraintLetter) {
14662  default: break;
14663  case 'I':
14664    if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
14665      if (C->getZExtValue() <= 31) {
14666        Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
14667        break;
14668      }
14669    }
14670    return;
14671  case 'J':
14672    if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
14673      if (C->getZExtValue() <= 63) {
14674        Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
14675        break;
14676      }
14677    }
14678    return;
14679  case 'K':
14680    if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
14681      if ((int8_t)C->getSExtValue() == C->getSExtValue()) {
14682        Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
14683        break;
14684      }
14685    }
14686    return;
14687  case 'N':
14688    if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
14689      if (C->getZExtValue() <= 255) {
14690        Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
14691        break;
14692      }
14693    }
14694    return;
14695  case 'e': {
14696    // 32-bit signed value
14697    if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
14698      if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
14699                                           C->getSExtValue())) {
14700        // Widen to 64 bits here to get it sign extended.
14701        Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
14702        break;
14703      }
14704    // FIXME gcc accepts some relocatable values here too, but only in certain
14705    // memory models; it's complicated.
14706    }
14707    return;
14708  }
14709  case 'Z': {
14710    // 32-bit unsigned value
14711    if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
14712      if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
14713                                           C->getZExtValue())) {
14714        Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
14715        break;
14716      }
14717    }
14718    // FIXME gcc accepts some relocatable values here too, but only in certain
14719    // memory models; it's complicated.
14720    return;
14721  }
14722  case 'i': {
14723    // Literal immediates are always ok.
14724    if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
14725      // Widen to 64 bits here to get it sign extended.
14726      Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
14727      break;
14728    }
14729
14730    // In any sort of PIC mode addresses need to be computed at runtime by
14731    // adding in a register or some sort of table lookup.  These can't
14732    // be used as immediates.
14733    if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
14734      return;
14735
14736    // If we are in non-pic codegen mode, we allow the address of a global (with
14737    // an optional displacement) to be used with 'i'.
14738    GlobalAddressSDNode *GA = 0;
14739    int64_t Offset = 0;
14740
14741    // Match either (GA), (GA+C), (GA+C1+C2), etc.
14742    while (1) {
14743      if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
14744        Offset += GA->getOffset();
14745        break;
14746      } else if (Op.getOpcode() == ISD::ADD) {
14747        if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
14748          Offset += C->getZExtValue();
14749          Op = Op.getOperand(0);
14750          continue;
14751        }
14752      } else if (Op.getOpcode() == ISD::SUB) {
14753        if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
14754          Offset += -C->getZExtValue();
14755          Op = Op.getOperand(0);
14756          continue;
14757        }
14758      }
14759
14760      // Otherwise, this isn't something we can handle, reject it.
14761      return;
14762    }
14763
14764    const GlobalValue *GV = GA->getGlobal();
14765    // If we require an extra load to get this address, as in PIC mode, we
14766    // can't accept it.
14767    if (isGlobalStubReference(Subtarget->ClassifyGlobalReference(GV,
14768                                                        getTargetMachine())))
14769      return;
14770
14771    Result = DAG.getTargetGlobalAddress(GV, Op.getDebugLoc(),
14772                                        GA->getValueType(0), Offset);
14773    break;
14774  }
14775  }
14776
14777  if (Result.getNode()) {
14778    Ops.push_back(Result);
14779    return;
14780  }
14781  return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
14782}
14783
14784std::pair<unsigned, const TargetRegisterClass*>
14785X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
14786                                                EVT VT) const {
14787  // First, see if this is a constraint that directly corresponds to an LLVM
14788  // register class.
14789  if (Constraint.size() == 1) {
14790    // GCC Constraint Letters
14791    switch (Constraint[0]) {
14792    default: break;
14793      // TODO: Slight differences here in allocation order and leaving
14794      // RIP in the class. Do they matter any more here than they do
14795      // in the normal allocation?
14796    case 'q':   // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
14797      if (Subtarget->is64Bit()) {
14798	if (VT == MVT::i32 || VT == MVT::f32)
14799	  return std::make_pair(0U, X86::GR32RegisterClass);
14800	else if (VT == MVT::i16)
14801	  return std::make_pair(0U, X86::GR16RegisterClass);
14802	else if (VT == MVT::i8 || VT == MVT::i1)
14803	  return std::make_pair(0U, X86::GR8RegisterClass);
14804	else if (VT == MVT::i64 || VT == MVT::f64)
14805	  return std::make_pair(0U, X86::GR64RegisterClass);
14806	break;
14807      }
14808      // 32-bit fallthrough
14809    case 'Q':   // Q_REGS
14810      if (VT == MVT::i32 || VT == MVT::f32)
14811	return std::make_pair(0U, X86::GR32_ABCDRegisterClass);
14812      else if (VT == MVT::i16)
14813	return std::make_pair(0U, X86::GR16_ABCDRegisterClass);
14814      else if (VT == MVT::i8 || VT == MVT::i1)
14815	return std::make_pair(0U, X86::GR8_ABCD_LRegisterClass);
14816      else if (VT == MVT::i64)
14817	return std::make_pair(0U, X86::GR64_ABCDRegisterClass);
14818      break;
14819    case 'r':   // GENERAL_REGS
14820    case 'l':   // INDEX_REGS
14821      if (VT == MVT::i8 || VT == MVT::i1)
14822        return std::make_pair(0U, X86::GR8RegisterClass);
14823      if (VT == MVT::i16)
14824        return std::make_pair(0U, X86::GR16RegisterClass);
14825      if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
14826        return std::make_pair(0U, X86::GR32RegisterClass);
14827      return std::make_pair(0U, X86::GR64RegisterClass);
14828    case 'R':   // LEGACY_REGS
14829      if (VT == MVT::i8 || VT == MVT::i1)
14830        return std::make_pair(0U, X86::GR8_NOREXRegisterClass);
14831      if (VT == MVT::i16)
14832        return std::make_pair(0U, X86::GR16_NOREXRegisterClass);
14833      if (VT == MVT::i32 || !Subtarget->is64Bit())
14834        return std::make_pair(0U, X86::GR32_NOREXRegisterClass);
14835      return std::make_pair(0U, X86::GR64_NOREXRegisterClass);
14836    case 'f':  // FP Stack registers.
14837      // If SSE is enabled for this VT, use f80 to ensure the isel moves the
14838      // value to the correct fpstack register class.
14839      if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
14840        return std::make_pair(0U, X86::RFP32RegisterClass);
14841      if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
14842        return std::make_pair(0U, X86::RFP64RegisterClass);
14843      return std::make_pair(0U, X86::RFP80RegisterClass);
14844    case 'y':   // MMX_REGS if MMX allowed.
14845      if (!Subtarget->hasMMX()) break;
14846      return std::make_pair(0U, X86::VR64RegisterClass);
14847    case 'Y':   // SSE_REGS if SSE2 allowed
14848      if (!Subtarget->hasXMMInt()) break;
14849      // FALL THROUGH.
14850    case 'x':   // SSE_REGS if SSE1 allowed
14851      if (!Subtarget->hasXMM()) break;
14852
14853      switch (VT.getSimpleVT().SimpleTy) {
14854      default: break;
14855      // Scalar SSE types.
14856      case MVT::f32:
14857      case MVT::i32:
14858        return std::make_pair(0U, X86::FR32RegisterClass);
14859      case MVT::f64:
14860      case MVT::i64:
14861        return std::make_pair(0U, X86::FR64RegisterClass);
14862      // Vector types.
14863      case MVT::v16i8:
14864      case MVT::v8i16:
14865      case MVT::v4i32:
14866      case MVT::v2i64:
14867      case MVT::v4f32:
14868      case MVT::v2f64:
14869        return std::make_pair(0U, X86::VR128RegisterClass);
14870      }
14871      break;
14872    }
14873  }
14874
14875  // Use the default implementation in TargetLowering to convert the register
14876  // constraint into a member of a register class.
14877  std::pair<unsigned, const TargetRegisterClass*> Res;
14878  Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
14879
14880  // Not found as a standard register?
14881  if (Res.second == 0) {
14882    // Map st(0) -> st(7) -> ST0
14883    if (Constraint.size() == 7 && Constraint[0] == '{' &&
14884        tolower(Constraint[1]) == 's' &&
14885        tolower(Constraint[2]) == 't' &&
14886        Constraint[3] == '(' &&
14887        (Constraint[4] >= '0' && Constraint[4] <= '7') &&
14888        Constraint[5] == ')' &&
14889        Constraint[6] == '}') {
14890
14891      Res.first = X86::ST0+Constraint[4]-'0';
14892      Res.second = X86::RFP80RegisterClass;
14893      return Res;
14894    }
14895
14896    // GCC allows "st(0)" to be called just plain "st".
14897    if (StringRef("{st}").equals_lower(Constraint)) {
14898      Res.first = X86::ST0;
14899      Res.second = X86::RFP80RegisterClass;
14900      return Res;
14901    }
14902
14903    // flags -> EFLAGS
14904    if (StringRef("{flags}").equals_lower(Constraint)) {
14905      Res.first = X86::EFLAGS;
14906      Res.second = X86::CCRRegisterClass;
14907      return Res;
14908    }
14909
14910    // 'A' means EAX + EDX.
14911    if (Constraint == "A") {
14912      Res.first = X86::EAX;
14913      Res.second = X86::GR32_ADRegisterClass;
14914      return Res;
14915    }
14916    return Res;
14917  }
14918
14919  // Otherwise, check to see if this is a register class of the wrong value
14920  // type.  For example, we want to map "{ax},i32" -> {eax}, we don't want it to
14921  // turn into {ax},{dx}.
14922  if (Res.second->hasType(VT))
14923    return Res;   // Correct type already, nothing to do.
14924
14925  // All of the single-register GCC register classes map their values onto
14926  // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp".  If we
14927  // really want an 8-bit or 32-bit register, map to the appropriate register
14928  // class and return the appropriate register.
14929  if (Res.second == X86::GR16RegisterClass) {
14930    if (VT == MVT::i8) {
14931      unsigned DestReg = 0;
14932      switch (Res.first) {
14933      default: break;
14934      case X86::AX: DestReg = X86::AL; break;
14935      case X86::DX: DestReg = X86::DL; break;
14936      case X86::CX: DestReg = X86::CL; break;
14937      case X86::BX: DestReg = X86::BL; break;
14938      }
14939      if (DestReg) {
14940        Res.first = DestReg;
14941        Res.second = X86::GR8RegisterClass;
14942      }
14943    } else if (VT == MVT::i32) {
14944      unsigned DestReg = 0;
14945      switch (Res.first) {
14946      default: break;
14947      case X86::AX: DestReg = X86::EAX; break;
14948      case X86::DX: DestReg = X86::EDX; break;
14949      case X86::CX: DestReg = X86::ECX; break;
14950      case X86::BX: DestReg = X86::EBX; break;
14951      case X86::SI: DestReg = X86::ESI; break;
14952      case X86::DI: DestReg = X86::EDI; break;
14953      case X86::BP: DestReg = X86::EBP; break;
14954      case X86::SP: DestReg = X86::ESP; break;
14955      }
14956      if (DestReg) {
14957        Res.first = DestReg;
14958        Res.second = X86::GR32RegisterClass;
14959      }
14960    } else if (VT == MVT::i64) {
14961      unsigned DestReg = 0;
14962      switch (Res.first) {
14963      default: break;
14964      case X86::AX: DestReg = X86::RAX; break;
14965      case X86::DX: DestReg = X86::RDX; break;
14966      case X86::CX: DestReg = X86::RCX; break;
14967      case X86::BX: DestReg = X86::RBX; break;
14968      case X86::SI: DestReg = X86::RSI; break;
14969      case X86::DI: DestReg = X86::RDI; break;
14970      case X86::BP: DestReg = X86::RBP; break;
14971      case X86::SP: DestReg = X86::RSP; break;
14972      }
14973      if (DestReg) {
14974        Res.first = DestReg;
14975        Res.second = X86::GR64RegisterClass;
14976      }
14977    }
14978  } else if (Res.second == X86::FR32RegisterClass ||
14979             Res.second == X86::FR64RegisterClass ||
14980             Res.second == X86::VR128RegisterClass) {
14981    // Handle references to XMM physical registers that got mapped into the
14982    // wrong class.  This can happen with constraints like {xmm0} where the
14983    // target independent register mapper will just pick the first match it can
14984    // find, ignoring the required type.
14985    if (VT == MVT::f32)
14986      Res.second = X86::FR32RegisterClass;
14987    else if (VT == MVT::f64)
14988      Res.second = X86::FR64RegisterClass;
14989    else if (X86::VR128RegisterClass->hasType(VT))
14990      Res.second = X86::VR128RegisterClass;
14991  }
14992
14993  return Res;
14994}
14995