X86ISelLowering.cpp revision 33390848a7eca75301d04a59b89b516d83e19ee0
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"
54using namespace llvm;
55using namespace dwarf;
56
57STATISTIC(NumTailCalls, "Number of tail calls");
58
59// Forward declarations.
60static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
61                       SDValue V2);
62
63static SDValue Insert128BitVector(SDValue Result,
64                                  SDValue Vec,
65                                  SDValue Idx,
66                                  SelectionDAG &DAG,
67                                  DebugLoc dl);
68
69static SDValue Extract128BitVector(SDValue Vec,
70                                   SDValue Idx,
71                                   SelectionDAG &DAG,
72                                   DebugLoc dl);
73
74static SDValue ConcatVectors(SDValue Lower, SDValue Upper, SelectionDAG &DAG);
75
76
77/// Generate a DAG to grab 128-bits from a vector > 128 bits.  This
78/// sets things up to match to an AVX VEXTRACTF128 instruction or a
79/// simple subregister reference.  Idx is an index in the 128 bits we
80/// want.  It need not be aligned to a 128-bit bounday.  That makes
81/// lowering EXTRACT_VECTOR_ELT operations easier.
82static SDValue Extract128BitVector(SDValue Vec,
83                                   SDValue Idx,
84                                   SelectionDAG &DAG,
85                                   DebugLoc dl) {
86  EVT VT = Vec.getValueType();
87  assert(VT.getSizeInBits() == 256 && "Unexpected vector size!");
88
89  EVT ElVT = VT.getVectorElementType();
90
91  int Factor = VT.getSizeInBits() / 128;
92
93  EVT ResultVT = EVT::getVectorVT(*DAG.getContext(),
94                                  ElVT,
95                                  VT.getVectorNumElements() / Factor);
96
97  // Extract from UNDEF is UNDEF.
98  if (Vec.getOpcode() == ISD::UNDEF)
99    return DAG.getNode(ISD::UNDEF, dl, ResultVT);
100
101  if (isa<ConstantSDNode>(Idx)) {
102    unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
103
104    // Extract the relevant 128 bits.  Generate an EXTRACT_SUBVECTOR
105    // we can match to VEXTRACTF128.
106    unsigned ElemsPerChunk = 128 / ElVT.getSizeInBits();
107
108    // This is the index of the first element of the 128-bit chunk
109    // we want.
110    unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits()) / 128)
111                                 * ElemsPerChunk);
112
113    SDValue VecIdx = DAG.getConstant(NormalizedIdxVal, MVT::i32);
114
115    SDValue Result = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, ResultVT, Vec,
116                                 VecIdx);
117
118    return Result;
119  }
120
121  return SDValue();
122}
123
124/// Generate a DAG to put 128-bits into a vector > 128 bits.  This
125/// sets things up to match to an AVX VINSERTF128 instruction or a
126/// simple superregister reference.  Idx is an index in the 128 bits
127/// we want.  It need not be aligned to a 128-bit bounday.  That makes
128/// lowering INSERT_VECTOR_ELT operations easier.
129static SDValue Insert128BitVector(SDValue Result,
130                                  SDValue Vec,
131                                  SDValue Idx,
132                                  SelectionDAG &DAG,
133                                  DebugLoc dl) {
134  if (isa<ConstantSDNode>(Idx)) {
135    EVT VT = Vec.getValueType();
136    assert(VT.getSizeInBits() == 128 && "Unexpected vector size!");
137
138    EVT ElVT = VT.getVectorElementType();
139
140    unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
141
142    EVT ResultVT = Result.getValueType();
143
144    // Insert the relevant 128 bits.
145    unsigned ElemsPerChunk = 128 / ElVT.getSizeInBits();
146
147    // This is the index of the first element of the 128-bit chunk
148    // we want.
149    unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits()) / 128)
150                                 * ElemsPerChunk);
151
152    SDValue VecIdx = DAG.getConstant(NormalizedIdxVal, MVT::i32);
153
154    Result = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Result, Vec,
155                         VecIdx);
156    return Result;
157  }
158
159  return SDValue();
160}
161
162/// Given two vectors, concat them.
163static SDValue ConcatVectors(SDValue Lower, SDValue Upper, SelectionDAG &DAG) {
164  DebugLoc dl = Lower.getDebugLoc();
165
166  assert(Lower.getValueType() == Upper.getValueType() && "Mismatched vectors!");
167
168  EVT VT = EVT::getVectorVT(*DAG.getContext(),
169                            Lower.getValueType().getVectorElementType(),
170                            Lower.getValueType().getVectorNumElements() * 2);
171
172  // TODO: Generalize to arbitrary vector length (this assumes 256-bit vectors).
173  assert(VT.getSizeInBits() == 256 && "Unsupported vector concat!");
174
175  // Insert the upper subvector.
176  SDValue Vec = Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, VT), Upper,
177                                   DAG.getConstant(
178                                     // This is half the length of the result
179                                     // vector.  Start inserting the upper 128
180                                     // bits here.
181                                     Lower.getValueType().getVectorNumElements(),
182                                     MVT::i32),
183                                   DAG, dl);
184
185  // Insert the lower subvector.
186  Vec = Insert128BitVector(Vec, Lower, DAG.getConstant(0, MVT::i32), DAG, dl);
187  return Vec;
188}
189
190static TargetLoweringObjectFile *createTLOF(X86TargetMachine &TM) {
191  const X86Subtarget *Subtarget = &TM.getSubtarget<X86Subtarget>();
192  bool is64Bit = Subtarget->is64Bit();
193
194  if (Subtarget->isTargetEnvMacho()) {
195    if (is64Bit)
196      return new X8664_MachoTargetObjectFile();
197    return new TargetLoweringObjectFileMachO();
198  }
199
200  if (Subtarget->isTargetELF()) {
201    if (is64Bit)
202      return new X8664_ELFTargetObjectFile(TM);
203    return new X8632_ELFTargetObjectFile(TM);
204  }
205  if (Subtarget->isTargetCOFF() && !Subtarget->isTargetEnvMacho())
206    return new TargetLoweringObjectFileCOFF();
207  llvm_unreachable("unknown subtarget type");
208}
209
210X86TargetLowering::X86TargetLowering(X86TargetMachine &TM)
211  : TargetLowering(TM, createTLOF(TM)) {
212  Subtarget = &TM.getSubtarget<X86Subtarget>();
213  X86ScalarSSEf64 = Subtarget->hasXMMInt();
214  X86ScalarSSEf32 = Subtarget->hasXMM();
215  X86StackPtr = Subtarget->is64Bit() ? X86::RSP : X86::ESP;
216
217  RegInfo = TM.getRegisterInfo();
218  TD = getTargetData();
219
220  // Set up the TargetLowering object.
221  static MVT IntVTs[] = { MVT::i8, MVT::i16, MVT::i32, MVT::i64 };
222
223  // X86 is weird, it always uses i8 for shift amounts and setcc results.
224  setBooleanContents(ZeroOrOneBooleanContent);
225
226  // For 64-bit since we have so many registers use the ILP scheduler, for
227  // 32-bit code use the register pressure specific scheduling.
228  if (Subtarget->is64Bit())
229    setSchedulingPreference(Sched::ILP);
230  else
231    setSchedulingPreference(Sched::RegPressure);
232  setStackPointerRegisterToSaveRestore(X86StackPtr);
233
234  if (Subtarget->isTargetWindows() && !Subtarget->isTargetCygMing()) {
235    // Setup Windows compiler runtime calls.
236    setLibcallName(RTLIB::SDIV_I64, "_alldiv");
237    setLibcallName(RTLIB::UDIV_I64, "_aulldiv");
238    setLibcallName(RTLIB::FPTOUINT_F64_I64, "_ftol2");
239    setLibcallName(RTLIB::FPTOUINT_F32_I64, "_ftol2");
240    setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::X86_StdCall);
241    setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::X86_StdCall);
242    setLibcallCallingConv(RTLIB::FPTOUINT_F64_I64, CallingConv::C);
243    setLibcallCallingConv(RTLIB::FPTOUINT_F32_I64, CallingConv::C);
244  }
245
246  if (Subtarget->isTargetDarwin()) {
247    // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
248    setUseUnderscoreSetJmp(false);
249    setUseUnderscoreLongJmp(false);
250  } else if (Subtarget->isTargetMingw()) {
251    // MS runtime is weird: it exports _setjmp, but longjmp!
252    setUseUnderscoreSetJmp(true);
253    setUseUnderscoreLongJmp(false);
254  } else {
255    setUseUnderscoreSetJmp(true);
256    setUseUnderscoreLongJmp(true);
257  }
258
259  // Set up the register classes.
260  addRegisterClass(MVT::i8, X86::GR8RegisterClass);
261  addRegisterClass(MVT::i16, X86::GR16RegisterClass);
262  addRegisterClass(MVT::i32, X86::GR32RegisterClass);
263  if (Subtarget->is64Bit())
264    addRegisterClass(MVT::i64, X86::GR64RegisterClass);
265
266  setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
267
268  // We don't accept any truncstore of integer registers.
269  setTruncStoreAction(MVT::i64, MVT::i32, Expand);
270  setTruncStoreAction(MVT::i64, MVT::i16, Expand);
271  setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
272  setTruncStoreAction(MVT::i32, MVT::i16, Expand);
273  setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
274  setTruncStoreAction(MVT::i16, MVT::i8,  Expand);
275
276  // SETOEQ and SETUNE require checking two conditions.
277  setCondCodeAction(ISD::SETOEQ, MVT::f32, Expand);
278  setCondCodeAction(ISD::SETOEQ, MVT::f64, Expand);
279  setCondCodeAction(ISD::SETOEQ, MVT::f80, Expand);
280  setCondCodeAction(ISD::SETUNE, MVT::f32, Expand);
281  setCondCodeAction(ISD::SETUNE, MVT::f64, Expand);
282  setCondCodeAction(ISD::SETUNE, MVT::f80, Expand);
283
284  // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
285  // operation.
286  setOperationAction(ISD::UINT_TO_FP       , MVT::i1   , Promote);
287  setOperationAction(ISD::UINT_TO_FP       , MVT::i8   , Promote);
288  setOperationAction(ISD::UINT_TO_FP       , MVT::i16  , Promote);
289
290  if (Subtarget->is64Bit()) {
291    setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Promote);
292    setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Expand);
293  } else if (!UseSoftFloat) {
294    // We have an algorithm for SSE2->double, and we turn this into a
295    // 64-bit FILD followed by conditional FADD for other targets.
296    setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Custom);
297    // We have an algorithm for SSE2, and we turn this into a 64-bit
298    // FILD for other targets.
299    setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Custom);
300  }
301
302  // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
303  // this operation.
304  setOperationAction(ISD::SINT_TO_FP       , MVT::i1   , Promote);
305  setOperationAction(ISD::SINT_TO_FP       , MVT::i8   , Promote);
306
307  if (!UseSoftFloat) {
308    // SSE has no i16 to fp conversion, only i32
309    if (X86ScalarSSEf32) {
310      setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
311      // f32 and f64 cases are Legal, f80 case is not
312      setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
313    } else {
314      setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Custom);
315      setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
316    }
317  } else {
318    setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
319    setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Promote);
320  }
321
322  // In 32-bit mode these are custom lowered.  In 64-bit mode F32 and F64
323  // are Legal, f80 is custom lowered.
324  setOperationAction(ISD::FP_TO_SINT     , MVT::i64  , Custom);
325  setOperationAction(ISD::SINT_TO_FP     , MVT::i64  , Custom);
326
327  // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
328  // this operation.
329  setOperationAction(ISD::FP_TO_SINT       , MVT::i1   , Promote);
330  setOperationAction(ISD::FP_TO_SINT       , MVT::i8   , Promote);
331
332  if (X86ScalarSSEf32) {
333    setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Promote);
334    // f32 and f64 cases are Legal, f80 case is not
335    setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
336  } else {
337    setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Custom);
338    setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
339  }
340
341  // Handle FP_TO_UINT by promoting the destination to a larger signed
342  // conversion.
343  setOperationAction(ISD::FP_TO_UINT       , MVT::i1   , Promote);
344  setOperationAction(ISD::FP_TO_UINT       , MVT::i8   , Promote);
345  setOperationAction(ISD::FP_TO_UINT       , MVT::i16  , Promote);
346
347  if (Subtarget->is64Bit()) {
348    setOperationAction(ISD::FP_TO_UINT     , MVT::i64  , Expand);
349    setOperationAction(ISD::FP_TO_UINT     , MVT::i32  , Promote);
350  } else if (!UseSoftFloat) {
351    if (X86ScalarSSEf32 && !Subtarget->hasSSE3())
352      // Expand FP_TO_UINT into a select.
353      // FIXME: We would like to use a Custom expander here eventually to do
354      // the optimal thing for SSE vs. the default expansion in the legalizer.
355      setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Expand);
356    else
357      // With SSE3 we can use fisttpll to convert to a signed i64; without
358      // SSE, we're stuck with a fistpll.
359      setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Custom);
360  }
361
362  // TODO: when we have SSE, these could be more efficient, by using movd/movq.
363  if (!X86ScalarSSEf64) {
364    setOperationAction(ISD::BITCAST        , MVT::f32  , Expand);
365    setOperationAction(ISD::BITCAST        , MVT::i32  , Expand);
366    if (Subtarget->is64Bit()) {
367      setOperationAction(ISD::BITCAST      , MVT::f64  , Expand);
368      // Without SSE, i64->f64 goes through memory.
369      setOperationAction(ISD::BITCAST      , MVT::i64  , Expand);
370    }
371  }
372
373  // Scalar integer divide and remainder are lowered to use operations that
374  // produce two results, to match the available instructions. This exposes
375  // the two-result form to trivial CSE, which is able to combine x/y and x%y
376  // into a single instruction.
377  //
378  // Scalar integer multiply-high is also lowered to use two-result
379  // operations, to match the available instructions. However, plain multiply
380  // (low) operations are left as Legal, as there are single-result
381  // instructions for this in x86. Using the two-result multiply instructions
382  // when both high and low results are needed must be arranged by dagcombine.
383  for (unsigned i = 0, e = 4; i != e; ++i) {
384    MVT VT = IntVTs[i];
385    setOperationAction(ISD::MULHS, VT, Expand);
386    setOperationAction(ISD::MULHU, VT, Expand);
387    setOperationAction(ISD::SDIV, VT, Expand);
388    setOperationAction(ISD::UDIV, VT, Expand);
389    setOperationAction(ISD::SREM, VT, Expand);
390    setOperationAction(ISD::UREM, VT, Expand);
391
392    // Add/Sub overflow ops with MVT::Glues are lowered to EFLAGS dependences.
393    setOperationAction(ISD::ADDC, VT, Custom);
394    setOperationAction(ISD::ADDE, VT, Custom);
395    setOperationAction(ISD::SUBC, VT, Custom);
396    setOperationAction(ISD::SUBE, VT, Custom);
397  }
398
399  setOperationAction(ISD::BR_JT            , MVT::Other, Expand);
400  setOperationAction(ISD::BRCOND           , MVT::Other, Custom);
401  setOperationAction(ISD::BR_CC            , MVT::Other, Expand);
402  setOperationAction(ISD::SELECT_CC        , MVT::Other, Expand);
403  if (Subtarget->is64Bit())
404    setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
405  setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16  , Legal);
406  setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8   , Legal);
407  setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1   , Expand);
408  setOperationAction(ISD::FP_ROUND_INREG   , MVT::f32  , Expand);
409  setOperationAction(ISD::FREM             , MVT::f32  , Expand);
410  setOperationAction(ISD::FREM             , MVT::f64  , Expand);
411  setOperationAction(ISD::FREM             , MVT::f80  , Expand);
412  setOperationAction(ISD::FLT_ROUNDS_      , MVT::i32  , Custom);
413
414  setOperationAction(ISD::CTTZ             , MVT::i8   , Custom);
415  setOperationAction(ISD::CTLZ             , MVT::i8   , Custom);
416  setOperationAction(ISD::CTTZ             , MVT::i16  , Custom);
417  setOperationAction(ISD::CTLZ             , MVT::i16  , Custom);
418  setOperationAction(ISD::CTTZ             , MVT::i32  , Custom);
419  setOperationAction(ISD::CTLZ             , MVT::i32  , Custom);
420  if (Subtarget->is64Bit()) {
421    setOperationAction(ISD::CTTZ           , MVT::i64  , Custom);
422    setOperationAction(ISD::CTLZ           , MVT::i64  , Custom);
423  }
424
425  if (Subtarget->hasPOPCNT()) {
426    setOperationAction(ISD::CTPOP          , MVT::i8   , Promote);
427  } else {
428    setOperationAction(ISD::CTPOP          , MVT::i8   , Expand);
429    setOperationAction(ISD::CTPOP          , MVT::i16  , Expand);
430    setOperationAction(ISD::CTPOP          , MVT::i32  , Expand);
431    if (Subtarget->is64Bit())
432      setOperationAction(ISD::CTPOP        , MVT::i64  , Expand);
433  }
434
435  setOperationAction(ISD::READCYCLECOUNTER , MVT::i64  , Custom);
436  setOperationAction(ISD::BSWAP            , MVT::i16  , Expand);
437
438  // These should be promoted to a larger select which is supported.
439  setOperationAction(ISD::SELECT          , MVT::i1   , Promote);
440  // X86 wants to expand cmov itself.
441  setOperationAction(ISD::SELECT          , MVT::i8   , Custom);
442  setOperationAction(ISD::SELECT          , MVT::i16  , Custom);
443  setOperationAction(ISD::SELECT          , MVT::i32  , Custom);
444  setOperationAction(ISD::SELECT          , MVT::f32  , Custom);
445  setOperationAction(ISD::SELECT          , MVT::f64  , Custom);
446  setOperationAction(ISD::SELECT          , MVT::f80  , Custom);
447  setOperationAction(ISD::SETCC           , MVT::i8   , Custom);
448  setOperationAction(ISD::SETCC           , MVT::i16  , Custom);
449  setOperationAction(ISD::SETCC           , MVT::i32  , Custom);
450  setOperationAction(ISD::SETCC           , MVT::f32  , Custom);
451  setOperationAction(ISD::SETCC           , MVT::f64  , Custom);
452  setOperationAction(ISD::SETCC           , MVT::f80  , Custom);
453  if (Subtarget->is64Bit()) {
454    setOperationAction(ISD::SELECT        , MVT::i64  , Custom);
455    setOperationAction(ISD::SETCC         , MVT::i64  , Custom);
456  }
457  setOperationAction(ISD::EH_RETURN       , MVT::Other, Custom);
458
459  // Darwin ABI issue.
460  setOperationAction(ISD::ConstantPool    , MVT::i32  , Custom);
461  setOperationAction(ISD::JumpTable       , MVT::i32  , Custom);
462  setOperationAction(ISD::GlobalAddress   , MVT::i32  , Custom);
463  setOperationAction(ISD::GlobalTLSAddress, MVT::i32  , Custom);
464  if (Subtarget->is64Bit())
465    setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
466  setOperationAction(ISD::ExternalSymbol  , MVT::i32  , Custom);
467  setOperationAction(ISD::BlockAddress    , MVT::i32  , Custom);
468  if (Subtarget->is64Bit()) {
469    setOperationAction(ISD::ConstantPool  , MVT::i64  , Custom);
470    setOperationAction(ISD::JumpTable     , MVT::i64  , Custom);
471    setOperationAction(ISD::GlobalAddress , MVT::i64  , Custom);
472    setOperationAction(ISD::ExternalSymbol, MVT::i64  , Custom);
473    setOperationAction(ISD::BlockAddress  , MVT::i64  , Custom);
474  }
475  // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
476  setOperationAction(ISD::SHL_PARTS       , MVT::i32  , Custom);
477  setOperationAction(ISD::SRA_PARTS       , MVT::i32  , Custom);
478  setOperationAction(ISD::SRL_PARTS       , MVT::i32  , Custom);
479  if (Subtarget->is64Bit()) {
480    setOperationAction(ISD::SHL_PARTS     , MVT::i64  , Custom);
481    setOperationAction(ISD::SRA_PARTS     , MVT::i64  , Custom);
482    setOperationAction(ISD::SRL_PARTS     , MVT::i64  , Custom);
483  }
484
485  if (Subtarget->hasXMM())
486    setOperationAction(ISD::PREFETCH      , MVT::Other, Legal);
487
488  // We may not have a libcall for MEMBARRIER so we should lower this.
489  setOperationAction(ISD::MEMBARRIER    , MVT::Other, Custom);
490
491  // On X86 and X86-64, atomic operations are lowered to locked instructions.
492  // Locked instructions, in turn, have implicit fence semantics (all memory
493  // operations are flushed before issuing the locked instruction, and they
494  // are not buffered), so we can fold away the common pattern of
495  // fence-atomic-fence.
496  setShouldFoldAtomicFences(true);
497
498  // Expand certain atomics
499  for (unsigned i = 0, e = 4; i != e; ++i) {
500    MVT VT = IntVTs[i];
501    setOperationAction(ISD::ATOMIC_CMP_SWAP, VT, Custom);
502    setOperationAction(ISD::ATOMIC_LOAD_SUB, VT, Custom);
503  }
504
505  if (!Subtarget->is64Bit()) {
506    setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i64, Custom);
507    setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
508    setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i64, Custom);
509    setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i64, Custom);
510    setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i64, Custom);
511    setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i64, Custom);
512    setOperationAction(ISD::ATOMIC_SWAP, MVT::i64, Custom);
513  }
514
515  // FIXME - use subtarget debug flags
516  if (!Subtarget->isTargetDarwin() &&
517      !Subtarget->isTargetELF() &&
518      !Subtarget->isTargetCygMing()) {
519    setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
520  }
521
522  setOperationAction(ISD::EXCEPTIONADDR, MVT::i64, Expand);
523  setOperationAction(ISD::EHSELECTION,   MVT::i64, Expand);
524  setOperationAction(ISD::EXCEPTIONADDR, MVT::i32, Expand);
525  setOperationAction(ISD::EHSELECTION,   MVT::i32, Expand);
526  if (Subtarget->is64Bit()) {
527    setExceptionPointerRegister(X86::RAX);
528    setExceptionSelectorRegister(X86::RDX);
529  } else {
530    setExceptionPointerRegister(X86::EAX);
531    setExceptionSelectorRegister(X86::EDX);
532  }
533  setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
534  setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
535
536  setOperationAction(ISD::TRAMPOLINE, MVT::Other, Custom);
537
538  setOperationAction(ISD::TRAP, MVT::Other, Legal);
539
540  // VASTART needs to be custom lowered to use the VarArgsFrameIndex
541  setOperationAction(ISD::VASTART           , MVT::Other, Custom);
542  setOperationAction(ISD::VAEND             , MVT::Other, Expand);
543  if (Subtarget->is64Bit()) {
544    setOperationAction(ISD::VAARG           , MVT::Other, Custom);
545    setOperationAction(ISD::VACOPY          , MVT::Other, Custom);
546  } else {
547    setOperationAction(ISD::VAARG           , MVT::Other, Expand);
548    setOperationAction(ISD::VACOPY          , MVT::Other, Expand);
549  }
550
551  setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
552  setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
553  setOperationAction(ISD::DYNAMIC_STACKALLOC,
554                     (Subtarget->is64Bit() ? MVT::i64 : MVT::i32),
555                     (Subtarget->isTargetCOFF()
556                      && !Subtarget->isTargetEnvMacho()
557                      ? Custom : Expand));
558
559  if (!UseSoftFloat && X86ScalarSSEf64) {
560    // f32 and f64 use SSE.
561    // Set up the FP register classes.
562    addRegisterClass(MVT::f32, X86::FR32RegisterClass);
563    addRegisterClass(MVT::f64, X86::FR64RegisterClass);
564
565    // Use ANDPD to simulate FABS.
566    setOperationAction(ISD::FABS , MVT::f64, Custom);
567    setOperationAction(ISD::FABS , MVT::f32, Custom);
568
569    // Use XORP to simulate FNEG.
570    setOperationAction(ISD::FNEG , MVT::f64, Custom);
571    setOperationAction(ISD::FNEG , MVT::f32, Custom);
572
573    // Use ANDPD and ORPD to simulate FCOPYSIGN.
574    setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
575    setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
576
577    // Lower this to FGETSIGNx86 plus an AND.
578    setOperationAction(ISD::FGETSIGN, MVT::i64, Custom);
579    setOperationAction(ISD::FGETSIGN, MVT::i32, Custom);
580
581    // We don't support sin/cos/fmod
582    setOperationAction(ISD::FSIN , MVT::f64, Expand);
583    setOperationAction(ISD::FCOS , MVT::f64, Expand);
584    setOperationAction(ISD::FSIN , MVT::f32, Expand);
585    setOperationAction(ISD::FCOS , MVT::f32, Expand);
586
587    // Expand FP immediates into loads from the stack, except for the special
588    // cases we handle.
589    addLegalFPImmediate(APFloat(+0.0)); // xorpd
590    addLegalFPImmediate(APFloat(+0.0f)); // xorps
591  } else if (!UseSoftFloat && X86ScalarSSEf32) {
592    // Use SSE for f32, x87 for f64.
593    // Set up the FP register classes.
594    addRegisterClass(MVT::f32, X86::FR32RegisterClass);
595    addRegisterClass(MVT::f64, X86::RFP64RegisterClass);
596
597    // Use ANDPS to simulate FABS.
598    setOperationAction(ISD::FABS , MVT::f32, Custom);
599
600    // Use XORP to simulate FNEG.
601    setOperationAction(ISD::FNEG , MVT::f32, Custom);
602
603    setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
604
605    // Use ANDPS and ORPS to simulate FCOPYSIGN.
606    setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
607    setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
608
609    // We don't support sin/cos/fmod
610    setOperationAction(ISD::FSIN , MVT::f32, Expand);
611    setOperationAction(ISD::FCOS , MVT::f32, Expand);
612
613    // Special cases we handle for FP constants.
614    addLegalFPImmediate(APFloat(+0.0f)); // xorps
615    addLegalFPImmediate(APFloat(+0.0)); // FLD0
616    addLegalFPImmediate(APFloat(+1.0)); // FLD1
617    addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
618    addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
619
620    if (!UnsafeFPMath) {
621      setOperationAction(ISD::FSIN           , MVT::f64  , Expand);
622      setOperationAction(ISD::FCOS           , MVT::f64  , Expand);
623    }
624  } else if (!UseSoftFloat) {
625    // f32 and f64 in x87.
626    // Set up the FP register classes.
627    addRegisterClass(MVT::f64, X86::RFP64RegisterClass);
628    addRegisterClass(MVT::f32, X86::RFP32RegisterClass);
629
630    setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
631    setOperationAction(ISD::UNDEF,     MVT::f32, Expand);
632    setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
633    setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
634
635    if (!UnsafeFPMath) {
636      setOperationAction(ISD::FSIN           , MVT::f64  , Expand);
637      setOperationAction(ISD::FCOS           , MVT::f64  , Expand);
638    }
639    addLegalFPImmediate(APFloat(+0.0)); // FLD0
640    addLegalFPImmediate(APFloat(+1.0)); // FLD1
641    addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
642    addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
643    addLegalFPImmediate(APFloat(+0.0f)); // FLD0
644    addLegalFPImmediate(APFloat(+1.0f)); // FLD1
645    addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
646    addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
647  }
648
649  // We don't support FMA.
650  setOperationAction(ISD::FMA, MVT::f64, Expand);
651  setOperationAction(ISD::FMA, MVT::f32, Expand);
652
653  // Long double always uses X87.
654  if (!UseSoftFloat) {
655    addRegisterClass(MVT::f80, X86::RFP80RegisterClass);
656    setOperationAction(ISD::UNDEF,     MVT::f80, Expand);
657    setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
658    {
659      APFloat TmpFlt = APFloat::getZero(APFloat::x87DoubleExtended);
660      addLegalFPImmediate(TmpFlt);  // FLD0
661      TmpFlt.changeSign();
662      addLegalFPImmediate(TmpFlt);  // FLD0/FCHS
663
664      bool ignored;
665      APFloat TmpFlt2(+1.0);
666      TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
667                      &ignored);
668      addLegalFPImmediate(TmpFlt2);  // FLD1
669      TmpFlt2.changeSign();
670      addLegalFPImmediate(TmpFlt2);  // FLD1/FCHS
671    }
672
673    if (!UnsafeFPMath) {
674      setOperationAction(ISD::FSIN           , MVT::f80  , Expand);
675      setOperationAction(ISD::FCOS           , MVT::f80  , Expand);
676    }
677
678    setOperationAction(ISD::FMA, MVT::f80, Expand);
679  }
680
681  // Always use a library call for pow.
682  setOperationAction(ISD::FPOW             , MVT::f32  , Expand);
683  setOperationAction(ISD::FPOW             , MVT::f64  , Expand);
684  setOperationAction(ISD::FPOW             , MVT::f80  , Expand);
685
686  setOperationAction(ISD::FLOG, MVT::f80, Expand);
687  setOperationAction(ISD::FLOG2, MVT::f80, Expand);
688  setOperationAction(ISD::FLOG10, MVT::f80, Expand);
689  setOperationAction(ISD::FEXP, MVT::f80, Expand);
690  setOperationAction(ISD::FEXP2, MVT::f80, Expand);
691
692  // First set operation action for all vector types to either promote
693  // (for widening) or expand (for scalarization). Then we will selectively
694  // turn on ones that can be effectively codegen'd.
695  for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
696       VT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++VT) {
697    setOperationAction(ISD::ADD , (MVT::SimpleValueType)VT, Expand);
698    setOperationAction(ISD::SUB , (MVT::SimpleValueType)VT, Expand);
699    setOperationAction(ISD::FADD, (MVT::SimpleValueType)VT, Expand);
700    setOperationAction(ISD::FNEG, (MVT::SimpleValueType)VT, Expand);
701    setOperationAction(ISD::FSUB, (MVT::SimpleValueType)VT, Expand);
702    setOperationAction(ISD::MUL , (MVT::SimpleValueType)VT, Expand);
703    setOperationAction(ISD::FMUL, (MVT::SimpleValueType)VT, Expand);
704    setOperationAction(ISD::SDIV, (MVT::SimpleValueType)VT, Expand);
705    setOperationAction(ISD::UDIV, (MVT::SimpleValueType)VT, Expand);
706    setOperationAction(ISD::FDIV, (MVT::SimpleValueType)VT, Expand);
707    setOperationAction(ISD::SREM, (MVT::SimpleValueType)VT, Expand);
708    setOperationAction(ISD::UREM, (MVT::SimpleValueType)VT, Expand);
709    setOperationAction(ISD::LOAD, (MVT::SimpleValueType)VT, Expand);
710    setOperationAction(ISD::VECTOR_SHUFFLE, (MVT::SimpleValueType)VT, Expand);
711    setOperationAction(ISD::EXTRACT_VECTOR_ELT,(MVT::SimpleValueType)VT,Expand);
712    setOperationAction(ISD::INSERT_VECTOR_ELT,(MVT::SimpleValueType)VT, Expand);
713    setOperationAction(ISD::EXTRACT_SUBVECTOR,(MVT::SimpleValueType)VT,Expand);
714    setOperationAction(ISD::INSERT_SUBVECTOR,(MVT::SimpleValueType)VT,Expand);
715    setOperationAction(ISD::FABS, (MVT::SimpleValueType)VT, Expand);
716    setOperationAction(ISD::FSIN, (MVT::SimpleValueType)VT, Expand);
717    setOperationAction(ISD::FCOS, (MVT::SimpleValueType)VT, Expand);
718    setOperationAction(ISD::FREM, (MVT::SimpleValueType)VT, Expand);
719    setOperationAction(ISD::FPOWI, (MVT::SimpleValueType)VT, Expand);
720    setOperationAction(ISD::FSQRT, (MVT::SimpleValueType)VT, Expand);
721    setOperationAction(ISD::FCOPYSIGN, (MVT::SimpleValueType)VT, Expand);
722    setOperationAction(ISD::SMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
723    setOperationAction(ISD::UMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
724    setOperationAction(ISD::SDIVREM, (MVT::SimpleValueType)VT, Expand);
725    setOperationAction(ISD::UDIVREM, (MVT::SimpleValueType)VT, Expand);
726    setOperationAction(ISD::FPOW, (MVT::SimpleValueType)VT, Expand);
727    setOperationAction(ISD::CTPOP, (MVT::SimpleValueType)VT, Expand);
728    setOperationAction(ISD::CTTZ, (MVT::SimpleValueType)VT, Expand);
729    setOperationAction(ISD::CTLZ, (MVT::SimpleValueType)VT, Expand);
730    setOperationAction(ISD::SHL, (MVT::SimpleValueType)VT, Expand);
731    setOperationAction(ISD::SRA, (MVT::SimpleValueType)VT, Expand);
732    setOperationAction(ISD::SRL, (MVT::SimpleValueType)VT, Expand);
733    setOperationAction(ISD::ROTL, (MVT::SimpleValueType)VT, Expand);
734    setOperationAction(ISD::ROTR, (MVT::SimpleValueType)VT, Expand);
735    setOperationAction(ISD::BSWAP, (MVT::SimpleValueType)VT, Expand);
736    setOperationAction(ISD::VSETCC, (MVT::SimpleValueType)VT, Expand);
737    setOperationAction(ISD::FLOG, (MVT::SimpleValueType)VT, Expand);
738    setOperationAction(ISD::FLOG2, (MVT::SimpleValueType)VT, Expand);
739    setOperationAction(ISD::FLOG10, (MVT::SimpleValueType)VT, Expand);
740    setOperationAction(ISD::FEXP, (MVT::SimpleValueType)VT, Expand);
741    setOperationAction(ISD::FEXP2, (MVT::SimpleValueType)VT, Expand);
742    setOperationAction(ISD::FP_TO_UINT, (MVT::SimpleValueType)VT, Expand);
743    setOperationAction(ISD::FP_TO_SINT, (MVT::SimpleValueType)VT, Expand);
744    setOperationAction(ISD::UINT_TO_FP, (MVT::SimpleValueType)VT, Expand);
745    setOperationAction(ISD::SINT_TO_FP, (MVT::SimpleValueType)VT, Expand);
746    setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,Expand);
747    setOperationAction(ISD::TRUNCATE,  (MVT::SimpleValueType)VT, Expand);
748    setOperationAction(ISD::SIGN_EXTEND,  (MVT::SimpleValueType)VT, Expand);
749    setOperationAction(ISD::ZERO_EXTEND,  (MVT::SimpleValueType)VT, Expand);
750    setOperationAction(ISD::ANY_EXTEND,  (MVT::SimpleValueType)VT, Expand);
751    for (unsigned InnerVT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
752         InnerVT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
753      setTruncStoreAction((MVT::SimpleValueType)VT,
754                          (MVT::SimpleValueType)InnerVT, Expand);
755    setLoadExtAction(ISD::SEXTLOAD, (MVT::SimpleValueType)VT, Expand);
756    setLoadExtAction(ISD::ZEXTLOAD, (MVT::SimpleValueType)VT, Expand);
757    setLoadExtAction(ISD::EXTLOAD, (MVT::SimpleValueType)VT, Expand);
758  }
759
760  // FIXME: In order to prevent SSE instructions being expanded to MMX ones
761  // with -msoft-float, disable use of MMX as well.
762  if (!UseSoftFloat && Subtarget->hasMMX()) {
763    addRegisterClass(MVT::x86mmx, X86::VR64RegisterClass);
764    // No operations on x86mmx supported, everything uses intrinsics.
765  }
766
767  // MMX-sized vectors (other than x86mmx) are expected to be expanded
768  // into smaller operations.
769  setOperationAction(ISD::MULHS,              MVT::v8i8,  Expand);
770  setOperationAction(ISD::MULHS,              MVT::v4i16, Expand);
771  setOperationAction(ISD::MULHS,              MVT::v2i32, Expand);
772  setOperationAction(ISD::MULHS,              MVT::v1i64, Expand);
773  setOperationAction(ISD::AND,                MVT::v8i8,  Expand);
774  setOperationAction(ISD::AND,                MVT::v4i16, Expand);
775  setOperationAction(ISD::AND,                MVT::v2i32, Expand);
776  setOperationAction(ISD::AND,                MVT::v1i64, Expand);
777  setOperationAction(ISD::OR,                 MVT::v8i8,  Expand);
778  setOperationAction(ISD::OR,                 MVT::v4i16, Expand);
779  setOperationAction(ISD::OR,                 MVT::v2i32, Expand);
780  setOperationAction(ISD::OR,                 MVT::v1i64, Expand);
781  setOperationAction(ISD::XOR,                MVT::v8i8,  Expand);
782  setOperationAction(ISD::XOR,                MVT::v4i16, Expand);
783  setOperationAction(ISD::XOR,                MVT::v2i32, Expand);
784  setOperationAction(ISD::XOR,                MVT::v1i64, Expand);
785  setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i8,  Expand);
786  setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v4i16, Expand);
787  setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v2i32, Expand);
788  setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v1i64, Expand);
789  setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v1i64, Expand);
790  setOperationAction(ISD::SELECT,             MVT::v8i8,  Expand);
791  setOperationAction(ISD::SELECT,             MVT::v4i16, Expand);
792  setOperationAction(ISD::SELECT,             MVT::v2i32, Expand);
793  setOperationAction(ISD::SELECT,             MVT::v1i64, Expand);
794  setOperationAction(ISD::BITCAST,            MVT::v8i8,  Expand);
795  setOperationAction(ISD::BITCAST,            MVT::v4i16, Expand);
796  setOperationAction(ISD::BITCAST,            MVT::v2i32, Expand);
797  setOperationAction(ISD::BITCAST,            MVT::v1i64, Expand);
798
799  if (!UseSoftFloat && Subtarget->hasXMM()) {
800    addRegisterClass(MVT::v4f32, X86::VR128RegisterClass);
801
802    setOperationAction(ISD::FADD,               MVT::v4f32, Legal);
803    setOperationAction(ISD::FSUB,               MVT::v4f32, Legal);
804    setOperationAction(ISD::FMUL,               MVT::v4f32, Legal);
805    setOperationAction(ISD::FDIV,               MVT::v4f32, Legal);
806    setOperationAction(ISD::FSQRT,              MVT::v4f32, Legal);
807    setOperationAction(ISD::FNEG,               MVT::v4f32, Custom);
808    setOperationAction(ISD::LOAD,               MVT::v4f32, Legal);
809    setOperationAction(ISD::BUILD_VECTOR,       MVT::v4f32, Custom);
810    setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4f32, Custom);
811    setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
812    setOperationAction(ISD::SELECT,             MVT::v4f32, Custom);
813    setOperationAction(ISD::VSETCC,             MVT::v4f32, Custom);
814  }
815
816  if (!UseSoftFloat && Subtarget->hasXMMInt()) {
817    addRegisterClass(MVT::v2f64, X86::VR128RegisterClass);
818
819    // FIXME: Unfortunately -soft-float and -no-implicit-float means XMM
820    // registers cannot be used even for integer operations.
821    addRegisterClass(MVT::v16i8, X86::VR128RegisterClass);
822    addRegisterClass(MVT::v8i16, X86::VR128RegisterClass);
823    addRegisterClass(MVT::v4i32, X86::VR128RegisterClass);
824    addRegisterClass(MVT::v2i64, X86::VR128RegisterClass);
825
826    setOperationAction(ISD::ADD,                MVT::v16i8, Legal);
827    setOperationAction(ISD::ADD,                MVT::v8i16, Legal);
828    setOperationAction(ISD::ADD,                MVT::v4i32, Legal);
829    setOperationAction(ISD::ADD,                MVT::v2i64, Legal);
830    setOperationAction(ISD::MUL,                MVT::v2i64, Custom);
831    setOperationAction(ISD::SUB,                MVT::v16i8, Legal);
832    setOperationAction(ISD::SUB,                MVT::v8i16, Legal);
833    setOperationAction(ISD::SUB,                MVT::v4i32, Legal);
834    setOperationAction(ISD::SUB,                MVT::v2i64, Legal);
835    setOperationAction(ISD::MUL,                MVT::v8i16, Legal);
836    setOperationAction(ISD::FADD,               MVT::v2f64, Legal);
837    setOperationAction(ISD::FSUB,               MVT::v2f64, Legal);
838    setOperationAction(ISD::FMUL,               MVT::v2f64, Legal);
839    setOperationAction(ISD::FDIV,               MVT::v2f64, Legal);
840    setOperationAction(ISD::FSQRT,              MVT::v2f64, Legal);
841    setOperationAction(ISD::FNEG,               MVT::v2f64, Custom);
842
843    setOperationAction(ISD::VSETCC,             MVT::v2f64, Custom);
844    setOperationAction(ISD::VSETCC,             MVT::v16i8, Custom);
845    setOperationAction(ISD::VSETCC,             MVT::v8i16, Custom);
846    setOperationAction(ISD::VSETCC,             MVT::v4i32, Custom);
847
848    setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v16i8, Custom);
849    setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i16, Custom);
850    setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
851    setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
852    setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
853
854    setOperationAction(ISD::CONCAT_VECTORS,     MVT::v2f64, Custom);
855    setOperationAction(ISD::CONCAT_VECTORS,     MVT::v2i64, Custom);
856    setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i8, Custom);
857    setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i16, Custom);
858    setOperationAction(ISD::CONCAT_VECTORS,     MVT::v4i32, Custom);
859
860    // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
861    for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v2i64; ++i) {
862      EVT VT = (MVT::SimpleValueType)i;
863      // Do not attempt to custom lower non-power-of-2 vectors
864      if (!isPowerOf2_32(VT.getVectorNumElements()))
865        continue;
866      // Do not attempt to custom lower non-128-bit vectors
867      if (!VT.is128BitVector())
868        continue;
869      setOperationAction(ISD::BUILD_VECTOR,
870                         VT.getSimpleVT().SimpleTy, Custom);
871      setOperationAction(ISD::VECTOR_SHUFFLE,
872                         VT.getSimpleVT().SimpleTy, Custom);
873      setOperationAction(ISD::EXTRACT_VECTOR_ELT,
874                         VT.getSimpleVT().SimpleTy, Custom);
875    }
876
877    setOperationAction(ISD::BUILD_VECTOR,       MVT::v2f64, Custom);
878    setOperationAction(ISD::BUILD_VECTOR,       MVT::v2i64, Custom);
879    setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2f64, Custom);
880    setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2i64, Custom);
881    setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2f64, Custom);
882    setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
883
884    if (Subtarget->is64Bit()) {
885      setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
886      setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
887    }
888
889    // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
890    for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v2i64; i++) {
891      MVT::SimpleValueType SVT = (MVT::SimpleValueType)i;
892      EVT VT = SVT;
893
894      // Do not attempt to promote non-128-bit vectors
895      if (!VT.is128BitVector())
896        continue;
897
898      setOperationAction(ISD::AND,    SVT, Promote);
899      AddPromotedToType (ISD::AND,    SVT, MVT::v2i64);
900      setOperationAction(ISD::OR,     SVT, Promote);
901      AddPromotedToType (ISD::OR,     SVT, MVT::v2i64);
902      setOperationAction(ISD::XOR,    SVT, Promote);
903      AddPromotedToType (ISD::XOR,    SVT, MVT::v2i64);
904      setOperationAction(ISD::LOAD,   SVT, Promote);
905      AddPromotedToType (ISD::LOAD,   SVT, MVT::v2i64);
906      setOperationAction(ISD::SELECT, SVT, Promote);
907      AddPromotedToType (ISD::SELECT, SVT, MVT::v2i64);
908    }
909
910    setTruncStoreAction(MVT::f64, MVT::f32, Expand);
911
912    // Custom lower v2i64 and v2f64 selects.
913    setOperationAction(ISD::LOAD,               MVT::v2f64, Legal);
914    setOperationAction(ISD::LOAD,               MVT::v2i64, Legal);
915    setOperationAction(ISD::SELECT,             MVT::v2f64, Custom);
916    setOperationAction(ISD::SELECT,             MVT::v2i64, Custom);
917
918    setOperationAction(ISD::FP_TO_SINT,         MVT::v4i32, Legal);
919    setOperationAction(ISD::SINT_TO_FP,         MVT::v4i32, Legal);
920  }
921
922  if (Subtarget->hasSSE41()) {
923    setOperationAction(ISD::FFLOOR,             MVT::f32,   Legal);
924    setOperationAction(ISD::FCEIL,              MVT::f32,   Legal);
925    setOperationAction(ISD::FTRUNC,             MVT::f32,   Legal);
926    setOperationAction(ISD::FRINT,              MVT::f32,   Legal);
927    setOperationAction(ISD::FNEARBYINT,         MVT::f32,   Legal);
928    setOperationAction(ISD::FFLOOR,             MVT::f64,   Legal);
929    setOperationAction(ISD::FCEIL,              MVT::f64,   Legal);
930    setOperationAction(ISD::FTRUNC,             MVT::f64,   Legal);
931    setOperationAction(ISD::FRINT,              MVT::f64,   Legal);
932    setOperationAction(ISD::FNEARBYINT,         MVT::f64,   Legal);
933
934    // FIXME: Do we need to handle scalar-to-vector here?
935    setOperationAction(ISD::MUL,                MVT::v4i32, Legal);
936
937    // Can turn SHL into an integer multiply.
938    setOperationAction(ISD::SHL,                MVT::v4i32, Custom);
939    setOperationAction(ISD::SHL,                MVT::v16i8, Custom);
940
941    // i8 and i16 vectors are custom , because the source register and source
942    // source memory operand types are not the same width.  f32 vectors are
943    // custom since the immediate controlling the insert encodes additional
944    // information.
945    setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i8, Custom);
946    setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
947    setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
948    setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
949
950    setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
951    setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
952    setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
953    setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
954
955    if (Subtarget->is64Bit()) {
956      setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Legal);
957      setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Legal);
958    }
959  }
960
961  if (Subtarget->hasSSE2()) {
962    setOperationAction(ISD::SRL,               MVT::v2i64, Custom);
963    setOperationAction(ISD::SRL,               MVT::v4i32, Custom);
964    setOperationAction(ISD::SRL,               MVT::v16i8, Custom);
965
966    setOperationAction(ISD::SHL,               MVT::v2i64, Custom);
967    setOperationAction(ISD::SHL,               MVT::v4i32, Custom);
968    setOperationAction(ISD::SHL,               MVT::v8i16, Custom);
969
970    setOperationAction(ISD::SRA,               MVT::v4i32, Custom);
971    setOperationAction(ISD::SRA,               MVT::v8i16, Custom);
972  }
973
974  if (Subtarget->hasSSE42())
975    setOperationAction(ISD::VSETCC,             MVT::v2i64, Custom);
976
977  if (!UseSoftFloat && Subtarget->hasAVX()) {
978    addRegisterClass(MVT::v8f32, X86::VR256RegisterClass);
979    addRegisterClass(MVT::v4f64, X86::VR256RegisterClass);
980    addRegisterClass(MVT::v8i32, X86::VR256RegisterClass);
981    addRegisterClass(MVT::v4i64, X86::VR256RegisterClass);
982    addRegisterClass(MVT::v32i8, X86::VR256RegisterClass);
983
984    setOperationAction(ISD::LOAD,               MVT::v8f32, Legal);
985    setOperationAction(ISD::LOAD,               MVT::v8i32, Legal);
986    setOperationAction(ISD::LOAD,               MVT::v4f64, Legal);
987    setOperationAction(ISD::LOAD,               MVT::v4i64, Legal);
988
989    setOperationAction(ISD::FADD,               MVT::v8f32, Legal);
990    setOperationAction(ISD::FSUB,               MVT::v8f32, Legal);
991    setOperationAction(ISD::FMUL,               MVT::v8f32, Legal);
992    setOperationAction(ISD::FDIV,               MVT::v8f32, Legal);
993    setOperationAction(ISD::FSQRT,              MVT::v8f32, Legal);
994    setOperationAction(ISD::FNEG,               MVT::v8f32, Custom);
995
996    setOperationAction(ISD::FADD,               MVT::v4f64, Legal);
997    setOperationAction(ISD::FSUB,               MVT::v4f64, Legal);
998    setOperationAction(ISD::FMUL,               MVT::v4f64, Legal);
999    setOperationAction(ISD::FDIV,               MVT::v4f64, Legal);
1000    setOperationAction(ISD::FSQRT,              MVT::v4f64, Legal);
1001    setOperationAction(ISD::FNEG,               MVT::v4f64, Custom);
1002
1003    // Custom lower build_vector, vector_shuffle, scalar_to_vector,
1004    // insert_vector_elt extract_subvector and extract_vector_elt for
1005    // 256-bit types.
1006    for (unsigned i = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
1007         i <= (unsigned)MVT::LAST_VECTOR_VALUETYPE;
1008         ++i) {
1009      MVT::SimpleValueType VT = (MVT::SimpleValueType)i;
1010      // Do not attempt to custom lower non-256-bit vectors
1011      if (!isPowerOf2_32(MVT(VT).getVectorNumElements())
1012          || (MVT(VT).getSizeInBits() < 256))
1013        continue;
1014      setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
1015      setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
1016      setOperationAction(ISD::INSERT_VECTOR_ELT,  VT, Custom);
1017      setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1018      setOperationAction(ISD::SCALAR_TO_VECTOR,   VT, Custom);
1019    }
1020    // Custom-lower insert_subvector and extract_subvector based on
1021    // the result type.
1022    for (unsigned i = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
1023         i <= (unsigned)MVT::LAST_VECTOR_VALUETYPE;
1024         ++i) {
1025      MVT::SimpleValueType VT = (MVT::SimpleValueType)i;
1026      // Do not attempt to custom lower non-256-bit vectors
1027      if (!isPowerOf2_32(MVT(VT).getVectorNumElements()))
1028        continue;
1029
1030      if (MVT(VT).getSizeInBits() == 128) {
1031        setOperationAction(ISD::EXTRACT_SUBVECTOR,  VT, Custom);
1032      }
1033      else if (MVT(VT).getSizeInBits() == 256) {
1034        setOperationAction(ISD::INSERT_SUBVECTOR,  VT, Custom);
1035      }
1036    }
1037
1038    // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
1039    // Don't promote loads because we need them for VPERM vector index versions.
1040
1041    for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
1042         VT != (unsigned)MVT::LAST_VECTOR_VALUETYPE;
1043         VT++) {
1044      if (!isPowerOf2_32(MVT((MVT::SimpleValueType)VT).getVectorNumElements())
1045          || (MVT((MVT::SimpleValueType)VT).getSizeInBits() < 256))
1046        continue;
1047      setOperationAction(ISD::AND,    (MVT::SimpleValueType)VT, Promote);
1048      AddPromotedToType (ISD::AND,    (MVT::SimpleValueType)VT, MVT::v4i64);
1049      setOperationAction(ISD::OR,     (MVT::SimpleValueType)VT, Promote);
1050      AddPromotedToType (ISD::OR,     (MVT::SimpleValueType)VT, MVT::v4i64);
1051      setOperationAction(ISD::XOR,    (MVT::SimpleValueType)VT, Promote);
1052      AddPromotedToType (ISD::XOR,    (MVT::SimpleValueType)VT, MVT::v4i64);
1053      //setOperationAction(ISD::LOAD,   (MVT::SimpleValueType)VT, Promote);
1054      //AddPromotedToType (ISD::LOAD,   (MVT::SimpleValueType)VT, MVT::v4i64);
1055      setOperationAction(ISD::SELECT, (MVT::SimpleValueType)VT, Promote);
1056      AddPromotedToType (ISD::SELECT, (MVT::SimpleValueType)VT, MVT::v4i64);
1057    }
1058  }
1059
1060  // We want to custom lower some of our intrinsics.
1061  setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1062
1063
1064  // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1065  // handle type legalization for these operations here.
1066  //
1067  // FIXME: We really should do custom legalization for addition and
1068  // subtraction on x86-32 once PR3203 is fixed.  We really can't do much better
1069  // than generic legalization for 64-bit multiplication-with-overflow, though.
1070  for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) {
1071    // Add/Sub/Mul with overflow operations are custom lowered.
1072    MVT VT = IntVTs[i];
1073    setOperationAction(ISD::SADDO, VT, Custom);
1074    setOperationAction(ISD::UADDO, VT, Custom);
1075    setOperationAction(ISD::SSUBO, VT, Custom);
1076    setOperationAction(ISD::USUBO, VT, Custom);
1077    setOperationAction(ISD::SMULO, VT, Custom);
1078    setOperationAction(ISD::UMULO, VT, Custom);
1079  }
1080
1081  // There are no 8-bit 3-address imul/mul instructions
1082  setOperationAction(ISD::SMULO, MVT::i8, Expand);
1083  setOperationAction(ISD::UMULO, MVT::i8, Expand);
1084
1085  if (!Subtarget->is64Bit()) {
1086    // These libcalls are not available in 32-bit.
1087    setLibcallName(RTLIB::SHL_I128, 0);
1088    setLibcallName(RTLIB::SRL_I128, 0);
1089    setLibcallName(RTLIB::SRA_I128, 0);
1090  }
1091
1092  // We have target-specific dag combine patterns for the following nodes:
1093  setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1094  setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1095  setTargetDAGCombine(ISD::BUILD_VECTOR);
1096  setTargetDAGCombine(ISD::SELECT);
1097  setTargetDAGCombine(ISD::SHL);
1098  setTargetDAGCombine(ISD::SRA);
1099  setTargetDAGCombine(ISD::SRL);
1100  setTargetDAGCombine(ISD::OR);
1101  setTargetDAGCombine(ISD::AND);
1102  setTargetDAGCombine(ISD::ADD);
1103  setTargetDAGCombine(ISD::SUB);
1104  setTargetDAGCombine(ISD::STORE);
1105  setTargetDAGCombine(ISD::ZERO_EXTEND);
1106  setTargetDAGCombine(ISD::SINT_TO_FP);
1107  if (Subtarget->is64Bit())
1108    setTargetDAGCombine(ISD::MUL);
1109
1110  computeRegisterProperties();
1111
1112  // On Darwin, -Os means optimize for size without hurting performance,
1113  // do not reduce the limit.
1114  maxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1115  maxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 16 : 8;
1116  maxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1117  maxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1118  maxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1119  maxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1120  setPrefLoopAlignment(16);
1121  benefitFromCodePlacementOpt = true;
1122
1123  setPrefFunctionAlignment(4);
1124}
1125
1126
1127MVT::SimpleValueType X86TargetLowering::getSetCCResultType(EVT VT) const {
1128  return MVT::i8;
1129}
1130
1131
1132/// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1133/// the desired ByVal argument alignment.
1134static void getMaxByValAlign(const Type *Ty, unsigned &MaxAlign) {
1135  if (MaxAlign == 16)
1136    return;
1137  if (const VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1138    if (VTy->getBitWidth() == 128)
1139      MaxAlign = 16;
1140  } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1141    unsigned EltAlign = 0;
1142    getMaxByValAlign(ATy->getElementType(), EltAlign);
1143    if (EltAlign > MaxAlign)
1144      MaxAlign = EltAlign;
1145  } else if (const StructType *STy = dyn_cast<StructType>(Ty)) {
1146    for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1147      unsigned EltAlign = 0;
1148      getMaxByValAlign(STy->getElementType(i), EltAlign);
1149      if (EltAlign > MaxAlign)
1150        MaxAlign = EltAlign;
1151      if (MaxAlign == 16)
1152        break;
1153    }
1154  }
1155  return;
1156}
1157
1158/// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1159/// function arguments in the caller parameter area. For X86, aggregates
1160/// that contain SSE vectors are placed at 16-byte boundaries while the rest
1161/// are at 4-byte boundaries.
1162unsigned X86TargetLowering::getByValTypeAlignment(const Type *Ty) const {
1163  if (Subtarget->is64Bit()) {
1164    // Max of 8 and alignment of type.
1165    unsigned TyAlign = TD->getABITypeAlignment(Ty);
1166    if (TyAlign > 8)
1167      return TyAlign;
1168    return 8;
1169  }
1170
1171  unsigned Align = 4;
1172  if (Subtarget->hasXMM())
1173    getMaxByValAlign(Ty, Align);
1174  return Align;
1175}
1176
1177/// getOptimalMemOpType - Returns the target specific optimal type for load
1178/// and store operations as a result of memset, memcpy, and memmove
1179/// lowering. If DstAlign is zero that means it's safe to destination
1180/// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1181/// means there isn't a need to check it against alignment requirement,
1182/// probably because the source does not need to be loaded. If
1183/// 'NonScalarIntSafe' is true, that means it's safe to return a
1184/// non-scalar-integer type, e.g. empty string source, constant, or loaded
1185/// from memory. 'MemcpyStrSrc' indicates whether the memcpy source is
1186/// constant so it does not need to be loaded.
1187/// It returns EVT::Other if the type should be determined using generic
1188/// target-independent logic.
1189EVT
1190X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1191                                       unsigned DstAlign, unsigned SrcAlign,
1192                                       bool NonScalarIntSafe,
1193                                       bool MemcpyStrSrc,
1194                                       MachineFunction &MF) const {
1195  // FIXME: This turns off use of xmm stores for memset/memcpy on targets like
1196  // linux.  This is because the stack realignment code can't handle certain
1197  // cases like PR2962.  This should be removed when PR2962 is fixed.
1198  const Function *F = MF.getFunction();
1199  if (NonScalarIntSafe &&
1200      !F->hasFnAttr(Attribute::NoImplicitFloat)) {
1201    if (Size >= 16 &&
1202        (Subtarget->isUnalignedMemAccessFast() ||
1203         ((DstAlign == 0 || DstAlign >= 16) &&
1204          (SrcAlign == 0 || SrcAlign >= 16))) &&
1205        Subtarget->getStackAlignment() >= 16) {
1206      if (Subtarget->hasSSE2())
1207        return MVT::v4i32;
1208      if (Subtarget->hasSSE1())
1209        return MVT::v4f32;
1210    } else if (!MemcpyStrSrc && Size >= 8 &&
1211               !Subtarget->is64Bit() &&
1212               Subtarget->getStackAlignment() >= 8 &&
1213               Subtarget->hasXMMInt()) {
1214      // Do not use f64 to lower memcpy if source is string constant. It's
1215      // better to use i32 to avoid the loads.
1216      return MVT::f64;
1217    }
1218  }
1219  if (Subtarget->is64Bit() && Size >= 8)
1220    return MVT::i64;
1221  return MVT::i32;
1222}
1223
1224/// getJumpTableEncoding - Return the entry encoding for a jump table in the
1225/// current function.  The returned value is a member of the
1226/// MachineJumpTableInfo::JTEntryKind enum.
1227unsigned X86TargetLowering::getJumpTableEncoding() const {
1228  // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1229  // symbol.
1230  if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1231      Subtarget->isPICStyleGOT())
1232    return MachineJumpTableInfo::EK_Custom32;
1233
1234  // Otherwise, use the normal jump table encoding heuristics.
1235  return TargetLowering::getJumpTableEncoding();
1236}
1237
1238const MCExpr *
1239X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1240                                             const MachineBasicBlock *MBB,
1241                                             unsigned uid,MCContext &Ctx) const{
1242  assert(getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1243         Subtarget->isPICStyleGOT());
1244  // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1245  // entries.
1246  return MCSymbolRefExpr::Create(MBB->getSymbol(),
1247                                 MCSymbolRefExpr::VK_GOTOFF, Ctx);
1248}
1249
1250/// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
1251/// jumptable.
1252SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1253                                                    SelectionDAG &DAG) const {
1254  if (!Subtarget->is64Bit())
1255    // This doesn't have DebugLoc associated with it, but is not really the
1256    // same as a Register.
1257    return DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), getPointerTy());
1258  return Table;
1259}
1260
1261/// getPICJumpTableRelocBaseExpr - This returns the relocation base for the
1262/// given PIC jumptable, the same as getPICJumpTableRelocBase, but as an
1263/// MCExpr.
1264const MCExpr *X86TargetLowering::
1265getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1266                             MCContext &Ctx) const {
1267  // X86-64 uses RIP relative addressing based on the jump table label.
1268  if (Subtarget->isPICStyleRIPRel())
1269    return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1270
1271  // Otherwise, the reference is relative to the PIC base.
1272  return MCSymbolRefExpr::Create(MF->getPICBaseSymbol(), Ctx);
1273}
1274
1275// FIXME: Why this routine is here? Move to RegInfo!
1276std::pair<const TargetRegisterClass*, uint8_t>
1277X86TargetLowering::findRepresentativeClass(EVT VT) const{
1278  const TargetRegisterClass *RRC = 0;
1279  uint8_t Cost = 1;
1280  switch (VT.getSimpleVT().SimpleTy) {
1281  default:
1282    return TargetLowering::findRepresentativeClass(VT);
1283  case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1284    RRC = (Subtarget->is64Bit()
1285           ? X86::GR64RegisterClass : X86::GR32RegisterClass);
1286    break;
1287  case MVT::x86mmx:
1288    RRC = X86::VR64RegisterClass;
1289    break;
1290  case MVT::f32: case MVT::f64:
1291  case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1292  case MVT::v4f32: case MVT::v2f64:
1293  case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
1294  case MVT::v4f64:
1295    RRC = X86::VR128RegisterClass;
1296    break;
1297  }
1298  return std::make_pair(RRC, Cost);
1299}
1300
1301bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
1302                                               unsigned &Offset) const {
1303  if (!Subtarget->isTargetLinux())
1304    return false;
1305
1306  if (Subtarget->is64Bit()) {
1307    // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
1308    Offset = 0x28;
1309    if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
1310      AddressSpace = 256;
1311    else
1312      AddressSpace = 257;
1313  } else {
1314    // %gs:0x14 on i386
1315    Offset = 0x14;
1316    AddressSpace = 256;
1317  }
1318  return true;
1319}
1320
1321
1322//===----------------------------------------------------------------------===//
1323//               Return Value Calling Convention Implementation
1324//===----------------------------------------------------------------------===//
1325
1326#include "X86GenCallingConv.inc"
1327
1328bool
1329X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv,
1330				  MachineFunction &MF, bool isVarArg,
1331                        const SmallVectorImpl<ISD::OutputArg> &Outs,
1332                        LLVMContext &Context) const {
1333  SmallVector<CCValAssign, 16> RVLocs;
1334  CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1335                 RVLocs, Context);
1336  return CCInfo.CheckReturn(Outs, RetCC_X86);
1337}
1338
1339SDValue
1340X86TargetLowering::LowerReturn(SDValue Chain,
1341                               CallingConv::ID CallConv, bool isVarArg,
1342                               const SmallVectorImpl<ISD::OutputArg> &Outs,
1343                               const SmallVectorImpl<SDValue> &OutVals,
1344                               DebugLoc dl, SelectionDAG &DAG) const {
1345  MachineFunction &MF = DAG.getMachineFunction();
1346  X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1347
1348  SmallVector<CCValAssign, 16> RVLocs;
1349  CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1350                 RVLocs, *DAG.getContext());
1351  CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1352
1353  // Add the regs to the liveout set for the function.
1354  MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
1355  for (unsigned i = 0; i != RVLocs.size(); ++i)
1356    if (RVLocs[i].isRegLoc() && !MRI.isLiveOut(RVLocs[i].getLocReg()))
1357      MRI.addLiveOut(RVLocs[i].getLocReg());
1358
1359  SDValue Flag;
1360
1361  SmallVector<SDValue, 6> RetOps;
1362  RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1363  // Operand #1 = Bytes To Pop
1364  RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(),
1365                   MVT::i16));
1366
1367  // Copy the result values into the output registers.
1368  for (unsigned i = 0; i != RVLocs.size(); ++i) {
1369    CCValAssign &VA = RVLocs[i];
1370    assert(VA.isRegLoc() && "Can only return in registers!");
1371    SDValue ValToCopy = OutVals[i];
1372    EVT ValVT = ValToCopy.getValueType();
1373
1374    // If this is x86-64, and we disabled SSE, we can't return FP values,
1375    // or SSE or MMX vectors.
1376    if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
1377         VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
1378          (Subtarget->is64Bit() && !Subtarget->hasXMM())) {
1379      report_fatal_error("SSE register return with SSE disabled");
1380    }
1381    // Likewise we can't return F64 values with SSE1 only.  gcc does so, but
1382    // llvm-gcc has never done it right and no one has noticed, so this
1383    // should be OK for now.
1384    if (ValVT == MVT::f64 &&
1385        (Subtarget->is64Bit() && !Subtarget->hasXMMInt()))
1386      report_fatal_error("SSE2 register return with SSE2 disabled");
1387
1388    // Returns in ST0/ST1 are handled specially: these are pushed as operands to
1389    // the RET instruction and handled by the FP Stackifier.
1390    if (VA.getLocReg() == X86::ST0 ||
1391        VA.getLocReg() == X86::ST1) {
1392      // If this is a copy from an xmm register to ST(0), use an FPExtend to
1393      // change the value to the FP stack register class.
1394      if (isScalarFPTypeInSSEReg(VA.getValVT()))
1395        ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
1396      RetOps.push_back(ValToCopy);
1397      // Don't emit a copytoreg.
1398      continue;
1399    }
1400
1401    // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
1402    // which is returned in RAX / RDX.
1403    if (Subtarget->is64Bit()) {
1404      if (ValVT == MVT::x86mmx) {
1405        if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1406          ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ValToCopy);
1407          ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
1408                                  ValToCopy);
1409          // If we don't have SSE2 available, convert to v4f32 so the generated
1410          // register is legal.
1411          if (!Subtarget->hasSSE2())
1412            ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32,ValToCopy);
1413        }
1414      }
1415    }
1416
1417    Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
1418    Flag = Chain.getValue(1);
1419  }
1420
1421  // The x86-64 ABI for returning structs by value requires that we copy
1422  // the sret argument into %rax for the return. We saved the argument into
1423  // a virtual register in the entry block, so now we copy the value out
1424  // and into %rax.
1425  if (Subtarget->is64Bit() &&
1426      DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
1427    MachineFunction &MF = DAG.getMachineFunction();
1428    X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1429    unsigned Reg = FuncInfo->getSRetReturnReg();
1430    assert(Reg &&
1431           "SRetReturnReg should have been set in LowerFormalArguments().");
1432    SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
1433
1434    Chain = DAG.getCopyToReg(Chain, dl, X86::RAX, Val, Flag);
1435    Flag = Chain.getValue(1);
1436
1437    // RAX now acts like a return value.
1438    MRI.addLiveOut(X86::RAX);
1439  }
1440
1441  RetOps[0] = Chain;  // Update chain.
1442
1443  // Add the flag if we have it.
1444  if (Flag.getNode())
1445    RetOps.push_back(Flag);
1446
1447  return DAG.getNode(X86ISD::RET_FLAG, dl,
1448                     MVT::Other, &RetOps[0], RetOps.size());
1449}
1450
1451bool X86TargetLowering::isUsedByReturnOnly(SDNode *N) const {
1452  if (N->getNumValues() != 1)
1453    return false;
1454  if (!N->hasNUsesOfValue(1, 0))
1455    return false;
1456
1457  SDNode *Copy = *N->use_begin();
1458  if (Copy->getOpcode() != ISD::CopyToReg &&
1459      Copy->getOpcode() != ISD::FP_EXTEND)
1460    return false;
1461
1462  bool HasRet = false;
1463  for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
1464       UI != UE; ++UI) {
1465    if (UI->getOpcode() != X86ISD::RET_FLAG)
1466      return false;
1467    HasRet = true;
1468  }
1469
1470  return HasRet;
1471}
1472
1473EVT
1474X86TargetLowering::getTypeForExtArgOrReturn(LLVMContext &Context, EVT VT,
1475                                            ISD::NodeType ExtendKind) const {
1476  MVT ReturnMVT;
1477  // TODO: Is this also valid on 32-bit?
1478  if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
1479    ReturnMVT = MVT::i8;
1480  else
1481    ReturnMVT = MVT::i32;
1482
1483  EVT MinVT = getRegisterType(Context, ReturnMVT);
1484  return VT.bitsLT(MinVT) ? MinVT : VT;
1485}
1486
1487/// LowerCallResult - Lower the result values of a call into the
1488/// appropriate copies out of appropriate physical registers.
1489///
1490SDValue
1491X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1492                                   CallingConv::ID CallConv, bool isVarArg,
1493                                   const SmallVectorImpl<ISD::InputArg> &Ins,
1494                                   DebugLoc dl, SelectionDAG &DAG,
1495                                   SmallVectorImpl<SDValue> &InVals) const {
1496
1497  // Assign locations to each value returned by this call.
1498  SmallVector<CCValAssign, 16> RVLocs;
1499  bool Is64Bit = Subtarget->is64Bit();
1500  CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1501		 getTargetMachine(), RVLocs, *DAG.getContext());
1502  CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
1503
1504  // Copy all of the result registers out of their specified physreg.
1505  for (unsigned i = 0; i != RVLocs.size(); ++i) {
1506    CCValAssign &VA = RVLocs[i];
1507    EVT CopyVT = VA.getValVT();
1508
1509    // If this is x86-64, and we disabled SSE, we can't return FP values
1510    if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
1511        ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasXMM())) {
1512      report_fatal_error("SSE register return with SSE disabled");
1513    }
1514
1515    SDValue Val;
1516
1517    // If this is a call to a function that returns an fp value on the floating
1518    // point stack, we must guarantee the the value is popped from the stack, so
1519    // a CopyFromReg is not good enough - the copy instruction may be eliminated
1520    // if the return value is not used. We use the FpPOP_RETVAL instruction
1521    // instead.
1522    if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1) {
1523      // If we prefer to use the value in xmm registers, copy it out as f80 and
1524      // use a truncate to move it from fp stack reg to xmm reg.
1525      if (isScalarFPTypeInSSEReg(VA.getValVT())) CopyVT = MVT::f80;
1526      SDValue Ops[] = { Chain, InFlag };
1527      Chain = SDValue(DAG.getMachineNode(X86::FpPOP_RETVAL, dl, CopyVT,
1528                                         MVT::Other, MVT::Glue, Ops, 2), 1);
1529      Val = Chain.getValue(0);
1530
1531      // Round the f80 to the right size, which also moves it to the appropriate
1532      // xmm register.
1533      if (CopyVT != VA.getValVT())
1534        Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
1535                          // This truncation won't change the value.
1536                          DAG.getIntPtrConstant(1));
1537    } else {
1538      Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1539                                 CopyVT, InFlag).getValue(1);
1540      Val = Chain.getValue(0);
1541    }
1542    InFlag = Chain.getValue(2);
1543    InVals.push_back(Val);
1544  }
1545
1546  return Chain;
1547}
1548
1549
1550//===----------------------------------------------------------------------===//
1551//                C & StdCall & Fast Calling Convention implementation
1552//===----------------------------------------------------------------------===//
1553//  StdCall calling convention seems to be standard for many Windows' API
1554//  routines and around. It differs from C calling convention just a little:
1555//  callee should clean up the stack, not caller. Symbols should be also
1556//  decorated in some fancy way :) It doesn't support any vector arguments.
1557//  For info on fast calling convention see Fast Calling Convention (tail call)
1558//  implementation LowerX86_32FastCCCallTo.
1559
1560/// CallIsStructReturn - Determines whether a call uses struct return
1561/// semantics.
1562static bool CallIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
1563  if (Outs.empty())
1564    return false;
1565
1566  return Outs[0].Flags.isSRet();
1567}
1568
1569/// ArgsAreStructReturn - Determines whether a function uses struct
1570/// return semantics.
1571static bool
1572ArgsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
1573  if (Ins.empty())
1574    return false;
1575
1576  return Ins[0].Flags.isSRet();
1577}
1578
1579/// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
1580/// by "Src" to address "Dst" with size and alignment information specified by
1581/// the specific parameter attribute. The copy will be passed as a byval
1582/// function parameter.
1583static SDValue
1584CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
1585                          ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
1586                          DebugLoc dl) {
1587  SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
1588
1589  return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
1590                       /*isVolatile*/false, /*AlwaysInline=*/true,
1591                       MachinePointerInfo(), MachinePointerInfo());
1592}
1593
1594/// IsTailCallConvention - Return true if the calling convention is one that
1595/// supports tail call optimization.
1596static bool IsTailCallConvention(CallingConv::ID CC) {
1597  return (CC == CallingConv::Fast || CC == CallingConv::GHC);
1598}
1599
1600bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
1601  if (!CI->isTailCall())
1602    return false;
1603
1604  CallSite CS(CI);
1605  CallingConv::ID CalleeCC = CS.getCallingConv();
1606  if (!IsTailCallConvention(CalleeCC) && CalleeCC != CallingConv::C)
1607    return false;
1608
1609  return true;
1610}
1611
1612/// FuncIsMadeTailCallSafe - Return true if the function is being made into
1613/// a tailcall target by changing its ABI.
1614static bool FuncIsMadeTailCallSafe(CallingConv::ID CC) {
1615  return GuaranteedTailCallOpt && IsTailCallConvention(CC);
1616}
1617
1618SDValue
1619X86TargetLowering::LowerMemArgument(SDValue Chain,
1620                                    CallingConv::ID CallConv,
1621                                    const SmallVectorImpl<ISD::InputArg> &Ins,
1622                                    DebugLoc dl, SelectionDAG &DAG,
1623                                    const CCValAssign &VA,
1624                                    MachineFrameInfo *MFI,
1625                                    unsigned i) const {
1626  // Create the nodes corresponding to a load from this parameter slot.
1627  ISD::ArgFlagsTy Flags = Ins[i].Flags;
1628  bool AlwaysUseMutable = FuncIsMadeTailCallSafe(CallConv);
1629  bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
1630  EVT ValVT;
1631
1632  // If value is passed by pointer we have address passed instead of the value
1633  // itself.
1634  if (VA.getLocInfo() == CCValAssign::Indirect)
1635    ValVT = VA.getLocVT();
1636  else
1637    ValVT = VA.getValVT();
1638
1639  // FIXME: For now, all byval parameter objects are marked mutable. This can be
1640  // changed with more analysis.
1641  // In case of tail call optimization mark all arguments mutable. Since they
1642  // could be overwritten by lowering of arguments in case of a tail call.
1643  if (Flags.isByVal()) {
1644    unsigned Bytes = Flags.getByValSize();
1645    if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
1646    int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
1647    return DAG.getFrameIndex(FI, getPointerTy());
1648  } else {
1649    int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
1650                                    VA.getLocMemOffset(), isImmutable);
1651    SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
1652    return DAG.getLoad(ValVT, dl, Chain, FIN,
1653                       MachinePointerInfo::getFixedStack(FI),
1654                       false, false, 0);
1655  }
1656}
1657
1658SDValue
1659X86TargetLowering::LowerFormalArguments(SDValue Chain,
1660                                        CallingConv::ID CallConv,
1661                                        bool isVarArg,
1662                                      const SmallVectorImpl<ISD::InputArg> &Ins,
1663                                        DebugLoc dl,
1664                                        SelectionDAG &DAG,
1665                                        SmallVectorImpl<SDValue> &InVals)
1666                                          const {
1667  MachineFunction &MF = DAG.getMachineFunction();
1668  X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1669
1670  const Function* Fn = MF.getFunction();
1671  if (Fn->hasExternalLinkage() &&
1672      Subtarget->isTargetCygMing() &&
1673      Fn->getName() == "main")
1674    FuncInfo->setForceFramePointer(true);
1675
1676  MachineFrameInfo *MFI = MF.getFrameInfo();
1677  bool Is64Bit = Subtarget->is64Bit();
1678  bool IsWin64 = Subtarget->isTargetWin64();
1679
1680  assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
1681         "Var args not supported with calling convention fastcc or ghc");
1682
1683  // Assign locations to all of the incoming arguments.
1684  SmallVector<CCValAssign, 16> ArgLocs;
1685  CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1686                 ArgLocs, *DAG.getContext());
1687
1688  // Allocate shadow area for Win64
1689  if (IsWin64) {
1690    CCInfo.AllocateStack(32, 8);
1691  }
1692
1693  CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
1694
1695  unsigned LastVal = ~0U;
1696  SDValue ArgValue;
1697  for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1698    CCValAssign &VA = ArgLocs[i];
1699    // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
1700    // places.
1701    assert(VA.getValNo() != LastVal &&
1702           "Don't support value assigned to multiple locs yet");
1703    LastVal = VA.getValNo();
1704
1705    if (VA.isRegLoc()) {
1706      EVT RegVT = VA.getLocVT();
1707      TargetRegisterClass *RC = NULL;
1708      if (RegVT == MVT::i32)
1709        RC = X86::GR32RegisterClass;
1710      else if (Is64Bit && RegVT == MVT::i64)
1711        RC = X86::GR64RegisterClass;
1712      else if (RegVT == MVT::f32)
1713        RC = X86::FR32RegisterClass;
1714      else if (RegVT == MVT::f64)
1715        RC = X86::FR64RegisterClass;
1716      else if (RegVT.isVector() && RegVT.getSizeInBits() == 256)
1717        RC = X86::VR256RegisterClass;
1718      else if (RegVT.isVector() && RegVT.getSizeInBits() == 128)
1719        RC = X86::VR128RegisterClass;
1720      else if (RegVT == MVT::x86mmx)
1721        RC = X86::VR64RegisterClass;
1722      else
1723        llvm_unreachable("Unknown argument type!");
1724
1725      unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
1726      ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
1727
1728      // If this is an 8 or 16-bit value, it is really passed promoted to 32
1729      // bits.  Insert an assert[sz]ext to capture this, then truncate to the
1730      // right size.
1731      if (VA.getLocInfo() == CCValAssign::SExt)
1732        ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
1733                               DAG.getValueType(VA.getValVT()));
1734      else if (VA.getLocInfo() == CCValAssign::ZExt)
1735        ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
1736                               DAG.getValueType(VA.getValVT()));
1737      else if (VA.getLocInfo() == CCValAssign::BCvt)
1738        ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
1739
1740      if (VA.isExtInLoc()) {
1741        // Handle MMX values passed in XMM regs.
1742        if (RegVT.isVector()) {
1743          ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(),
1744                                 ArgValue);
1745        } else
1746          ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
1747      }
1748    } else {
1749      assert(VA.isMemLoc());
1750      ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
1751    }
1752
1753    // If value is passed via pointer - do a load.
1754    if (VA.getLocInfo() == CCValAssign::Indirect)
1755      ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
1756                             MachinePointerInfo(), false, false, 0);
1757
1758    InVals.push_back(ArgValue);
1759  }
1760
1761  // The x86-64 ABI for returning structs by value requires that we copy
1762  // the sret argument into %rax for the return. Save the argument into
1763  // a virtual register so that we can access it from the return points.
1764  if (Is64Bit && MF.getFunction()->hasStructRetAttr()) {
1765    X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1766    unsigned Reg = FuncInfo->getSRetReturnReg();
1767    if (!Reg) {
1768      Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(MVT::i64));
1769      FuncInfo->setSRetReturnReg(Reg);
1770    }
1771    SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[0]);
1772    Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
1773  }
1774
1775  unsigned StackSize = CCInfo.getNextStackOffset();
1776  // Align stack specially for tail calls.
1777  if (FuncIsMadeTailCallSafe(CallConv))
1778    StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
1779
1780  // If the function takes variable number of arguments, make a frame index for
1781  // the start of the first vararg value... for expansion of llvm.va_start.
1782  if (isVarArg) {
1783    if (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
1784                    CallConv != CallingConv::X86_ThisCall)) {
1785      FuncInfo->setVarArgsFrameIndex(MFI->CreateFixedObject(1, StackSize,true));
1786    }
1787    if (Is64Bit) {
1788      unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
1789
1790      // FIXME: We should really autogenerate these arrays
1791      static const unsigned GPR64ArgRegsWin64[] = {
1792        X86::RCX, X86::RDX, X86::R8,  X86::R9
1793      };
1794      static const unsigned GPR64ArgRegs64Bit[] = {
1795        X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
1796      };
1797      static const unsigned XMMArgRegs64Bit[] = {
1798        X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
1799        X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
1800      };
1801      const unsigned *GPR64ArgRegs;
1802      unsigned NumXMMRegs = 0;
1803
1804      if (IsWin64) {
1805        // The XMM registers which might contain var arg parameters are shadowed
1806        // in their paired GPR.  So we only need to save the GPR to their home
1807        // slots.
1808        TotalNumIntRegs = 4;
1809        GPR64ArgRegs = GPR64ArgRegsWin64;
1810      } else {
1811        TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
1812        GPR64ArgRegs = GPR64ArgRegs64Bit;
1813
1814        NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs64Bit, TotalNumXMMRegs);
1815      }
1816      unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
1817                                                       TotalNumIntRegs);
1818
1819      bool NoImplicitFloatOps = Fn->hasFnAttr(Attribute::NoImplicitFloat);
1820      assert(!(NumXMMRegs && !Subtarget->hasXMM()) &&
1821             "SSE register cannot be used when SSE is disabled!");
1822      assert(!(NumXMMRegs && UseSoftFloat && NoImplicitFloatOps) &&
1823             "SSE register cannot be used when SSE is disabled!");
1824      if (UseSoftFloat || NoImplicitFloatOps || !Subtarget->hasXMM())
1825        // Kernel mode asks for SSE to be disabled, so don't push them
1826        // on the stack.
1827        TotalNumXMMRegs = 0;
1828
1829      if (IsWin64) {
1830        const TargetFrameLowering &TFI = *getTargetMachine().getFrameLowering();
1831        // Get to the caller-allocated home save location.  Add 8 to account
1832        // for the return address.
1833        int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
1834        FuncInfo->setRegSaveFrameIndex(
1835          MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
1836        // Fixup to set vararg frame on shadow area (4 x i64).
1837        if (NumIntRegs < 4)
1838          FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
1839      } else {
1840        // For X86-64, if there are vararg parameters that are passed via
1841        // registers, then we must store them to their spots on the stack so they
1842        // may be loaded by deferencing the result of va_next.
1843        FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
1844        FuncInfo->setVarArgsFPOffset(TotalNumIntRegs * 8 + NumXMMRegs * 16);
1845        FuncInfo->setRegSaveFrameIndex(
1846          MFI->CreateStackObject(TotalNumIntRegs * 8 + TotalNumXMMRegs * 16, 16,
1847                               false));
1848      }
1849
1850      // Store the integer parameter registers.
1851      SmallVector<SDValue, 8> MemOps;
1852      SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
1853                                        getPointerTy());
1854      unsigned Offset = FuncInfo->getVarArgsGPOffset();
1855      for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
1856        SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
1857                                  DAG.getIntPtrConstant(Offset));
1858        unsigned VReg = MF.addLiveIn(GPR64ArgRegs[NumIntRegs],
1859                                     X86::GR64RegisterClass);
1860        SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
1861        SDValue Store =
1862          DAG.getStore(Val.getValue(1), dl, Val, FIN,
1863                       MachinePointerInfo::getFixedStack(
1864                         FuncInfo->getRegSaveFrameIndex(), Offset),
1865                       false, false, 0);
1866        MemOps.push_back(Store);
1867        Offset += 8;
1868      }
1869
1870      if (TotalNumXMMRegs != 0 && NumXMMRegs != TotalNumXMMRegs) {
1871        // Now store the XMM (fp + vector) parameter registers.
1872        SmallVector<SDValue, 11> SaveXMMOps;
1873        SaveXMMOps.push_back(Chain);
1874
1875        unsigned AL = MF.addLiveIn(X86::AL, X86::GR8RegisterClass);
1876        SDValue ALVal = DAG.getCopyFromReg(DAG.getEntryNode(), dl, AL, MVT::i8);
1877        SaveXMMOps.push_back(ALVal);
1878
1879        SaveXMMOps.push_back(DAG.getIntPtrConstant(
1880                               FuncInfo->getRegSaveFrameIndex()));
1881        SaveXMMOps.push_back(DAG.getIntPtrConstant(
1882                               FuncInfo->getVarArgsFPOffset()));
1883
1884        for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
1885          unsigned VReg = MF.addLiveIn(XMMArgRegs64Bit[NumXMMRegs],
1886                                       X86::VR128RegisterClass);
1887          SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::v4f32);
1888          SaveXMMOps.push_back(Val);
1889        }
1890        MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
1891                                     MVT::Other,
1892                                     &SaveXMMOps[0], SaveXMMOps.size()));
1893      }
1894
1895      if (!MemOps.empty())
1896        Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1897                            &MemOps[0], MemOps.size());
1898    }
1899  }
1900
1901  // Some CCs need callee pop.
1902  if (X86::isCalleePop(CallConv, Is64Bit, isVarArg, GuaranteedTailCallOpt)) {
1903    FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
1904  } else {
1905    FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
1906    // If this is an sret function, the return should pop the hidden pointer.
1907    if (!Is64Bit && !IsTailCallConvention(CallConv) && ArgsAreStructReturn(Ins))
1908      FuncInfo->setBytesToPopOnReturn(4);
1909  }
1910
1911  if (!Is64Bit) {
1912    // RegSaveFrameIndex is X86-64 only.
1913    FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
1914    if (CallConv == CallingConv::X86_FastCall ||
1915        CallConv == CallingConv::X86_ThisCall)
1916      // fastcc functions can't have varargs.
1917      FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
1918  }
1919
1920  return Chain;
1921}
1922
1923SDValue
1924X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
1925                                    SDValue StackPtr, SDValue Arg,
1926                                    DebugLoc dl, SelectionDAG &DAG,
1927                                    const CCValAssign &VA,
1928                                    ISD::ArgFlagsTy Flags) const {
1929  unsigned LocMemOffset = VA.getLocMemOffset();
1930  SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
1931  PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
1932  if (Flags.isByVal())
1933    return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
1934
1935  return DAG.getStore(Chain, dl, Arg, PtrOff,
1936                      MachinePointerInfo::getStack(LocMemOffset),
1937                      false, false, 0);
1938}
1939
1940/// EmitTailCallLoadRetAddr - Emit a load of return address if tail call
1941/// optimization is performed and it is required.
1942SDValue
1943X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
1944                                           SDValue &OutRetAddr, SDValue Chain,
1945                                           bool IsTailCall, bool Is64Bit,
1946                                           int FPDiff, DebugLoc dl) const {
1947  // Adjust the Return address stack slot.
1948  EVT VT = getPointerTy();
1949  OutRetAddr = getReturnAddressFrameIndex(DAG);
1950
1951  // Load the "old" Return address.
1952  OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
1953                           false, false, 0);
1954  return SDValue(OutRetAddr.getNode(), 1);
1955}
1956
1957/// EmitTailCallStoreRetAddr - Emit a store of the return address if tail call
1958/// optimization is performed and it is required (FPDiff!=0).
1959static SDValue
1960EmitTailCallStoreRetAddr(SelectionDAG & DAG, MachineFunction &MF,
1961                         SDValue Chain, SDValue RetAddrFrIdx,
1962                         bool Is64Bit, int FPDiff, DebugLoc dl) {
1963  // Store the return address to the appropriate stack slot.
1964  if (!FPDiff) return Chain;
1965  // Calculate the new stack slot for the return address.
1966  int SlotSize = Is64Bit ? 8 : 4;
1967  int NewReturnAddrFI =
1968    MF.getFrameInfo()->CreateFixedObject(SlotSize, FPDiff-SlotSize, false);
1969  EVT VT = Is64Bit ? MVT::i64 : MVT::i32;
1970  SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, VT);
1971  Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
1972                       MachinePointerInfo::getFixedStack(NewReturnAddrFI),
1973                       false, false, 0);
1974  return Chain;
1975}
1976
1977SDValue
1978X86TargetLowering::LowerCall(SDValue Chain, SDValue Callee,
1979                             CallingConv::ID CallConv, bool isVarArg,
1980                             bool &isTailCall,
1981                             const SmallVectorImpl<ISD::OutputArg> &Outs,
1982                             const SmallVectorImpl<SDValue> &OutVals,
1983                             const SmallVectorImpl<ISD::InputArg> &Ins,
1984                             DebugLoc dl, SelectionDAG &DAG,
1985                             SmallVectorImpl<SDValue> &InVals) const {
1986  MachineFunction &MF = DAG.getMachineFunction();
1987  bool Is64Bit        = Subtarget->is64Bit();
1988  bool IsWin64        = Subtarget->isTargetWin64();
1989  bool IsStructRet    = CallIsStructReturn(Outs);
1990  bool IsSibcall      = false;
1991
1992  if (isTailCall) {
1993    // Check if it's really possible to do a tail call.
1994    isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
1995                    isVarArg, IsStructRet, MF.getFunction()->hasStructRetAttr(),
1996                                                   Outs, OutVals, Ins, DAG);
1997
1998    // Sibcalls are automatically detected tailcalls which do not require
1999    // ABI changes.
2000    if (!GuaranteedTailCallOpt && isTailCall)
2001      IsSibcall = true;
2002
2003    if (isTailCall)
2004      ++NumTailCalls;
2005  }
2006
2007  assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2008         "Var args not supported with calling convention fastcc or ghc");
2009
2010  // Analyze operands of the call, assigning locations to each operand.
2011  SmallVector<CCValAssign, 16> ArgLocs;
2012  CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
2013                 ArgLocs, *DAG.getContext());
2014
2015  // Allocate shadow area for Win64
2016  if (IsWin64) {
2017    CCInfo.AllocateStack(32, 8);
2018  }
2019
2020  CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2021
2022  // Get a count of how many bytes are to be pushed on the stack.
2023  unsigned NumBytes = CCInfo.getNextStackOffset();
2024  if (IsSibcall)
2025    // This is a sibcall. The memory operands are available in caller's
2026    // own caller's stack.
2027    NumBytes = 0;
2028  else if (GuaranteedTailCallOpt && IsTailCallConvention(CallConv))
2029    NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
2030
2031  int FPDiff = 0;
2032  if (isTailCall && !IsSibcall) {
2033    // Lower arguments at fp - stackoffset + fpdiff.
2034    unsigned NumBytesCallerPushed =
2035      MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn();
2036    FPDiff = NumBytesCallerPushed - NumBytes;
2037
2038    // Set the delta of movement of the returnaddr stackslot.
2039    // But only set if delta is greater than previous delta.
2040    if (FPDiff < (MF.getInfo<X86MachineFunctionInfo>()->getTCReturnAddrDelta()))
2041      MF.getInfo<X86MachineFunctionInfo>()->setTCReturnAddrDelta(FPDiff);
2042  }
2043
2044  if (!IsSibcall)
2045    Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true));
2046
2047  SDValue RetAddrFrIdx;
2048  // Load return address for tail calls.
2049  if (isTailCall && FPDiff)
2050    Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
2051                                    Is64Bit, FPDiff, dl);
2052
2053  SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2054  SmallVector<SDValue, 8> MemOpChains;
2055  SDValue StackPtr;
2056
2057  // Walk the register/memloc assignments, inserting copies/loads.  In the case
2058  // of tail call optimization arguments are handle later.
2059  for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2060    CCValAssign &VA = ArgLocs[i];
2061    EVT RegVT = VA.getLocVT();
2062    SDValue Arg = OutVals[i];
2063    ISD::ArgFlagsTy Flags = Outs[i].Flags;
2064    bool isByVal = Flags.isByVal();
2065
2066    // Promote the value if needed.
2067    switch (VA.getLocInfo()) {
2068    default: llvm_unreachable("Unknown loc info!");
2069    case CCValAssign::Full: break;
2070    case CCValAssign::SExt:
2071      Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
2072      break;
2073    case CCValAssign::ZExt:
2074      Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
2075      break;
2076    case CCValAssign::AExt:
2077      if (RegVT.isVector() && RegVT.getSizeInBits() == 128) {
2078        // Special case: passing MMX values in XMM registers.
2079        Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
2080        Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
2081        Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
2082      } else
2083        Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
2084      break;
2085    case CCValAssign::BCvt:
2086      Arg = DAG.getNode(ISD::BITCAST, dl, RegVT, Arg);
2087      break;
2088    case CCValAssign::Indirect: {
2089      // Store the argument.
2090      SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
2091      int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
2092      Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
2093                           MachinePointerInfo::getFixedStack(FI),
2094                           false, false, 0);
2095      Arg = SpillSlot;
2096      break;
2097    }
2098    }
2099
2100    if (VA.isRegLoc()) {
2101      RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2102      if (isVarArg && IsWin64) {
2103        // Win64 ABI requires argument XMM reg to be copied to the corresponding
2104        // shadow reg if callee is a varargs function.
2105        unsigned ShadowReg = 0;
2106        switch (VA.getLocReg()) {
2107        case X86::XMM0: ShadowReg = X86::RCX; break;
2108        case X86::XMM1: ShadowReg = X86::RDX; break;
2109        case X86::XMM2: ShadowReg = X86::R8; break;
2110        case X86::XMM3: ShadowReg = X86::R9; break;
2111        }
2112        if (ShadowReg)
2113          RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
2114      }
2115    } else if (!IsSibcall && (!isTailCall || isByVal)) {
2116      assert(VA.isMemLoc());
2117      if (StackPtr.getNode() == 0)
2118        StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr, getPointerTy());
2119      MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
2120                                             dl, DAG, VA, Flags));
2121    }
2122  }
2123
2124  if (!MemOpChains.empty())
2125    Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2126                        &MemOpChains[0], MemOpChains.size());
2127
2128  // Build a sequence of copy-to-reg nodes chained together with token chain
2129  // and flag operands which copy the outgoing args into registers.
2130  SDValue InFlag;
2131  // Tail call byval lowering might overwrite argument registers so in case of
2132  // tail call optimization the copies to registers are lowered later.
2133  if (!isTailCall)
2134    for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2135      Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2136                               RegsToPass[i].second, InFlag);
2137      InFlag = Chain.getValue(1);
2138    }
2139
2140  if (Subtarget->isPICStyleGOT()) {
2141    // ELF / PIC requires GOT in the EBX register before function calls via PLT
2142    // GOT pointer.
2143    if (!isTailCall) {
2144      Chain = DAG.getCopyToReg(Chain, dl, X86::EBX,
2145                               DAG.getNode(X86ISD::GlobalBaseReg,
2146                                           DebugLoc(), getPointerTy()),
2147                               InFlag);
2148      InFlag = Chain.getValue(1);
2149    } else {
2150      // If we are tail calling and generating PIC/GOT style code load the
2151      // address of the callee into ECX. The value in ecx is used as target of
2152      // the tail jump. This is done to circumvent the ebx/callee-saved problem
2153      // for tail calls on PIC/GOT architectures. Normally we would just put the
2154      // address of GOT into ebx and then call target@PLT. But for tail calls
2155      // ebx would be restored (since ebx is callee saved) before jumping to the
2156      // target@PLT.
2157
2158      // Note: The actual moving to ECX is done further down.
2159      GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2160      if (G && !G->getGlobal()->hasHiddenVisibility() &&
2161          !G->getGlobal()->hasProtectedVisibility())
2162        Callee = LowerGlobalAddress(Callee, DAG);
2163      else if (isa<ExternalSymbolSDNode>(Callee))
2164        Callee = LowerExternalSymbol(Callee, DAG);
2165    }
2166  }
2167
2168  if (Is64Bit && isVarArg && !IsWin64) {
2169    // From AMD64 ABI document:
2170    // For calls that may call functions that use varargs or stdargs
2171    // (prototype-less calls or calls to functions containing ellipsis (...) in
2172    // the declaration) %al is used as hidden argument to specify the number
2173    // of SSE registers used. The contents of %al do not need to match exactly
2174    // the number of registers, but must be an ubound on the number of SSE
2175    // registers used and is in the range 0 - 8 inclusive.
2176
2177    // Count the number of XMM registers allocated.
2178    static const unsigned XMMArgRegs[] = {
2179      X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2180      X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2181    };
2182    unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
2183    assert((Subtarget->hasXMM() || !NumXMMRegs)
2184           && "SSE registers cannot be used when SSE is disabled");
2185
2186    Chain = DAG.getCopyToReg(Chain, dl, X86::AL,
2187                             DAG.getConstant(NumXMMRegs, MVT::i8), InFlag);
2188    InFlag = Chain.getValue(1);
2189  }
2190
2191
2192  // For tail calls lower the arguments to the 'real' stack slot.
2193  if (isTailCall) {
2194    // Force all the incoming stack arguments to be loaded from the stack
2195    // before any new outgoing arguments are stored to the stack, because the
2196    // outgoing stack slots may alias the incoming argument stack slots, and
2197    // the alias isn't otherwise explicit. This is slightly more conservative
2198    // than necessary, because it means that each store effectively depends
2199    // on every argument instead of just those arguments it would clobber.
2200    SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
2201
2202    SmallVector<SDValue, 8> MemOpChains2;
2203    SDValue FIN;
2204    int FI = 0;
2205    // Do not flag preceding copytoreg stuff together with the following stuff.
2206    InFlag = SDValue();
2207    if (GuaranteedTailCallOpt) {
2208      for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2209        CCValAssign &VA = ArgLocs[i];
2210        if (VA.isRegLoc())
2211          continue;
2212        assert(VA.isMemLoc());
2213        SDValue Arg = OutVals[i];
2214        ISD::ArgFlagsTy Flags = Outs[i].Flags;
2215        // Create frame index.
2216        int32_t Offset = VA.getLocMemOffset()+FPDiff;
2217        uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
2218        FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
2219        FIN = DAG.getFrameIndex(FI, getPointerTy());
2220
2221        if (Flags.isByVal()) {
2222          // Copy relative to framepointer.
2223          SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
2224          if (StackPtr.getNode() == 0)
2225            StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr,
2226                                          getPointerTy());
2227          Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
2228
2229          MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
2230                                                           ArgChain,
2231                                                           Flags, DAG, dl));
2232        } else {
2233          // Store relative to framepointer.
2234          MemOpChains2.push_back(
2235            DAG.getStore(ArgChain, dl, Arg, FIN,
2236                         MachinePointerInfo::getFixedStack(FI),
2237                         false, false, 0));
2238        }
2239      }
2240    }
2241
2242    if (!MemOpChains2.empty())
2243      Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2244                          &MemOpChains2[0], MemOpChains2.size());
2245
2246    // Copy arguments to their registers.
2247    for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2248      Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2249                               RegsToPass[i].second, InFlag);
2250      InFlag = Chain.getValue(1);
2251    }
2252    InFlag =SDValue();
2253
2254    // Store the return address to the appropriate stack slot.
2255    Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx, Is64Bit,
2256                                     FPDiff, dl);
2257  }
2258
2259  if (getTargetMachine().getCodeModel() == CodeModel::Large) {
2260    assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
2261    // In the 64-bit large code model, we have to make all calls
2262    // through a register, since the call instruction's 32-bit
2263    // pc-relative offset may not be large enough to hold the whole
2264    // address.
2265  } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2266    // If the callee is a GlobalAddress node (quite common, every direct call
2267    // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
2268    // it.
2269
2270    // We should use extra load for direct calls to dllimported functions in
2271    // non-JIT mode.
2272    const GlobalValue *GV = G->getGlobal();
2273    if (!GV->hasDLLImportLinkage()) {
2274      unsigned char OpFlags = 0;
2275      bool ExtraLoad = false;
2276      unsigned WrapperKind = ISD::DELETED_NODE;
2277
2278      // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
2279      // external symbols most go through the PLT in PIC mode.  If the symbol
2280      // has hidden or protected visibility, or if it is static or local, then
2281      // we don't need to use the PLT - we can directly call it.
2282      if (Subtarget->isTargetELF() &&
2283          getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
2284          GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
2285        OpFlags = X86II::MO_PLT;
2286      } else if (Subtarget->isPICStyleStubAny() &&
2287                 (GV->isDeclaration() || GV->isWeakForLinker()) &&
2288                 (!Subtarget->getTargetTriple().isMacOSX() ||
2289                  Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2290        // PC-relative references to external symbols should go through $stub,
2291        // unless we're building with the leopard linker or later, which
2292        // automatically synthesizes these stubs.
2293        OpFlags = X86II::MO_DARWIN_STUB;
2294      } else if (Subtarget->isPICStyleRIPRel() &&
2295                 isa<Function>(GV) &&
2296                 cast<Function>(GV)->hasFnAttr(Attribute::NonLazyBind)) {
2297        // If the function is marked as non-lazy, generate an indirect call
2298        // which loads from the GOT directly. This avoids runtime overhead
2299        // at the cost of eager binding (and one extra byte of encoding).
2300        OpFlags = X86II::MO_GOTPCREL;
2301        WrapperKind = X86ISD::WrapperRIP;
2302        ExtraLoad = true;
2303      }
2304
2305      Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
2306                                          G->getOffset(), OpFlags);
2307
2308      // Add a wrapper if needed.
2309      if (WrapperKind != ISD::DELETED_NODE)
2310        Callee = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Callee);
2311      // Add extra indirection if needed.
2312      if (ExtraLoad)
2313        Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Callee,
2314                             MachinePointerInfo::getGOT(),
2315                             false, false, 0);
2316    }
2317  } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2318    unsigned char OpFlags = 0;
2319
2320    // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
2321    // external symbols should go through the PLT.
2322    if (Subtarget->isTargetELF() &&
2323        getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2324      OpFlags = X86II::MO_PLT;
2325    } else if (Subtarget->isPICStyleStubAny() &&
2326               (!Subtarget->getTargetTriple().isMacOSX() ||
2327                Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2328      // PC-relative references to external symbols should go through $stub,
2329      // unless we're building with the leopard linker or later, which
2330      // automatically synthesizes these stubs.
2331      OpFlags = X86II::MO_DARWIN_STUB;
2332    }
2333
2334    Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
2335                                         OpFlags);
2336  }
2337
2338  // Returns a chain & a flag for retval copy to use.
2339  SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2340  SmallVector<SDValue, 8> Ops;
2341
2342  if (!IsSibcall && isTailCall) {
2343    Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
2344                           DAG.getIntPtrConstant(0, true), InFlag);
2345    InFlag = Chain.getValue(1);
2346  }
2347
2348  Ops.push_back(Chain);
2349  Ops.push_back(Callee);
2350
2351  if (isTailCall)
2352    Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
2353
2354  // Add argument registers to the end of the list so that they are known live
2355  // into the call.
2356  for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2357    Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2358                                  RegsToPass[i].second.getValueType()));
2359
2360  // Add an implicit use GOT pointer in EBX.
2361  if (!isTailCall && Subtarget->isPICStyleGOT())
2362    Ops.push_back(DAG.getRegister(X86::EBX, getPointerTy()));
2363
2364  // Add an implicit use of AL for non-Windows x86 64-bit vararg functions.
2365  if (Is64Bit && isVarArg && !IsWin64)
2366    Ops.push_back(DAG.getRegister(X86::AL, MVT::i8));
2367
2368  if (InFlag.getNode())
2369    Ops.push_back(InFlag);
2370
2371  if (isTailCall) {
2372    // We used to do:
2373    //// If this is the first return lowered for this function, add the regs
2374    //// to the liveout set for the function.
2375    // This isn't right, although it's probably harmless on x86; liveouts
2376    // should be computed from returns not tail calls.  Consider a void
2377    // function making a tail call to a function returning int.
2378    return DAG.getNode(X86ISD::TC_RETURN, dl,
2379                       NodeTys, &Ops[0], Ops.size());
2380  }
2381
2382  Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, &Ops[0], Ops.size());
2383  InFlag = Chain.getValue(1);
2384
2385  // Create the CALLSEQ_END node.
2386  unsigned NumBytesForCalleeToPush;
2387  if (X86::isCalleePop(CallConv, Is64Bit, isVarArg, GuaranteedTailCallOpt))
2388    NumBytesForCalleeToPush = NumBytes;    // Callee pops everything
2389  else if (!Is64Bit && !IsTailCallConvention(CallConv) && IsStructRet)
2390    // If this is a call to a struct-return function, the callee
2391    // pops the hidden struct pointer, so we have to push it back.
2392    // This is common for Darwin/X86, Linux & Mingw32 targets.
2393    NumBytesForCalleeToPush = 4;
2394  else
2395    NumBytesForCalleeToPush = 0;  // Callee pops nothing.
2396
2397  // Returns a flag for retval copy to use.
2398  if (!IsSibcall) {
2399    Chain = DAG.getCALLSEQ_END(Chain,
2400                               DAG.getIntPtrConstant(NumBytes, true),
2401                               DAG.getIntPtrConstant(NumBytesForCalleeToPush,
2402                                                     true),
2403                               InFlag);
2404    InFlag = Chain.getValue(1);
2405  }
2406
2407  // Handle result values, copying them out of physregs into vregs that we
2408  // return.
2409  return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
2410                         Ins, dl, DAG, InVals);
2411}
2412
2413
2414//===----------------------------------------------------------------------===//
2415//                Fast Calling Convention (tail call) implementation
2416//===----------------------------------------------------------------------===//
2417
2418//  Like std call, callee cleans arguments, convention except that ECX is
2419//  reserved for storing the tail called function address. Only 2 registers are
2420//  free for argument passing (inreg). Tail call optimization is performed
2421//  provided:
2422//                * tailcallopt is enabled
2423//                * caller/callee are fastcc
2424//  On X86_64 architecture with GOT-style position independent code only local
2425//  (within module) calls are supported at the moment.
2426//  To keep the stack aligned according to platform abi the function
2427//  GetAlignedArgumentStackSize ensures that argument delta is always multiples
2428//  of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
2429//  If a tail called function callee has more arguments than the caller the
2430//  caller needs to make sure that there is room to move the RETADDR to. This is
2431//  achieved by reserving an area the size of the argument delta right after the
2432//  original REtADDR, but before the saved framepointer or the spilled registers
2433//  e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
2434//  stack layout:
2435//    arg1
2436//    arg2
2437//    RETADDR
2438//    [ new RETADDR
2439//      move area ]
2440//    (possible EBP)
2441//    ESI
2442//    EDI
2443//    local1 ..
2444
2445/// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
2446/// for a 16 byte align requirement.
2447unsigned
2448X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
2449                                               SelectionDAG& DAG) const {
2450  MachineFunction &MF = DAG.getMachineFunction();
2451  const TargetMachine &TM = MF.getTarget();
2452  const TargetFrameLowering &TFI = *TM.getFrameLowering();
2453  unsigned StackAlignment = TFI.getStackAlignment();
2454  uint64_t AlignMask = StackAlignment - 1;
2455  int64_t Offset = StackSize;
2456  uint64_t SlotSize = TD->getPointerSize();
2457  if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
2458    // Number smaller than 12 so just add the difference.
2459    Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
2460  } else {
2461    // Mask out lower bits, add stackalignment once plus the 12 bytes.
2462    Offset = ((~AlignMask) & Offset) + StackAlignment +
2463      (StackAlignment-SlotSize);
2464  }
2465  return Offset;
2466}
2467
2468/// MatchingStackOffset - Return true if the given stack call argument is
2469/// already available in the same position (relatively) of the caller's
2470/// incoming argument stack.
2471static
2472bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
2473                         MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
2474                         const X86InstrInfo *TII) {
2475  unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
2476  int FI = INT_MAX;
2477  if (Arg.getOpcode() == ISD::CopyFromReg) {
2478    unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
2479    if (!TargetRegisterInfo::isVirtualRegister(VR))
2480      return false;
2481    MachineInstr *Def = MRI->getVRegDef(VR);
2482    if (!Def)
2483      return false;
2484    if (!Flags.isByVal()) {
2485      if (!TII->isLoadFromStackSlot(Def, FI))
2486        return false;
2487    } else {
2488      unsigned Opcode = Def->getOpcode();
2489      if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r) &&
2490          Def->getOperand(1).isFI()) {
2491        FI = Def->getOperand(1).getIndex();
2492        Bytes = Flags.getByValSize();
2493      } else
2494        return false;
2495    }
2496  } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
2497    if (Flags.isByVal())
2498      // ByVal argument is passed in as a pointer but it's now being
2499      // dereferenced. e.g.
2500      // define @foo(%struct.X* %A) {
2501      //   tail call @bar(%struct.X* byval %A)
2502      // }
2503      return false;
2504    SDValue Ptr = Ld->getBasePtr();
2505    FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
2506    if (!FINode)
2507      return false;
2508    FI = FINode->getIndex();
2509  } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
2510    FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
2511    FI = FINode->getIndex();
2512    Bytes = Flags.getByValSize();
2513  } else
2514    return false;
2515
2516  assert(FI != INT_MAX);
2517  if (!MFI->isFixedObjectIndex(FI))
2518    return false;
2519  return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
2520}
2521
2522/// IsEligibleForTailCallOptimization - Check whether the call is eligible
2523/// for tail call optimization. Targets which want to do tail call
2524/// optimization should implement this function.
2525bool
2526X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
2527                                                     CallingConv::ID CalleeCC,
2528                                                     bool isVarArg,
2529                                                     bool isCalleeStructRet,
2530                                                     bool isCallerStructRet,
2531                                    const SmallVectorImpl<ISD::OutputArg> &Outs,
2532                                    const SmallVectorImpl<SDValue> &OutVals,
2533                                    const SmallVectorImpl<ISD::InputArg> &Ins,
2534                                                     SelectionDAG& DAG) const {
2535  if (!IsTailCallConvention(CalleeCC) &&
2536      CalleeCC != CallingConv::C)
2537    return false;
2538
2539  // If -tailcallopt is specified, make fastcc functions tail-callable.
2540  const MachineFunction &MF = DAG.getMachineFunction();
2541  const Function *CallerF = DAG.getMachineFunction().getFunction();
2542  CallingConv::ID CallerCC = CallerF->getCallingConv();
2543  bool CCMatch = CallerCC == CalleeCC;
2544
2545  if (GuaranteedTailCallOpt) {
2546    if (IsTailCallConvention(CalleeCC) && CCMatch)
2547      return true;
2548    return false;
2549  }
2550
2551  // Look for obvious safe cases to perform tail call optimization that do not
2552  // require ABI changes. This is what gcc calls sibcall.
2553
2554  // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
2555  // emit a special epilogue.
2556  if (RegInfo->needsStackRealignment(MF))
2557    return false;
2558
2559  // Also avoid sibcall optimization if either caller or callee uses struct
2560  // return semantics.
2561  if (isCalleeStructRet || isCallerStructRet)
2562    return false;
2563
2564  // An stdcall caller is expected to clean up its arguments; the callee
2565  // isn't going to do that.
2566  if (!CCMatch && CallerCC==CallingConv::X86_StdCall)
2567    return false;
2568
2569  // Do not sibcall optimize vararg calls unless all arguments are passed via
2570  // registers.
2571  if (isVarArg && !Outs.empty()) {
2572
2573    // Optimizing for varargs on Win64 is unlikely to be safe without
2574    // additional testing.
2575    if (Subtarget->isTargetWin64())
2576      return false;
2577
2578    SmallVector<CCValAssign, 16> ArgLocs;
2579    CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
2580		   getTargetMachine(), ArgLocs, *DAG.getContext());
2581
2582    CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2583    for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
2584      if (!ArgLocs[i].isRegLoc())
2585        return false;
2586  }
2587
2588  // If the call result is in ST0 / ST1, it needs to be popped off the x87 stack.
2589  // Therefore if it's not used by the call it is not safe to optimize this into
2590  // a sibcall.
2591  bool Unused = false;
2592  for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
2593    if (!Ins[i].Used) {
2594      Unused = true;
2595      break;
2596    }
2597  }
2598  if (Unused) {
2599    SmallVector<CCValAssign, 16> RVLocs;
2600    CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(),
2601		   getTargetMachine(), RVLocs, *DAG.getContext());
2602    CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2603    for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2604      CCValAssign &VA = RVLocs[i];
2605      if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1)
2606        return false;
2607    }
2608  }
2609
2610  // If the calling conventions do not match, then we'd better make sure the
2611  // results are returned in the same way as what the caller expects.
2612  if (!CCMatch) {
2613    SmallVector<CCValAssign, 16> RVLocs1;
2614    CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(),
2615		    getTargetMachine(), RVLocs1, *DAG.getContext());
2616    CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
2617
2618    SmallVector<CCValAssign, 16> RVLocs2;
2619    CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(),
2620		    getTargetMachine(), RVLocs2, *DAG.getContext());
2621    CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
2622
2623    if (RVLocs1.size() != RVLocs2.size())
2624      return false;
2625    for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
2626      if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
2627        return false;
2628      if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
2629        return false;
2630      if (RVLocs1[i].isRegLoc()) {
2631        if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
2632          return false;
2633      } else {
2634        if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
2635          return false;
2636      }
2637    }
2638  }
2639
2640  // If the callee takes no arguments then go on to check the results of the
2641  // call.
2642  if (!Outs.empty()) {
2643    // Check if stack adjustment is needed. For now, do not do this if any
2644    // argument is passed on the stack.
2645    SmallVector<CCValAssign, 16> ArgLocs;
2646    CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
2647		   getTargetMachine(), ArgLocs, *DAG.getContext());
2648
2649    // Allocate shadow area for Win64
2650    if (Subtarget->isTargetWin64()) {
2651      CCInfo.AllocateStack(32, 8);
2652    }
2653
2654    CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2655    if (CCInfo.getNextStackOffset()) {
2656      MachineFunction &MF = DAG.getMachineFunction();
2657      if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
2658        return false;
2659
2660      // Check if the arguments are already laid out in the right way as
2661      // the caller's fixed stack objects.
2662      MachineFrameInfo *MFI = MF.getFrameInfo();
2663      const MachineRegisterInfo *MRI = &MF.getRegInfo();
2664      const X86InstrInfo *TII =
2665        ((X86TargetMachine&)getTargetMachine()).getInstrInfo();
2666      for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2667        CCValAssign &VA = ArgLocs[i];
2668        SDValue Arg = OutVals[i];
2669        ISD::ArgFlagsTy Flags = Outs[i].Flags;
2670        if (VA.getLocInfo() == CCValAssign::Indirect)
2671          return false;
2672        if (!VA.isRegLoc()) {
2673          if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2674                                   MFI, MRI, TII))
2675            return false;
2676        }
2677      }
2678    }
2679
2680    // If the tailcall address may be in a register, then make sure it's
2681    // possible to register allocate for it. In 32-bit, the call address can
2682    // only target EAX, EDX, or ECX since the tail call must be scheduled after
2683    // callee-saved registers are restored. These happen to be the same
2684    // registers used to pass 'inreg' arguments so watch out for those.
2685    if (!Subtarget->is64Bit() &&
2686        !isa<GlobalAddressSDNode>(Callee) &&
2687        !isa<ExternalSymbolSDNode>(Callee)) {
2688      unsigned NumInRegs = 0;
2689      for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2690        CCValAssign &VA = ArgLocs[i];
2691        if (!VA.isRegLoc())
2692          continue;
2693        unsigned Reg = VA.getLocReg();
2694        switch (Reg) {
2695        default: break;
2696        case X86::EAX: case X86::EDX: case X86::ECX:
2697          if (++NumInRegs == 3)
2698            return false;
2699          break;
2700        }
2701      }
2702    }
2703  }
2704
2705  return true;
2706}
2707
2708FastISel *
2709X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo) const {
2710  return X86::createFastISel(funcInfo);
2711}
2712
2713
2714//===----------------------------------------------------------------------===//
2715//                           Other Lowering Hooks
2716//===----------------------------------------------------------------------===//
2717
2718static bool MayFoldLoad(SDValue Op) {
2719  return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
2720}
2721
2722static bool MayFoldIntoStore(SDValue Op) {
2723  return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
2724}
2725
2726static bool isTargetShuffle(unsigned Opcode) {
2727  switch(Opcode) {
2728  default: return false;
2729  case X86ISD::PSHUFD:
2730  case X86ISD::PSHUFHW:
2731  case X86ISD::PSHUFLW:
2732  case X86ISD::SHUFPD:
2733  case X86ISD::PALIGN:
2734  case X86ISD::SHUFPS:
2735  case X86ISD::MOVLHPS:
2736  case X86ISD::MOVLHPD:
2737  case X86ISD::MOVHLPS:
2738  case X86ISD::MOVLPS:
2739  case X86ISD::MOVLPD:
2740  case X86ISD::MOVSHDUP:
2741  case X86ISD::MOVSLDUP:
2742  case X86ISD::MOVDDUP:
2743  case X86ISD::MOVSS:
2744  case X86ISD::MOVSD:
2745  case X86ISD::UNPCKLPS:
2746  case X86ISD::UNPCKLPD:
2747  case X86ISD::VUNPCKLPS:
2748  case X86ISD::VUNPCKLPD:
2749  case X86ISD::VUNPCKLPSY:
2750  case X86ISD::VUNPCKLPDY:
2751  case X86ISD::PUNPCKLWD:
2752  case X86ISD::PUNPCKLBW:
2753  case X86ISD::PUNPCKLDQ:
2754  case X86ISD::PUNPCKLQDQ:
2755  case X86ISD::UNPCKHPS:
2756  case X86ISD::UNPCKHPD:
2757  case X86ISD::PUNPCKHWD:
2758  case X86ISD::PUNPCKHBW:
2759  case X86ISD::PUNPCKHDQ:
2760  case X86ISD::PUNPCKHQDQ:
2761    return true;
2762  }
2763  return false;
2764}
2765
2766static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2767                                               SDValue V1, SelectionDAG &DAG) {
2768  switch(Opc) {
2769  default: llvm_unreachable("Unknown x86 shuffle node");
2770  case X86ISD::MOVSHDUP:
2771  case X86ISD::MOVSLDUP:
2772  case X86ISD::MOVDDUP:
2773    return DAG.getNode(Opc, dl, VT, V1);
2774  }
2775
2776  return SDValue();
2777}
2778
2779static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2780                          SDValue V1, unsigned TargetMask, SelectionDAG &DAG) {
2781  switch(Opc) {
2782  default: llvm_unreachable("Unknown x86 shuffle node");
2783  case X86ISD::PSHUFD:
2784  case X86ISD::PSHUFHW:
2785  case X86ISD::PSHUFLW:
2786    return DAG.getNode(Opc, dl, VT, V1, DAG.getConstant(TargetMask, MVT::i8));
2787  }
2788
2789  return SDValue();
2790}
2791
2792static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2793               SDValue V1, SDValue V2, unsigned TargetMask, SelectionDAG &DAG) {
2794  switch(Opc) {
2795  default: llvm_unreachable("Unknown x86 shuffle node");
2796  case X86ISD::PALIGN:
2797  case X86ISD::SHUFPD:
2798  case X86ISD::SHUFPS:
2799    return DAG.getNode(Opc, dl, VT, V1, V2,
2800                       DAG.getConstant(TargetMask, MVT::i8));
2801  }
2802  return SDValue();
2803}
2804
2805static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2806                                    SDValue V1, SDValue V2, SelectionDAG &DAG) {
2807  switch(Opc) {
2808  default: llvm_unreachable("Unknown x86 shuffle node");
2809  case X86ISD::MOVLHPS:
2810  case X86ISD::MOVLHPD:
2811  case X86ISD::MOVHLPS:
2812  case X86ISD::MOVLPS:
2813  case X86ISD::MOVLPD:
2814  case X86ISD::MOVSS:
2815  case X86ISD::MOVSD:
2816  case X86ISD::UNPCKLPS:
2817  case X86ISD::UNPCKLPD:
2818  case X86ISD::VUNPCKLPS:
2819  case X86ISD::VUNPCKLPD:
2820  case X86ISD::VUNPCKLPSY:
2821  case X86ISD::VUNPCKLPDY:
2822  case X86ISD::PUNPCKLWD:
2823  case X86ISD::PUNPCKLBW:
2824  case X86ISD::PUNPCKLDQ:
2825  case X86ISD::PUNPCKLQDQ:
2826  case X86ISD::UNPCKHPS:
2827  case X86ISD::UNPCKHPD:
2828  case X86ISD::PUNPCKHWD:
2829  case X86ISD::PUNPCKHBW:
2830  case X86ISD::PUNPCKHDQ:
2831  case X86ISD::PUNPCKHQDQ:
2832    return DAG.getNode(Opc, dl, VT, V1, V2);
2833  }
2834  return SDValue();
2835}
2836
2837SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
2838  MachineFunction &MF = DAG.getMachineFunction();
2839  X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2840  int ReturnAddrIndex = FuncInfo->getRAIndex();
2841
2842  if (ReturnAddrIndex == 0) {
2843    // Set up a frame object for the return address.
2844    uint64_t SlotSize = TD->getPointerSize();
2845    ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize, -SlotSize,
2846                                                           false);
2847    FuncInfo->setRAIndex(ReturnAddrIndex);
2848  }
2849
2850  return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
2851}
2852
2853
2854bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
2855                                       bool hasSymbolicDisplacement) {
2856  // Offset should fit into 32 bit immediate field.
2857  if (!isInt<32>(Offset))
2858    return false;
2859
2860  // If we don't have a symbolic displacement - we don't have any extra
2861  // restrictions.
2862  if (!hasSymbolicDisplacement)
2863    return true;
2864
2865  // FIXME: Some tweaks might be needed for medium code model.
2866  if (M != CodeModel::Small && M != CodeModel::Kernel)
2867    return false;
2868
2869  // For small code model we assume that latest object is 16MB before end of 31
2870  // bits boundary. We may also accept pretty large negative constants knowing
2871  // that all objects are in the positive half of address space.
2872  if (M == CodeModel::Small && Offset < 16*1024*1024)
2873    return true;
2874
2875  // For kernel code model we know that all object resist in the negative half
2876  // of 32bits address space. We may not accept negative offsets, since they may
2877  // be just off and we may accept pretty large positive ones.
2878  if (M == CodeModel::Kernel && Offset > 0)
2879    return true;
2880
2881  return false;
2882}
2883
2884/// isCalleePop - Determines whether the callee is required to pop its
2885/// own arguments. Callee pop is necessary to support tail calls.
2886bool X86::isCalleePop(CallingConv::ID CallingConv,
2887                      bool is64Bit, bool IsVarArg, bool TailCallOpt) {
2888  if (IsVarArg)
2889    return false;
2890
2891  switch (CallingConv) {
2892  default:
2893    return false;
2894  case CallingConv::X86_StdCall:
2895    return !is64Bit;
2896  case CallingConv::X86_FastCall:
2897    return !is64Bit;
2898  case CallingConv::X86_ThisCall:
2899    return !is64Bit;
2900  case CallingConv::Fast:
2901    return TailCallOpt;
2902  case CallingConv::GHC:
2903    return TailCallOpt;
2904  }
2905}
2906
2907/// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
2908/// specific condition code, returning the condition code and the LHS/RHS of the
2909/// comparison to make.
2910static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
2911                               SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
2912  if (!isFP) {
2913    if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
2914      if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
2915        // X > -1   -> X == 0, jump !sign.
2916        RHS = DAG.getConstant(0, RHS.getValueType());
2917        return X86::COND_NS;
2918      } else if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
2919        // X < 0   -> X == 0, jump on sign.
2920        return X86::COND_S;
2921      } else if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
2922        // X < 1   -> X <= 0
2923        RHS = DAG.getConstant(0, RHS.getValueType());
2924        return X86::COND_LE;
2925      }
2926    }
2927
2928    switch (SetCCOpcode) {
2929    default: llvm_unreachable("Invalid integer condition!");
2930    case ISD::SETEQ:  return X86::COND_E;
2931    case ISD::SETGT:  return X86::COND_G;
2932    case ISD::SETGE:  return X86::COND_GE;
2933    case ISD::SETLT:  return X86::COND_L;
2934    case ISD::SETLE:  return X86::COND_LE;
2935    case ISD::SETNE:  return X86::COND_NE;
2936    case ISD::SETULT: return X86::COND_B;
2937    case ISD::SETUGT: return X86::COND_A;
2938    case ISD::SETULE: return X86::COND_BE;
2939    case ISD::SETUGE: return X86::COND_AE;
2940    }
2941  }
2942
2943  // First determine if it is required or is profitable to flip the operands.
2944
2945  // If LHS is a foldable load, but RHS is not, flip the condition.
2946  if (ISD::isNON_EXTLoad(LHS.getNode()) &&
2947      !ISD::isNON_EXTLoad(RHS.getNode())) {
2948    SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
2949    std::swap(LHS, RHS);
2950  }
2951
2952  switch (SetCCOpcode) {
2953  default: break;
2954  case ISD::SETOLT:
2955  case ISD::SETOLE:
2956  case ISD::SETUGT:
2957  case ISD::SETUGE:
2958    std::swap(LHS, RHS);
2959    break;
2960  }
2961
2962  // On a floating point condition, the flags are set as follows:
2963  // ZF  PF  CF   op
2964  //  0 | 0 | 0 | X > Y
2965  //  0 | 0 | 1 | X < Y
2966  //  1 | 0 | 0 | X == Y
2967  //  1 | 1 | 1 | unordered
2968  switch (SetCCOpcode) {
2969  default: llvm_unreachable("Condcode should be pre-legalized away");
2970  case ISD::SETUEQ:
2971  case ISD::SETEQ:   return X86::COND_E;
2972  case ISD::SETOLT:              // flipped
2973  case ISD::SETOGT:
2974  case ISD::SETGT:   return X86::COND_A;
2975  case ISD::SETOLE:              // flipped
2976  case ISD::SETOGE:
2977  case ISD::SETGE:   return X86::COND_AE;
2978  case ISD::SETUGT:              // flipped
2979  case ISD::SETULT:
2980  case ISD::SETLT:   return X86::COND_B;
2981  case ISD::SETUGE:              // flipped
2982  case ISD::SETULE:
2983  case ISD::SETLE:   return X86::COND_BE;
2984  case ISD::SETONE:
2985  case ISD::SETNE:   return X86::COND_NE;
2986  case ISD::SETUO:   return X86::COND_P;
2987  case ISD::SETO:    return X86::COND_NP;
2988  case ISD::SETOEQ:
2989  case ISD::SETUNE:  return X86::COND_INVALID;
2990  }
2991}
2992
2993/// hasFPCMov - is there a floating point cmov for the specific X86 condition
2994/// code. Current x86 isa includes the following FP cmov instructions:
2995/// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
2996static bool hasFPCMov(unsigned X86CC) {
2997  switch (X86CC) {
2998  default:
2999    return false;
3000  case X86::COND_B:
3001  case X86::COND_BE:
3002  case X86::COND_E:
3003  case X86::COND_P:
3004  case X86::COND_A:
3005  case X86::COND_AE:
3006  case X86::COND_NE:
3007  case X86::COND_NP:
3008    return true;
3009  }
3010}
3011
3012/// isFPImmLegal - Returns true if the target can instruction select the
3013/// specified FP immediate natively. If false, the legalizer will
3014/// materialize the FP immediate as a load from a constant pool.
3015bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3016  for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
3017    if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
3018      return true;
3019  }
3020  return false;
3021}
3022
3023/// isUndefOrInRange - Return true if Val is undef or if its value falls within
3024/// the specified range (L, H].
3025static bool isUndefOrInRange(int Val, int Low, int Hi) {
3026  return (Val < 0) || (Val >= Low && Val < Hi);
3027}
3028
3029/// isUndefOrEqual - Val is either less than zero (undef) or equal to the
3030/// specified value.
3031static bool isUndefOrEqual(int Val, int CmpVal) {
3032  if (Val < 0 || Val == CmpVal)
3033    return true;
3034  return false;
3035}
3036
3037/// isPSHUFDMask - Return true if the node specifies a shuffle of elements that
3038/// is suitable for input to PSHUFD or PSHUFW.  That is, it doesn't reference
3039/// the second operand.
3040static bool isPSHUFDMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3041  if (VT == MVT::v4f32 || VT == MVT::v4i32 )
3042    return (Mask[0] < 4 && Mask[1] < 4 && Mask[2] < 4 && Mask[3] < 4);
3043  if (VT == MVT::v2f64 || VT == MVT::v2i64)
3044    return (Mask[0] < 2 && Mask[1] < 2);
3045  return false;
3046}
3047
3048bool X86::isPSHUFDMask(ShuffleVectorSDNode *N) {
3049  SmallVector<int, 8> M;
3050  N->getMask(M);
3051  return ::isPSHUFDMask(M, N->getValueType(0));
3052}
3053
3054/// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that
3055/// is suitable for input to PSHUFHW.
3056static bool isPSHUFHWMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3057  if (VT != MVT::v8i16)
3058    return false;
3059
3060  // Lower quadword copied in order or undef.
3061  for (int i = 0; i != 4; ++i)
3062    if (Mask[i] >= 0 && Mask[i] != i)
3063      return false;
3064
3065  // Upper quadword shuffled.
3066  for (int i = 4; i != 8; ++i)
3067    if (Mask[i] >= 0 && (Mask[i] < 4 || Mask[i] > 7))
3068      return false;
3069
3070  return true;
3071}
3072
3073bool X86::isPSHUFHWMask(ShuffleVectorSDNode *N) {
3074  SmallVector<int, 8> M;
3075  N->getMask(M);
3076  return ::isPSHUFHWMask(M, N->getValueType(0));
3077}
3078
3079/// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that
3080/// is suitable for input to PSHUFLW.
3081static bool isPSHUFLWMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3082  if (VT != MVT::v8i16)
3083    return false;
3084
3085  // Upper quadword copied in order.
3086  for (int i = 4; i != 8; ++i)
3087    if (Mask[i] >= 0 && Mask[i] != i)
3088      return false;
3089
3090  // Lower quadword shuffled.
3091  for (int i = 0; i != 4; ++i)
3092    if (Mask[i] >= 4)
3093      return false;
3094
3095  return true;
3096}
3097
3098bool X86::isPSHUFLWMask(ShuffleVectorSDNode *N) {
3099  SmallVector<int, 8> M;
3100  N->getMask(M);
3101  return ::isPSHUFLWMask(M, N->getValueType(0));
3102}
3103
3104/// isPALIGNRMask - Return true if the node specifies a shuffle of elements that
3105/// is suitable for input to PALIGNR.
3106static bool isPALIGNRMask(const SmallVectorImpl<int> &Mask, EVT VT,
3107                          bool hasSSSE3) {
3108  int i, e = VT.getVectorNumElements();
3109
3110  // Do not handle v2i64 / v2f64 shuffles with palignr.
3111  if (e < 4 || !hasSSSE3)
3112    return false;
3113
3114  for (i = 0; i != e; ++i)
3115    if (Mask[i] >= 0)
3116      break;
3117
3118  // All undef, not a palignr.
3119  if (i == e)
3120    return false;
3121
3122  // Determine if it's ok to perform a palignr with only the LHS, since we
3123  // don't have access to the actual shuffle elements to see if RHS is undef.
3124  bool Unary = Mask[i] < (int)e;
3125  bool NeedsUnary = false;
3126
3127  int s = Mask[i] - i;
3128
3129  // Check the rest of the elements to see if they are consecutive.
3130  for (++i; i != e; ++i) {
3131    int m = Mask[i];
3132    if (m < 0)
3133      continue;
3134
3135    Unary = Unary && (m < (int)e);
3136    NeedsUnary = NeedsUnary || (m < s);
3137
3138    if (NeedsUnary && !Unary)
3139      return false;
3140    if (Unary && m != ((s+i) & (e-1)))
3141      return false;
3142    if (!Unary && m != (s+i))
3143      return false;
3144  }
3145  return true;
3146}
3147
3148bool X86::isPALIGNRMask(ShuffleVectorSDNode *N) {
3149  SmallVector<int, 8> M;
3150  N->getMask(M);
3151  return ::isPALIGNRMask(M, N->getValueType(0), true);
3152}
3153
3154/// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
3155/// specifies a shuffle of elements that is suitable for input to SHUFP*.
3156static bool isSHUFPMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3157  int NumElems = VT.getVectorNumElements();
3158  if (NumElems != 2 && NumElems != 4)
3159    return false;
3160
3161  int Half = NumElems / 2;
3162  for (int i = 0; i < Half; ++i)
3163    if (!isUndefOrInRange(Mask[i], 0, NumElems))
3164      return false;
3165  for (int i = Half; i < NumElems; ++i)
3166    if (!isUndefOrInRange(Mask[i], NumElems, NumElems*2))
3167      return false;
3168
3169  return true;
3170}
3171
3172bool X86::isSHUFPMask(ShuffleVectorSDNode *N) {
3173  SmallVector<int, 8> M;
3174  N->getMask(M);
3175  return ::isSHUFPMask(M, N->getValueType(0));
3176}
3177
3178/// isCommutedSHUFP - Returns true if the shuffle mask is exactly
3179/// the reverse of what x86 shuffles want. x86 shuffles requires the lower
3180/// half elements to come from vector 1 (which would equal the dest.) and
3181/// the upper half to come from vector 2.
3182static bool isCommutedSHUFPMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3183  int NumElems = VT.getVectorNumElements();
3184
3185  if (NumElems != 2 && NumElems != 4)
3186    return false;
3187
3188  int Half = NumElems / 2;
3189  for (int i = 0; i < Half; ++i)
3190    if (!isUndefOrInRange(Mask[i], NumElems, NumElems*2))
3191      return false;
3192  for (int i = Half; i < NumElems; ++i)
3193    if (!isUndefOrInRange(Mask[i], 0, NumElems))
3194      return false;
3195  return true;
3196}
3197
3198static bool isCommutedSHUFP(ShuffleVectorSDNode *N) {
3199  SmallVector<int, 8> M;
3200  N->getMask(M);
3201  return isCommutedSHUFPMask(M, N->getValueType(0));
3202}
3203
3204/// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
3205/// specifies a shuffle of elements that is suitable for input to MOVHLPS.
3206bool X86::isMOVHLPSMask(ShuffleVectorSDNode *N) {
3207  if (N->getValueType(0).getVectorNumElements() != 4)
3208    return false;
3209
3210  // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
3211  return isUndefOrEqual(N->getMaskElt(0), 6) &&
3212         isUndefOrEqual(N->getMaskElt(1), 7) &&
3213         isUndefOrEqual(N->getMaskElt(2), 2) &&
3214         isUndefOrEqual(N->getMaskElt(3), 3);
3215}
3216
3217/// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
3218/// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
3219/// <2, 3, 2, 3>
3220bool X86::isMOVHLPS_v_undef_Mask(ShuffleVectorSDNode *N) {
3221  unsigned NumElems = N->getValueType(0).getVectorNumElements();
3222
3223  if (NumElems != 4)
3224    return false;
3225
3226  return isUndefOrEqual(N->getMaskElt(0), 2) &&
3227  isUndefOrEqual(N->getMaskElt(1), 3) &&
3228  isUndefOrEqual(N->getMaskElt(2), 2) &&
3229  isUndefOrEqual(N->getMaskElt(3), 3);
3230}
3231
3232/// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
3233/// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
3234bool X86::isMOVLPMask(ShuffleVectorSDNode *N) {
3235  unsigned NumElems = N->getValueType(0).getVectorNumElements();
3236
3237  if (NumElems != 2 && NumElems != 4)
3238    return false;
3239
3240  for (unsigned i = 0; i < NumElems/2; ++i)
3241    if (!isUndefOrEqual(N->getMaskElt(i), i + NumElems))
3242      return false;
3243
3244  for (unsigned i = NumElems/2; i < NumElems; ++i)
3245    if (!isUndefOrEqual(N->getMaskElt(i), i))
3246      return false;
3247
3248  return true;
3249}
3250
3251/// isMOVLHPSMask - Return true if the specified VECTOR_SHUFFLE operand
3252/// specifies a shuffle of elements that is suitable for input to MOVLHPS.
3253bool X86::isMOVLHPSMask(ShuffleVectorSDNode *N) {
3254  unsigned NumElems = N->getValueType(0).getVectorNumElements();
3255
3256  if ((NumElems != 2 && NumElems != 4)
3257      || N->getValueType(0).getSizeInBits() > 128)
3258    return false;
3259
3260  for (unsigned i = 0; i < NumElems/2; ++i)
3261    if (!isUndefOrEqual(N->getMaskElt(i), i))
3262      return false;
3263
3264  for (unsigned i = 0; i < NumElems/2; ++i)
3265    if (!isUndefOrEqual(N->getMaskElt(i + NumElems/2), i + NumElems))
3266      return false;
3267
3268  return true;
3269}
3270
3271/// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
3272/// specifies a shuffle of elements that is suitable for input to UNPCKL.
3273static bool isUNPCKLMask(const SmallVectorImpl<int> &Mask, EVT VT,
3274                         bool V2IsSplat = false) {
3275  int NumElts = VT.getVectorNumElements();
3276  if (NumElts != 2 && NumElts != 4 && NumElts != 8 && NumElts != 16)
3277    return false;
3278
3279  // Handle vector lengths > 128 bits.  Define a "section" as a set of
3280  // 128 bits.  AVX defines UNPCK* to operate independently on 128-bit
3281  // sections.
3282  unsigned NumSections = VT.getSizeInBits() / 128;
3283  if (NumSections == 0 ) NumSections = 1;  // Handle MMX
3284  unsigned NumSectionElts = NumElts / NumSections;
3285
3286  unsigned Start = 0;
3287  unsigned End = NumSectionElts;
3288  for (unsigned s = 0; s < NumSections; ++s) {
3289    for (unsigned i = Start, j = s * NumSectionElts;
3290         i != End;
3291         i += 2, ++j) {
3292      int BitI  = Mask[i];
3293      int BitI1 = Mask[i+1];
3294      if (!isUndefOrEqual(BitI, j))
3295        return false;
3296      if (V2IsSplat) {
3297        if (!isUndefOrEqual(BitI1, NumElts))
3298          return false;
3299      } else {
3300        if (!isUndefOrEqual(BitI1, j + NumElts))
3301          return false;
3302      }
3303    }
3304    // Process the next 128 bits.
3305    Start += NumSectionElts;
3306    End += NumSectionElts;
3307  }
3308
3309  return true;
3310}
3311
3312bool X86::isUNPCKLMask(ShuffleVectorSDNode *N, bool V2IsSplat) {
3313  SmallVector<int, 8> M;
3314  N->getMask(M);
3315  return ::isUNPCKLMask(M, N->getValueType(0), V2IsSplat);
3316}
3317
3318/// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
3319/// specifies a shuffle of elements that is suitable for input to UNPCKH.
3320static bool isUNPCKHMask(const SmallVectorImpl<int> &Mask, EVT VT,
3321                         bool V2IsSplat = false) {
3322  int NumElts = VT.getVectorNumElements();
3323  if (NumElts != 2 && NumElts != 4 && NumElts != 8 && NumElts != 16)
3324    return false;
3325
3326  for (int i = 0, j = 0; i != NumElts; i += 2, ++j) {
3327    int BitI  = Mask[i];
3328    int BitI1 = Mask[i+1];
3329    if (!isUndefOrEqual(BitI, j + NumElts/2))
3330      return false;
3331    if (V2IsSplat) {
3332      if (isUndefOrEqual(BitI1, NumElts))
3333        return false;
3334    } else {
3335      if (!isUndefOrEqual(BitI1, j + NumElts/2 + NumElts))
3336        return false;
3337    }
3338  }
3339  return true;
3340}
3341
3342bool X86::isUNPCKHMask(ShuffleVectorSDNode *N, bool V2IsSplat) {
3343  SmallVector<int, 8> M;
3344  N->getMask(M);
3345  return ::isUNPCKHMask(M, N->getValueType(0), V2IsSplat);
3346}
3347
3348/// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
3349/// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
3350/// <0, 0, 1, 1>
3351static bool isUNPCKL_v_undef_Mask(const SmallVectorImpl<int> &Mask, EVT VT) {
3352  int NumElems = VT.getVectorNumElements();
3353  if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
3354    return false;
3355
3356  // Handle vector lengths > 128 bits.  Define a "section" as a set of
3357  // 128 bits.  AVX defines UNPCK* to operate independently on 128-bit
3358  // sections.
3359  unsigned NumSections = VT.getSizeInBits() / 128;
3360  if (NumSections == 0 ) NumSections = 1;  // Handle MMX
3361  unsigned NumSectionElts = NumElems / NumSections;
3362
3363  for (unsigned s = 0; s < NumSections; ++s) {
3364    for (unsigned i = s * NumSectionElts, j = s * NumSectionElts;
3365         i != NumSectionElts * (s + 1);
3366         i += 2, ++j) {
3367      int BitI  = Mask[i];
3368      int BitI1 = Mask[i+1];
3369
3370      if (!isUndefOrEqual(BitI, j))
3371        return false;
3372      if (!isUndefOrEqual(BitI1, j))
3373        return false;
3374    }
3375  }
3376
3377  return true;
3378}
3379
3380bool X86::isUNPCKL_v_undef_Mask(ShuffleVectorSDNode *N) {
3381  SmallVector<int, 8> M;
3382  N->getMask(M);
3383  return ::isUNPCKL_v_undef_Mask(M, N->getValueType(0));
3384}
3385
3386/// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
3387/// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
3388/// <2, 2, 3, 3>
3389static bool isUNPCKH_v_undef_Mask(const SmallVectorImpl<int> &Mask, EVT VT) {
3390  int NumElems = VT.getVectorNumElements();
3391  if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
3392    return false;
3393
3394  for (int i = 0, j = NumElems / 2; i != NumElems; i += 2, ++j) {
3395    int BitI  = Mask[i];
3396    int BitI1 = Mask[i+1];
3397    if (!isUndefOrEqual(BitI, j))
3398      return false;
3399    if (!isUndefOrEqual(BitI1, j))
3400      return false;
3401  }
3402  return true;
3403}
3404
3405bool X86::isUNPCKH_v_undef_Mask(ShuffleVectorSDNode *N) {
3406  SmallVector<int, 8> M;
3407  N->getMask(M);
3408  return ::isUNPCKH_v_undef_Mask(M, N->getValueType(0));
3409}
3410
3411/// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
3412/// specifies a shuffle of elements that is suitable for input to MOVSS,
3413/// MOVSD, and MOVD, i.e. setting the lowest element.
3414static bool isMOVLMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3415  if (VT.getVectorElementType().getSizeInBits() < 32)
3416    return false;
3417
3418  int NumElts = VT.getVectorNumElements();
3419
3420  if (!isUndefOrEqual(Mask[0], NumElts))
3421    return false;
3422
3423  for (int i = 1; i < NumElts; ++i)
3424    if (!isUndefOrEqual(Mask[i], i))
3425      return false;
3426
3427  return true;
3428}
3429
3430bool X86::isMOVLMask(ShuffleVectorSDNode *N) {
3431  SmallVector<int, 8> M;
3432  N->getMask(M);
3433  return ::isMOVLMask(M, N->getValueType(0));
3434}
3435
3436/// isCommutedMOVL - Returns true if the shuffle mask is except the reverse
3437/// of what x86 movss want. X86 movs requires the lowest  element to be lowest
3438/// element of vector 2 and the other elements to come from vector 1 in order.
3439static bool isCommutedMOVLMask(const SmallVectorImpl<int> &Mask, EVT VT,
3440                               bool V2IsSplat = false, bool V2IsUndef = false) {
3441  int NumOps = VT.getVectorNumElements();
3442  if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
3443    return false;
3444
3445  if (!isUndefOrEqual(Mask[0], 0))
3446    return false;
3447
3448  for (int i = 1; i < NumOps; ++i)
3449    if (!(isUndefOrEqual(Mask[i], i+NumOps) ||
3450          (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) ||
3451          (V2IsSplat && isUndefOrEqual(Mask[i], NumOps))))
3452      return false;
3453
3454  return true;
3455}
3456
3457static bool isCommutedMOVL(ShuffleVectorSDNode *N, bool V2IsSplat = false,
3458                           bool V2IsUndef = false) {
3459  SmallVector<int, 8> M;
3460  N->getMask(M);
3461  return isCommutedMOVLMask(M, N->getValueType(0), V2IsSplat, V2IsUndef);
3462}
3463
3464/// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3465/// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
3466bool X86::isMOVSHDUPMask(ShuffleVectorSDNode *N) {
3467  if (N->getValueType(0).getVectorNumElements() != 4)
3468    return false;
3469
3470  // Expect 1, 1, 3, 3
3471  for (unsigned i = 0; i < 2; ++i) {
3472    int Elt = N->getMaskElt(i);
3473    if (Elt >= 0 && Elt != 1)
3474      return false;
3475  }
3476
3477  bool HasHi = false;
3478  for (unsigned i = 2; i < 4; ++i) {
3479    int Elt = N->getMaskElt(i);
3480    if (Elt >= 0 && Elt != 3)
3481      return false;
3482    if (Elt == 3)
3483      HasHi = true;
3484  }
3485  // Don't use movshdup if it can be done with a shufps.
3486  // FIXME: verify that matching u, u, 3, 3 is what we want.
3487  return HasHi;
3488}
3489
3490/// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3491/// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
3492bool X86::isMOVSLDUPMask(ShuffleVectorSDNode *N) {
3493  if (N->getValueType(0).getVectorNumElements() != 4)
3494    return false;
3495
3496  // Expect 0, 0, 2, 2
3497  for (unsigned i = 0; i < 2; ++i)
3498    if (N->getMaskElt(i) > 0)
3499      return false;
3500
3501  bool HasHi = false;
3502  for (unsigned i = 2; i < 4; ++i) {
3503    int Elt = N->getMaskElt(i);
3504    if (Elt >= 0 && Elt != 2)
3505      return false;
3506    if (Elt == 2)
3507      HasHi = true;
3508  }
3509  // Don't use movsldup if it can be done with a shufps.
3510  return HasHi;
3511}
3512
3513/// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3514/// specifies a shuffle of elements that is suitable for input to MOVDDUP.
3515bool X86::isMOVDDUPMask(ShuffleVectorSDNode *N) {
3516  int e = N->getValueType(0).getVectorNumElements() / 2;
3517
3518  for (int i = 0; i < e; ++i)
3519    if (!isUndefOrEqual(N->getMaskElt(i), i))
3520      return false;
3521  for (int i = 0; i < e; ++i)
3522    if (!isUndefOrEqual(N->getMaskElt(e+i), i))
3523      return false;
3524  return true;
3525}
3526
3527/// isVEXTRACTF128Index - Return true if the specified
3528/// EXTRACT_SUBVECTOR operand specifies a vector extract that is
3529/// suitable for input to VEXTRACTF128.
3530bool X86::isVEXTRACTF128Index(SDNode *N) {
3531  if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
3532    return false;
3533
3534  // The index should be aligned on a 128-bit boundary.
3535  uint64_t Index =
3536    cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
3537
3538  unsigned VL = N->getValueType(0).getVectorNumElements();
3539  unsigned VBits = N->getValueType(0).getSizeInBits();
3540  unsigned ElSize = VBits / VL;
3541  bool Result = (Index * ElSize) % 128 == 0;
3542
3543  return Result;
3544}
3545
3546/// isVINSERTF128Index - Return true if the specified INSERT_SUBVECTOR
3547/// operand specifies a subvector insert that is suitable for input to
3548/// VINSERTF128.
3549bool X86::isVINSERTF128Index(SDNode *N) {
3550  if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
3551    return false;
3552
3553  // The index should be aligned on a 128-bit boundary.
3554  uint64_t Index =
3555    cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
3556
3557  unsigned VL = N->getValueType(0).getVectorNumElements();
3558  unsigned VBits = N->getValueType(0).getSizeInBits();
3559  unsigned ElSize = VBits / VL;
3560  bool Result = (Index * ElSize) % 128 == 0;
3561
3562  return Result;
3563}
3564
3565/// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
3566/// the specified VECTOR_SHUFFLE mask with PSHUF* and SHUFP* instructions.
3567unsigned X86::getShuffleSHUFImmediate(SDNode *N) {
3568  ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3569  int NumOperands = SVOp->getValueType(0).getVectorNumElements();
3570
3571  unsigned Shift = (NumOperands == 4) ? 2 : 1;
3572  unsigned Mask = 0;
3573  for (int i = 0; i < NumOperands; ++i) {
3574    int Val = SVOp->getMaskElt(NumOperands-i-1);
3575    if (Val < 0) Val = 0;
3576    if (Val >= NumOperands) Val -= NumOperands;
3577    Mask |= Val;
3578    if (i != NumOperands - 1)
3579      Mask <<= Shift;
3580  }
3581  return Mask;
3582}
3583
3584/// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
3585/// the specified VECTOR_SHUFFLE mask with the PSHUFHW instruction.
3586unsigned X86::getShufflePSHUFHWImmediate(SDNode *N) {
3587  ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3588  unsigned Mask = 0;
3589  // 8 nodes, but we only care about the last 4.
3590  for (unsigned i = 7; i >= 4; --i) {
3591    int Val = SVOp->getMaskElt(i);
3592    if (Val >= 0)
3593      Mask |= (Val - 4);
3594    if (i != 4)
3595      Mask <<= 2;
3596  }
3597  return Mask;
3598}
3599
3600/// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
3601/// the specified VECTOR_SHUFFLE mask with the PSHUFLW instruction.
3602unsigned X86::getShufflePSHUFLWImmediate(SDNode *N) {
3603  ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3604  unsigned Mask = 0;
3605  // 8 nodes, but we only care about the first 4.
3606  for (int i = 3; i >= 0; --i) {
3607    int Val = SVOp->getMaskElt(i);
3608    if (Val >= 0)
3609      Mask |= Val;
3610    if (i != 0)
3611      Mask <<= 2;
3612  }
3613  return Mask;
3614}
3615
3616/// getShufflePALIGNRImmediate - Return the appropriate immediate to shuffle
3617/// the specified VECTOR_SHUFFLE mask with the PALIGNR instruction.
3618unsigned X86::getShufflePALIGNRImmediate(SDNode *N) {
3619  ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3620  EVT VVT = N->getValueType(0);
3621  unsigned EltSize = VVT.getVectorElementType().getSizeInBits() >> 3;
3622  int Val = 0;
3623
3624  unsigned i, e;
3625  for (i = 0, e = VVT.getVectorNumElements(); i != e; ++i) {
3626    Val = SVOp->getMaskElt(i);
3627    if (Val >= 0)
3628      break;
3629  }
3630  return (Val - i) * EltSize;
3631}
3632
3633/// getExtractVEXTRACTF128Immediate - Return the appropriate immediate
3634/// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF128
3635/// instructions.
3636unsigned X86::getExtractVEXTRACTF128Immediate(SDNode *N) {
3637  if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
3638    llvm_unreachable("Illegal extract subvector for VEXTRACTF128");
3639
3640  uint64_t Index =
3641    cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
3642
3643  EVT VecVT = N->getOperand(0).getValueType();
3644  EVT ElVT = VecVT.getVectorElementType();
3645
3646  unsigned NumElemsPerChunk = 128 / ElVT.getSizeInBits();
3647
3648  return Index / NumElemsPerChunk;
3649}
3650
3651/// getInsertVINSERTF128Immediate - Return the appropriate immediate
3652/// to insert at the specified INSERT_SUBVECTOR index with VINSERTF128
3653/// instructions.
3654unsigned X86::getInsertVINSERTF128Immediate(SDNode *N) {
3655  if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
3656    llvm_unreachable("Illegal insert subvector for VINSERTF128");
3657
3658  uint64_t Index =
3659    cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
3660
3661  EVT VecVT = N->getValueType(0);
3662  EVT ElVT = VecVT.getVectorElementType();
3663
3664  unsigned NumElemsPerChunk = 128 / ElVT.getSizeInBits();
3665
3666  return Index / NumElemsPerChunk;
3667}
3668
3669/// isZeroNode - Returns true if Elt is a constant zero or a floating point
3670/// constant +0.0.
3671bool X86::isZeroNode(SDValue Elt) {
3672  return ((isa<ConstantSDNode>(Elt) &&
3673           cast<ConstantSDNode>(Elt)->isNullValue()) ||
3674          (isa<ConstantFPSDNode>(Elt) &&
3675           cast<ConstantFPSDNode>(Elt)->getValueAPF().isPosZero()));
3676}
3677
3678/// CommuteVectorShuffle - Swap vector_shuffle operands as well as values in
3679/// their permute mask.
3680static SDValue CommuteVectorShuffle(ShuffleVectorSDNode *SVOp,
3681                                    SelectionDAG &DAG) {
3682  EVT VT = SVOp->getValueType(0);
3683  unsigned NumElems = VT.getVectorNumElements();
3684  SmallVector<int, 8> MaskVec;
3685
3686  for (unsigned i = 0; i != NumElems; ++i) {
3687    int idx = SVOp->getMaskElt(i);
3688    if (idx < 0)
3689      MaskVec.push_back(idx);
3690    else if (idx < (int)NumElems)
3691      MaskVec.push_back(idx + NumElems);
3692    else
3693      MaskVec.push_back(idx - NumElems);
3694  }
3695  return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(1),
3696                              SVOp->getOperand(0), &MaskVec[0]);
3697}
3698
3699/// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
3700/// the two vector operands have swapped position.
3701static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask, EVT VT) {
3702  unsigned NumElems = VT.getVectorNumElements();
3703  for (unsigned i = 0; i != NumElems; ++i) {
3704    int idx = Mask[i];
3705    if (idx < 0)
3706      continue;
3707    else if (idx < (int)NumElems)
3708      Mask[i] = idx + NumElems;
3709    else
3710      Mask[i] = idx - NumElems;
3711  }
3712}
3713
3714/// ShouldXformToMOVHLPS - Return true if the node should be transformed to
3715/// match movhlps. The lower half elements should come from upper half of
3716/// V1 (and in order), and the upper half elements should come from the upper
3717/// half of V2 (and in order).
3718static bool ShouldXformToMOVHLPS(ShuffleVectorSDNode *Op) {
3719  if (Op->getValueType(0).getVectorNumElements() != 4)
3720    return false;
3721  for (unsigned i = 0, e = 2; i != e; ++i)
3722    if (!isUndefOrEqual(Op->getMaskElt(i), i+2))
3723      return false;
3724  for (unsigned i = 2; i != 4; ++i)
3725    if (!isUndefOrEqual(Op->getMaskElt(i), i+4))
3726      return false;
3727  return true;
3728}
3729
3730/// isScalarLoadToVector - Returns true if the node is a scalar load that
3731/// is promoted to a vector. It also returns the LoadSDNode by reference if
3732/// required.
3733static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = NULL) {
3734  if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
3735    return false;
3736  N = N->getOperand(0).getNode();
3737  if (!ISD::isNON_EXTLoad(N))
3738    return false;
3739  if (LD)
3740    *LD = cast<LoadSDNode>(N);
3741  return true;
3742}
3743
3744/// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
3745/// match movlp{s|d}. The lower half elements should come from lower half of
3746/// V1 (and in order), and the upper half elements should come from the upper
3747/// half of V2 (and in order). And since V1 will become the source of the
3748/// MOVLP, it must be either a vector load or a scalar load to vector.
3749static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2,
3750                               ShuffleVectorSDNode *Op) {
3751  if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
3752    return false;
3753  // Is V2 is a vector load, don't do this transformation. We will try to use
3754  // load folding shufps op.
3755  if (ISD::isNON_EXTLoad(V2))
3756    return false;
3757
3758  unsigned NumElems = Op->getValueType(0).getVectorNumElements();
3759
3760  if (NumElems != 2 && NumElems != 4)
3761    return false;
3762  for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3763    if (!isUndefOrEqual(Op->getMaskElt(i), i))
3764      return false;
3765  for (unsigned i = NumElems/2; i != NumElems; ++i)
3766    if (!isUndefOrEqual(Op->getMaskElt(i), i+NumElems))
3767      return false;
3768  return true;
3769}
3770
3771/// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
3772/// all the same.
3773static bool isSplatVector(SDNode *N) {
3774  if (N->getOpcode() != ISD::BUILD_VECTOR)
3775    return false;
3776
3777  SDValue SplatValue = N->getOperand(0);
3778  for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
3779    if (N->getOperand(i) != SplatValue)
3780      return false;
3781  return true;
3782}
3783
3784/// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
3785/// to an zero vector.
3786/// FIXME: move to dag combiner / method on ShuffleVectorSDNode
3787static bool isZeroShuffle(ShuffleVectorSDNode *N) {
3788  SDValue V1 = N->getOperand(0);
3789  SDValue V2 = N->getOperand(1);
3790  unsigned NumElems = N->getValueType(0).getVectorNumElements();
3791  for (unsigned i = 0; i != NumElems; ++i) {
3792    int Idx = N->getMaskElt(i);
3793    if (Idx >= (int)NumElems) {
3794      unsigned Opc = V2.getOpcode();
3795      if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
3796        continue;
3797      if (Opc != ISD::BUILD_VECTOR ||
3798          !X86::isZeroNode(V2.getOperand(Idx-NumElems)))
3799        return false;
3800    } else if (Idx >= 0) {
3801      unsigned Opc = V1.getOpcode();
3802      if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
3803        continue;
3804      if (Opc != ISD::BUILD_VECTOR ||
3805          !X86::isZeroNode(V1.getOperand(Idx)))
3806        return false;
3807    }
3808  }
3809  return true;
3810}
3811
3812/// getZeroVector - Returns a vector of specified type with all zero elements.
3813///
3814static SDValue getZeroVector(EVT VT, bool HasSSE2, SelectionDAG &DAG,
3815                             DebugLoc dl) {
3816  assert(VT.isVector() && "Expected a vector type");
3817
3818  // Always build SSE zero vectors as <4 x i32> bitcasted
3819  // to their dest type. This ensures they get CSE'd.
3820  SDValue Vec;
3821  if (VT.getSizeInBits() == 128) {  // SSE
3822    if (HasSSE2) {  // SSE2
3823      SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
3824      Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
3825    } else { // SSE1
3826      SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
3827      Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
3828    }
3829  } else if (VT.getSizeInBits() == 256) { // AVX
3830    // 256-bit logic and arithmetic instructions in AVX are
3831    // all floating-point, no support for integer ops. Default
3832    // to emitting fp zeroed vectors then.
3833    SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
3834    SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
3835    Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops, 8);
3836  }
3837  return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
3838}
3839
3840/// getOnesVector - Returns a vector of specified type with all bits set.
3841///
3842static SDValue getOnesVector(EVT VT, SelectionDAG &DAG, DebugLoc dl) {
3843  assert(VT.isVector() && "Expected a vector type");
3844
3845  // Always build ones vectors as <4 x i32> or <2 x i32> bitcasted to their dest
3846  // type.  This ensures they get CSE'd.
3847  SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
3848  SDValue Vec;
3849  Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
3850  return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
3851}
3852
3853
3854/// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
3855/// that point to V2 points to its first element.
3856static SDValue NormalizeMask(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
3857  EVT VT = SVOp->getValueType(0);
3858  unsigned NumElems = VT.getVectorNumElements();
3859
3860  bool Changed = false;
3861  SmallVector<int, 8> MaskVec;
3862  SVOp->getMask(MaskVec);
3863
3864  for (unsigned i = 0; i != NumElems; ++i) {
3865    if (MaskVec[i] > (int)NumElems) {
3866      MaskVec[i] = NumElems;
3867      Changed = true;
3868    }
3869  }
3870  if (Changed)
3871    return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(0),
3872                                SVOp->getOperand(1), &MaskVec[0]);
3873  return SDValue(SVOp, 0);
3874}
3875
3876/// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
3877/// operation of specified width.
3878static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
3879                       SDValue V2) {
3880  unsigned NumElems = VT.getVectorNumElements();
3881  SmallVector<int, 8> Mask;
3882  Mask.push_back(NumElems);
3883  for (unsigned i = 1; i != NumElems; ++i)
3884    Mask.push_back(i);
3885  return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
3886}
3887
3888/// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
3889static SDValue getUnpackl(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
3890                          SDValue V2) {
3891  unsigned NumElems = VT.getVectorNumElements();
3892  SmallVector<int, 8> Mask;
3893  for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
3894    Mask.push_back(i);
3895    Mask.push_back(i + NumElems);
3896  }
3897  return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
3898}
3899
3900/// getUnpackhMask - Returns a vector_shuffle node for an unpackh operation.
3901static SDValue getUnpackh(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
3902                          SDValue V2) {
3903  unsigned NumElems = VT.getVectorNumElements();
3904  unsigned Half = NumElems/2;
3905  SmallVector<int, 8> Mask;
3906  for (unsigned i = 0; i != Half; ++i) {
3907    Mask.push_back(i + Half);
3908    Mask.push_back(i + NumElems + Half);
3909  }
3910  return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
3911}
3912
3913/// PromoteSplat - Promote a splat of v4i32, v8i16 or v16i8 to v4f32.
3914static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG) {
3915  EVT PVT = MVT::v4f32;
3916  EVT VT = SV->getValueType(0);
3917  DebugLoc dl = SV->getDebugLoc();
3918  SDValue V1 = SV->getOperand(0);
3919  int NumElems = VT.getVectorNumElements();
3920  int EltNo = SV->getSplatIndex();
3921
3922  // unpack elements to the correct location
3923  while (NumElems > 4) {
3924    if (EltNo < NumElems/2) {
3925      V1 = getUnpackl(DAG, dl, VT, V1, V1);
3926    } else {
3927      V1 = getUnpackh(DAG, dl, VT, V1, V1);
3928      EltNo -= NumElems/2;
3929    }
3930    NumElems >>= 1;
3931  }
3932
3933  // Perform the splat.
3934  int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo };
3935  V1 = DAG.getNode(ISD::BITCAST, dl, PVT, V1);
3936  V1 = DAG.getVectorShuffle(PVT, dl, V1, DAG.getUNDEF(PVT), &SplatMask[0]);
3937  return DAG.getNode(ISD::BITCAST, dl, VT, V1);
3938}
3939
3940/// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
3941/// vector of zero or undef vector.  This produces a shuffle where the low
3942/// element of V2 is swizzled into the zero/undef vector, landing at element
3943/// Idx.  This produces a shuffle mask like 4,1,2,3 (idx=0) or  0,1,2,4 (idx=3).
3944static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
3945                                             bool isZero, bool HasSSE2,
3946                                             SelectionDAG &DAG) {
3947  EVT VT = V2.getValueType();
3948  SDValue V1 = isZero
3949    ? getZeroVector(VT, HasSSE2, DAG, V2.getDebugLoc()) : DAG.getUNDEF(VT);
3950  unsigned NumElems = VT.getVectorNumElements();
3951  SmallVector<int, 16> MaskVec;
3952  for (unsigned i = 0; i != NumElems; ++i)
3953    // If this is the insertion idx, put the low elt of V2 here.
3954    MaskVec.push_back(i == Idx ? NumElems : i);
3955  return DAG.getVectorShuffle(VT, V2.getDebugLoc(), V1, V2, &MaskVec[0]);
3956}
3957
3958/// getShuffleScalarElt - Returns the scalar element that will make up the ith
3959/// element of the result of the vector shuffle.
3960static SDValue getShuffleScalarElt(SDNode *N, int Index, SelectionDAG &DAG,
3961                                   unsigned Depth) {
3962  if (Depth == 6)
3963    return SDValue();  // Limit search depth.
3964
3965  SDValue V = SDValue(N, 0);
3966  EVT VT = V.getValueType();
3967  unsigned Opcode = V.getOpcode();
3968
3969  // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
3970  if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
3971    Index = SV->getMaskElt(Index);
3972
3973    if (Index < 0)
3974      return DAG.getUNDEF(VT.getVectorElementType());
3975
3976    int NumElems = VT.getVectorNumElements();
3977    SDValue NewV = (Index < NumElems) ? SV->getOperand(0) : SV->getOperand(1);
3978    return getShuffleScalarElt(NewV.getNode(), Index % NumElems, DAG, Depth+1);
3979  }
3980
3981  // Recurse into target specific vector shuffles to find scalars.
3982  if (isTargetShuffle(Opcode)) {
3983    int NumElems = VT.getVectorNumElements();
3984    SmallVector<unsigned, 16> ShuffleMask;
3985    SDValue ImmN;
3986
3987    switch(Opcode) {
3988    case X86ISD::SHUFPS:
3989    case X86ISD::SHUFPD:
3990      ImmN = N->getOperand(N->getNumOperands()-1);
3991      DecodeSHUFPSMask(NumElems,
3992                       cast<ConstantSDNode>(ImmN)->getZExtValue(),
3993                       ShuffleMask);
3994      break;
3995    case X86ISD::PUNPCKHBW:
3996    case X86ISD::PUNPCKHWD:
3997    case X86ISD::PUNPCKHDQ:
3998    case X86ISD::PUNPCKHQDQ:
3999      DecodePUNPCKHMask(NumElems, ShuffleMask);
4000      break;
4001    case X86ISD::UNPCKHPS:
4002    case X86ISD::UNPCKHPD:
4003      DecodeUNPCKHPMask(NumElems, ShuffleMask);
4004      break;
4005    case X86ISD::PUNPCKLBW:
4006    case X86ISD::PUNPCKLWD:
4007    case X86ISD::PUNPCKLDQ:
4008    case X86ISD::PUNPCKLQDQ:
4009      DecodePUNPCKLMask(VT, ShuffleMask);
4010      break;
4011    case X86ISD::UNPCKLPS:
4012    case X86ISD::UNPCKLPD:
4013    case X86ISD::VUNPCKLPS:
4014    case X86ISD::VUNPCKLPD:
4015    case X86ISD::VUNPCKLPSY:
4016    case X86ISD::VUNPCKLPDY:
4017      DecodeUNPCKLPMask(VT, ShuffleMask);
4018      break;
4019    case X86ISD::MOVHLPS:
4020      DecodeMOVHLPSMask(NumElems, ShuffleMask);
4021      break;
4022    case X86ISD::MOVLHPS:
4023      DecodeMOVLHPSMask(NumElems, ShuffleMask);
4024      break;
4025    case X86ISD::PSHUFD:
4026      ImmN = N->getOperand(N->getNumOperands()-1);
4027      DecodePSHUFMask(NumElems,
4028                      cast<ConstantSDNode>(ImmN)->getZExtValue(),
4029                      ShuffleMask);
4030      break;
4031    case X86ISD::PSHUFHW:
4032      ImmN = N->getOperand(N->getNumOperands()-1);
4033      DecodePSHUFHWMask(cast<ConstantSDNode>(ImmN)->getZExtValue(),
4034                        ShuffleMask);
4035      break;
4036    case X86ISD::PSHUFLW:
4037      ImmN = N->getOperand(N->getNumOperands()-1);
4038      DecodePSHUFLWMask(cast<ConstantSDNode>(ImmN)->getZExtValue(),
4039                        ShuffleMask);
4040      break;
4041    case X86ISD::MOVSS:
4042    case X86ISD::MOVSD: {
4043      // The index 0 always comes from the first element of the second source,
4044      // this is why MOVSS and MOVSD are used in the first place. The other
4045      // elements come from the other positions of the first source vector.
4046      unsigned OpNum = (Index == 0) ? 1 : 0;
4047      return getShuffleScalarElt(V.getOperand(OpNum).getNode(), Index, DAG,
4048                                 Depth+1);
4049    }
4050    default:
4051      assert("not implemented for target shuffle node");
4052      return SDValue();
4053    }
4054
4055    Index = ShuffleMask[Index];
4056    if (Index < 0)
4057      return DAG.getUNDEF(VT.getVectorElementType());
4058
4059    SDValue NewV = (Index < NumElems) ? N->getOperand(0) : N->getOperand(1);
4060    return getShuffleScalarElt(NewV.getNode(), Index % NumElems, DAG,
4061                               Depth+1);
4062  }
4063
4064  // Actual nodes that may contain scalar elements
4065  if (Opcode == ISD::BITCAST) {
4066    V = V.getOperand(0);
4067    EVT SrcVT = V.getValueType();
4068    unsigned NumElems = VT.getVectorNumElements();
4069
4070    if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
4071      return SDValue();
4072  }
4073
4074  if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
4075    return (Index == 0) ? V.getOperand(0)
4076                          : DAG.getUNDEF(VT.getVectorElementType());
4077
4078  if (V.getOpcode() == ISD::BUILD_VECTOR)
4079    return V.getOperand(Index);
4080
4081  return SDValue();
4082}
4083
4084/// getNumOfConsecutiveZeros - Return the number of elements of a vector
4085/// shuffle operation which come from a consecutively from a zero. The
4086/// search can start in two different directions, from left or right.
4087static
4088unsigned getNumOfConsecutiveZeros(SDNode *N, int NumElems,
4089                                  bool ZerosFromLeft, SelectionDAG &DAG) {
4090  int i = 0;
4091
4092  while (i < NumElems) {
4093    unsigned Index = ZerosFromLeft ? i : NumElems-i-1;
4094    SDValue Elt = getShuffleScalarElt(N, Index, DAG, 0);
4095    if (!(Elt.getNode() &&
4096         (Elt.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elt))))
4097      break;
4098    ++i;
4099  }
4100
4101  return i;
4102}
4103
4104/// isShuffleMaskConsecutive - Check if the shuffle mask indicies from MaskI to
4105/// MaskE correspond consecutively to elements from one of the vector operands,
4106/// starting from its index OpIdx. Also tell OpNum which source vector operand.
4107static
4108bool isShuffleMaskConsecutive(ShuffleVectorSDNode *SVOp, int MaskI, int MaskE,
4109                              int OpIdx, int NumElems, unsigned &OpNum) {
4110  bool SeenV1 = false;
4111  bool SeenV2 = false;
4112
4113  for (int i = MaskI; i <= MaskE; ++i, ++OpIdx) {
4114    int Idx = SVOp->getMaskElt(i);
4115    // Ignore undef indicies
4116    if (Idx < 0)
4117      continue;
4118
4119    if (Idx < NumElems)
4120      SeenV1 = true;
4121    else
4122      SeenV2 = true;
4123
4124    // Only accept consecutive elements from the same vector
4125    if ((Idx % NumElems != OpIdx) || (SeenV1 && SeenV2))
4126      return false;
4127  }
4128
4129  OpNum = SeenV1 ? 0 : 1;
4130  return true;
4131}
4132
4133/// isVectorShiftRight - Returns true if the shuffle can be implemented as a
4134/// logical left shift of a vector.
4135static bool isVectorShiftRight(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4136                               bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4137  unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
4138  unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems,
4139              false /* check zeros from right */, DAG);
4140  unsigned OpSrc;
4141
4142  if (!NumZeros)
4143    return false;
4144
4145  // Considering the elements in the mask that are not consecutive zeros,
4146  // check if they consecutively come from only one of the source vectors.
4147  //
4148  //               V1 = {X, A, B, C}     0
4149  //                         \  \  \    /
4150  //   vector_shuffle V1, V2 <1, 2, 3, X>
4151  //
4152  if (!isShuffleMaskConsecutive(SVOp,
4153            0,                   // Mask Start Index
4154            NumElems-NumZeros-1, // Mask End Index
4155            NumZeros,            // Where to start looking in the src vector
4156            NumElems,            // Number of elements in vector
4157            OpSrc))              // Which source operand ?
4158    return false;
4159
4160  isLeft = false;
4161  ShAmt = NumZeros;
4162  ShVal = SVOp->getOperand(OpSrc);
4163  return true;
4164}
4165
4166/// isVectorShiftLeft - Returns true if the shuffle can be implemented as a
4167/// logical left shift of a vector.
4168static bool isVectorShiftLeft(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4169                              bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4170  unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
4171  unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems,
4172              true /* check zeros from left */, DAG);
4173  unsigned OpSrc;
4174
4175  if (!NumZeros)
4176    return false;
4177
4178  // Considering the elements in the mask that are not consecutive zeros,
4179  // check if they consecutively come from only one of the source vectors.
4180  //
4181  //                           0    { A, B, X, X } = V2
4182  //                          / \    /  /
4183  //   vector_shuffle V1, V2 <X, X, 4, 5>
4184  //
4185  if (!isShuffleMaskConsecutive(SVOp,
4186            NumZeros,     // Mask Start Index
4187            NumElems-1,   // Mask End Index
4188            0,            // Where to start looking in the src vector
4189            NumElems,     // Number of elements in vector
4190            OpSrc))       // Which source operand ?
4191    return false;
4192
4193  isLeft = true;
4194  ShAmt = NumZeros;
4195  ShVal = SVOp->getOperand(OpSrc);
4196  return true;
4197}
4198
4199/// isVectorShift - Returns true if the shuffle can be implemented as a
4200/// logical left or right shift of a vector.
4201static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4202                          bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4203  if (isVectorShiftLeft(SVOp, DAG, isLeft, ShVal, ShAmt) ||
4204      isVectorShiftRight(SVOp, DAG, isLeft, ShVal, ShAmt))
4205    return true;
4206
4207  return false;
4208}
4209
4210/// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
4211///
4212static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
4213                                       unsigned NumNonZero, unsigned NumZero,
4214                                       SelectionDAG &DAG,
4215                                       const TargetLowering &TLI) {
4216  if (NumNonZero > 8)
4217    return SDValue();
4218
4219  DebugLoc dl = Op.getDebugLoc();
4220  SDValue V(0, 0);
4221  bool First = true;
4222  for (unsigned i = 0; i < 16; ++i) {
4223    bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
4224    if (ThisIsNonZero && First) {
4225      if (NumZero)
4226        V = getZeroVector(MVT::v8i16, true, DAG, dl);
4227      else
4228        V = DAG.getUNDEF(MVT::v8i16);
4229      First = false;
4230    }
4231
4232    if ((i & 1) != 0) {
4233      SDValue ThisElt(0, 0), LastElt(0, 0);
4234      bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
4235      if (LastIsNonZero) {
4236        LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
4237                              MVT::i16, Op.getOperand(i-1));
4238      }
4239      if (ThisIsNonZero) {
4240        ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
4241        ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
4242                              ThisElt, DAG.getConstant(8, MVT::i8));
4243        if (LastIsNonZero)
4244          ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
4245      } else
4246        ThisElt = LastElt;
4247
4248      if (ThisElt.getNode())
4249        V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
4250                        DAG.getIntPtrConstant(i/2));
4251    }
4252  }
4253
4254  return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V);
4255}
4256
4257/// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
4258///
4259static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
4260                                     unsigned NumNonZero, unsigned NumZero,
4261                                     SelectionDAG &DAG,
4262                                     const TargetLowering &TLI) {
4263  if (NumNonZero > 4)
4264    return SDValue();
4265
4266  DebugLoc dl = Op.getDebugLoc();
4267  SDValue V(0, 0);
4268  bool First = true;
4269  for (unsigned i = 0; i < 8; ++i) {
4270    bool isNonZero = (NonZeros & (1 << i)) != 0;
4271    if (isNonZero) {
4272      if (First) {
4273        if (NumZero)
4274          V = getZeroVector(MVT::v8i16, true, DAG, dl);
4275        else
4276          V = DAG.getUNDEF(MVT::v8i16);
4277        First = false;
4278      }
4279      V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
4280                      MVT::v8i16, V, Op.getOperand(i),
4281                      DAG.getIntPtrConstant(i));
4282    }
4283  }
4284
4285  return V;
4286}
4287
4288/// getVShift - Return a vector logical shift node.
4289///
4290static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
4291                         unsigned NumBits, SelectionDAG &DAG,
4292                         const TargetLowering &TLI, DebugLoc dl) {
4293  EVT ShVT = MVT::v2i64;
4294  unsigned Opc = isLeft ? X86ISD::VSHL : X86ISD::VSRL;
4295  SrcOp = DAG.getNode(ISD::BITCAST, dl, ShVT, SrcOp);
4296  return DAG.getNode(ISD::BITCAST, dl, VT,
4297                     DAG.getNode(Opc, dl, ShVT, SrcOp,
4298                             DAG.getConstant(NumBits,
4299                                  TLI.getShiftAmountTy(SrcOp.getValueType()))));
4300}
4301
4302SDValue
4303X86TargetLowering::LowerAsSplatVectorLoad(SDValue SrcOp, EVT VT, DebugLoc dl,
4304                                          SelectionDAG &DAG) const {
4305
4306  // Check if the scalar load can be widened into a vector load. And if
4307  // the address is "base + cst" see if the cst can be "absorbed" into
4308  // the shuffle mask.
4309  if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
4310    SDValue Ptr = LD->getBasePtr();
4311    if (!ISD::isNormalLoad(LD) || LD->isVolatile())
4312      return SDValue();
4313    EVT PVT = LD->getValueType(0);
4314    if (PVT != MVT::i32 && PVT != MVT::f32)
4315      return SDValue();
4316
4317    int FI = -1;
4318    int64_t Offset = 0;
4319    if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
4320      FI = FINode->getIndex();
4321      Offset = 0;
4322    } else if (DAG.isBaseWithConstantOffset(Ptr) &&
4323               isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
4324      FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
4325      Offset = Ptr.getConstantOperandVal(1);
4326      Ptr = Ptr.getOperand(0);
4327    } else {
4328      return SDValue();
4329    }
4330
4331    SDValue Chain = LD->getChain();
4332    // Make sure the stack object alignment is at least 16.
4333    MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
4334    if (DAG.InferPtrAlignment(Ptr) < 16) {
4335      if (MFI->isFixedObjectIndex(FI)) {
4336        // Can't change the alignment. FIXME: It's possible to compute
4337        // the exact stack offset and reference FI + adjust offset instead.
4338        // If someone *really* cares about this. That's the way to implement it.
4339        return SDValue();
4340      } else {
4341        MFI->setObjectAlignment(FI, 16);
4342      }
4343    }
4344
4345    // (Offset % 16) must be multiple of 4. Then address is then
4346    // Ptr + (Offset & ~15).
4347    if (Offset < 0)
4348      return SDValue();
4349    if ((Offset % 16) & 3)
4350      return SDValue();
4351    int64_t StartOffset = Offset & ~15;
4352    if (StartOffset)
4353      Ptr = DAG.getNode(ISD::ADD, Ptr.getDebugLoc(), Ptr.getValueType(),
4354                        Ptr,DAG.getConstant(StartOffset, Ptr.getValueType()));
4355
4356    int EltNo = (Offset - StartOffset) >> 2;
4357    int Mask[4] = { EltNo, EltNo, EltNo, EltNo };
4358    EVT VT = (PVT == MVT::i32) ? MVT::v4i32 : MVT::v4f32;
4359    SDValue V1 = DAG.getLoad(VT, dl, Chain, Ptr,
4360                             LD->getPointerInfo().getWithOffset(StartOffset),
4361                             false, false, 0);
4362    // Canonicalize it to a v4i32 shuffle.
4363    V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1);
4364    return DAG.getNode(ISD::BITCAST, dl, VT,
4365                       DAG.getVectorShuffle(MVT::v4i32, dl, V1,
4366                                            DAG.getUNDEF(MVT::v4i32),&Mask[0]));
4367  }
4368
4369  return SDValue();
4370}
4371
4372/// EltsFromConsecutiveLoads - Given the initializing elements 'Elts' of a
4373/// vector of type 'VT', see if the elements can be replaced by a single large
4374/// load which has the same value as a build_vector whose operands are 'elts'.
4375///
4376/// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
4377///
4378/// FIXME: we'd also like to handle the case where the last elements are zero
4379/// rather than undef via VZEXT_LOAD, but we do not detect that case today.
4380/// There's even a handy isZeroNode for that purpose.
4381static SDValue EltsFromConsecutiveLoads(EVT VT, SmallVectorImpl<SDValue> &Elts,
4382                                        DebugLoc &DL, SelectionDAG &DAG) {
4383  EVT EltVT = VT.getVectorElementType();
4384  unsigned NumElems = Elts.size();
4385
4386  LoadSDNode *LDBase = NULL;
4387  unsigned LastLoadedElt = -1U;
4388
4389  // For each element in the initializer, see if we've found a load or an undef.
4390  // If we don't find an initial load element, or later load elements are
4391  // non-consecutive, bail out.
4392  for (unsigned i = 0; i < NumElems; ++i) {
4393    SDValue Elt = Elts[i];
4394
4395    if (!Elt.getNode() ||
4396        (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
4397      return SDValue();
4398    if (!LDBase) {
4399      if (Elt.getNode()->getOpcode() == ISD::UNDEF)
4400        return SDValue();
4401      LDBase = cast<LoadSDNode>(Elt.getNode());
4402      LastLoadedElt = i;
4403      continue;
4404    }
4405    if (Elt.getOpcode() == ISD::UNDEF)
4406      continue;
4407
4408    LoadSDNode *LD = cast<LoadSDNode>(Elt);
4409    if (!DAG.isConsecutiveLoad(LD, LDBase, EltVT.getSizeInBits()/8, i))
4410      return SDValue();
4411    LastLoadedElt = i;
4412  }
4413
4414  // If we have found an entire vector of loads and undefs, then return a large
4415  // load of the entire vector width starting at the base pointer.  If we found
4416  // consecutive loads for the low half, generate a vzext_load node.
4417  if (LastLoadedElt == NumElems - 1) {
4418    if (DAG.InferPtrAlignment(LDBase->getBasePtr()) >= 16)
4419      return DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
4420                         LDBase->getPointerInfo(),
4421                         LDBase->isVolatile(), LDBase->isNonTemporal(), 0);
4422    return DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
4423                       LDBase->getPointerInfo(),
4424                       LDBase->isVolatile(), LDBase->isNonTemporal(),
4425                       LDBase->getAlignment());
4426  } else if (NumElems == 4 && LastLoadedElt == 1) {
4427    SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
4428    SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
4429    SDValue ResNode = DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys,
4430                                              Ops, 2, MVT::i32,
4431                                              LDBase->getMemOperand());
4432    return DAG.getNode(ISD::BITCAST, DL, VT, ResNode);
4433  }
4434  return SDValue();
4435}
4436
4437SDValue
4438X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
4439  DebugLoc dl = Op.getDebugLoc();
4440
4441  EVT VT = Op.getValueType();
4442  EVT ExtVT = VT.getVectorElementType();
4443
4444  unsigned NumElems = Op.getNumOperands();
4445
4446  // For AVX-length vectors, build the individual 128-bit pieces and
4447  // use shuffles to put them in place.
4448  if (VT.getSizeInBits() > 256 &&
4449      Subtarget->hasAVX() &&
4450      !ISD::isBuildVectorAllZeros(Op.getNode())) {
4451    SmallVector<SDValue, 8> V;
4452    V.resize(NumElems);
4453    for (unsigned i = 0; i < NumElems; ++i) {
4454      V[i] = Op.getOperand(i);
4455    }
4456
4457    EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
4458
4459    // Build the lower subvector.
4460    SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[0], NumElems/2);
4461    // Build the upper subvector.
4462    SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[NumElems / 2],
4463                                NumElems/2);
4464
4465    return ConcatVectors(Lower, Upper, DAG);
4466  }
4467
4468  // All zero's are handled with pxor in SSE2 and above, xorps in SSE1.
4469  // All one's are handled with pcmpeqd. In AVX, zero's are handled with
4470  // vpxor in 128-bit and xor{pd,ps} in 256-bit, but no 256 version of pcmpeqd
4471  // is present, so AllOnes is ignored.
4472  if (ISD::isBuildVectorAllZeros(Op.getNode()) ||
4473      (Op.getValueType().getSizeInBits() != 256 &&
4474       ISD::isBuildVectorAllOnes(Op.getNode()))) {
4475    // Canonicalize this to <4 x i32> (SSE) to
4476    // 1) ensure the zero vectors are CSE'd, and 2) ensure that i64 scalars are
4477    // eliminated on x86-32 hosts.
4478    if (Op.getValueType() == MVT::v4i32)
4479      return Op;
4480
4481    if (ISD::isBuildVectorAllOnes(Op.getNode()))
4482      return getOnesVector(Op.getValueType(), DAG, dl);
4483    return getZeroVector(Op.getValueType(), Subtarget->hasSSE2(), DAG, dl);
4484  }
4485
4486  unsigned EVTBits = ExtVT.getSizeInBits();
4487
4488  unsigned NumZero  = 0;
4489  unsigned NumNonZero = 0;
4490  unsigned NonZeros = 0;
4491  bool IsAllConstants = true;
4492  SmallSet<SDValue, 8> Values;
4493  for (unsigned i = 0; i < NumElems; ++i) {
4494    SDValue Elt = Op.getOperand(i);
4495    if (Elt.getOpcode() == ISD::UNDEF)
4496      continue;
4497    Values.insert(Elt);
4498    if (Elt.getOpcode() != ISD::Constant &&
4499        Elt.getOpcode() != ISD::ConstantFP)
4500      IsAllConstants = false;
4501    if (X86::isZeroNode(Elt))
4502      NumZero++;
4503    else {
4504      NonZeros |= (1 << i);
4505      NumNonZero++;
4506    }
4507  }
4508
4509  // All undef vector. Return an UNDEF.  All zero vectors were handled above.
4510  if (NumNonZero == 0)
4511    return DAG.getUNDEF(VT);
4512
4513  // Special case for single non-zero, non-undef, element.
4514  if (NumNonZero == 1) {
4515    unsigned Idx = CountTrailingZeros_32(NonZeros);
4516    SDValue Item = Op.getOperand(Idx);
4517
4518    // If this is an insertion of an i64 value on x86-32, and if the top bits of
4519    // the value are obviously zero, truncate the value to i32 and do the
4520    // insertion that way.  Only do this if the value is non-constant or if the
4521    // value is a constant being inserted into element 0.  It is cheaper to do
4522    // a constant pool load than it is to do a movd + shuffle.
4523    if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
4524        (!IsAllConstants || Idx == 0)) {
4525      if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
4526        // Handle SSE only.
4527        assert(VT == MVT::v2i64 && "Expected an SSE value type!");
4528        EVT VecVT = MVT::v4i32;
4529        unsigned VecElts = 4;
4530
4531        // Truncate the value (which may itself be a constant) to i32, and
4532        // convert it to a vector with movd (S2V+shuffle to zero extend).
4533        Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
4534        Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
4535        Item = getShuffleVectorZeroOrUndef(Item, 0, true,
4536                                           Subtarget->hasSSE2(), DAG);
4537
4538        // Now we have our 32-bit value zero extended in the low element of
4539        // a vector.  If Idx != 0, swizzle it into place.
4540        if (Idx != 0) {
4541          SmallVector<int, 4> Mask;
4542          Mask.push_back(Idx);
4543          for (unsigned i = 1; i != VecElts; ++i)
4544            Mask.push_back(i);
4545          Item = DAG.getVectorShuffle(VecVT, dl, Item,
4546                                      DAG.getUNDEF(Item.getValueType()),
4547                                      &Mask[0]);
4548        }
4549        return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Item);
4550      }
4551    }
4552
4553    // If we have a constant or non-constant insertion into the low element of
4554    // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
4555    // the rest of the elements.  This will be matched as movd/movq/movss/movsd
4556    // depending on what the source datatype is.
4557    if (Idx == 0) {
4558      if (NumZero == 0) {
4559        return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
4560      } else if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
4561          (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
4562        Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
4563        // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
4564        return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget->hasSSE2(),
4565                                           DAG);
4566      } else if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
4567        Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
4568        assert(VT.getSizeInBits() == 128 && "Expected an SSE value type!");
4569        EVT MiddleVT = MVT::v4i32;
4570        Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MiddleVT, Item);
4571        Item = getShuffleVectorZeroOrUndef(Item, 0, true,
4572                                           Subtarget->hasSSE2(), DAG);
4573        return DAG.getNode(ISD::BITCAST, dl, VT, Item);
4574      }
4575    }
4576
4577    // Is it a vector logical left shift?
4578    if (NumElems == 2 && Idx == 1 &&
4579        X86::isZeroNode(Op.getOperand(0)) &&
4580        !X86::isZeroNode(Op.getOperand(1))) {
4581      unsigned NumBits = VT.getSizeInBits();
4582      return getVShift(true, VT,
4583                       DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
4584                                   VT, Op.getOperand(1)),
4585                       NumBits/2, DAG, *this, dl);
4586    }
4587
4588    if (IsAllConstants) // Otherwise, it's better to do a constpool load.
4589      return SDValue();
4590
4591    // Otherwise, if this is a vector with i32 or f32 elements, and the element
4592    // is a non-constant being inserted into an element other than the low one,
4593    // we can't use a constant pool load.  Instead, use SCALAR_TO_VECTOR (aka
4594    // movd/movss) to move this into the low element, then shuffle it into
4595    // place.
4596    if (EVTBits == 32) {
4597      Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
4598
4599      // Turn it into a shuffle of zero and zero-extended scalar to vector.
4600      Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0,
4601                                         Subtarget->hasSSE2(), DAG);
4602      SmallVector<int, 8> MaskVec;
4603      for (unsigned i = 0; i < NumElems; i++)
4604        MaskVec.push_back(i == Idx ? 0 : 1);
4605      return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
4606    }
4607  }
4608
4609  // Splat is obviously ok. Let legalizer expand it to a shuffle.
4610  if (Values.size() == 1) {
4611    if (EVTBits == 32) {
4612      // Instead of a shuffle like this:
4613      // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
4614      // Check if it's possible to issue this instead.
4615      // shuffle (vload ptr)), undef, <1, 1, 1, 1>
4616      unsigned Idx = CountTrailingZeros_32(NonZeros);
4617      SDValue Item = Op.getOperand(Idx);
4618      if (Op.getNode()->isOnlyUserOf(Item.getNode()))
4619        return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
4620    }
4621    return SDValue();
4622  }
4623
4624  // A vector full of immediates; various special cases are already
4625  // handled, so this is best done with a single constant-pool load.
4626  if (IsAllConstants)
4627    return SDValue();
4628
4629  // Let legalizer expand 2-wide build_vectors.
4630  if (EVTBits == 64) {
4631    if (NumNonZero == 1) {
4632      // One half is zero or undef.
4633      unsigned Idx = CountTrailingZeros_32(NonZeros);
4634      SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
4635                                 Op.getOperand(Idx));
4636      return getShuffleVectorZeroOrUndef(V2, Idx, true,
4637                                         Subtarget->hasSSE2(), DAG);
4638    }
4639    return SDValue();
4640  }
4641
4642  // If element VT is < 32 bits, convert it to inserts into a zero vector.
4643  if (EVTBits == 8 && NumElems == 16) {
4644    SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
4645                                        *this);
4646    if (V.getNode()) return V;
4647  }
4648
4649  if (EVTBits == 16 && NumElems == 8) {
4650    SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
4651                                      *this);
4652    if (V.getNode()) return V;
4653  }
4654
4655  // If element VT is == 32 bits, turn it into a number of shuffles.
4656  SmallVector<SDValue, 8> V;
4657  V.resize(NumElems);
4658  if (NumElems == 4 && NumZero > 0) {
4659    for (unsigned i = 0; i < 4; ++i) {
4660      bool isZero = !(NonZeros & (1 << i));
4661      if (isZero)
4662        V[i] = getZeroVector(VT, Subtarget->hasSSE2(), DAG, dl);
4663      else
4664        V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
4665    }
4666
4667    for (unsigned i = 0; i < 2; ++i) {
4668      switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
4669        default: break;
4670        case 0:
4671          V[i] = V[i*2];  // Must be a zero vector.
4672          break;
4673        case 1:
4674          V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
4675          break;
4676        case 2:
4677          V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
4678          break;
4679        case 3:
4680          V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
4681          break;
4682      }
4683    }
4684
4685    SmallVector<int, 8> MaskVec;
4686    bool Reverse = (NonZeros & 0x3) == 2;
4687    for (unsigned i = 0; i < 2; ++i)
4688      MaskVec.push_back(Reverse ? 1-i : i);
4689    Reverse = ((NonZeros & (0x3 << 2)) >> 2) == 2;
4690    for (unsigned i = 0; i < 2; ++i)
4691      MaskVec.push_back(Reverse ? 1-i+NumElems : i+NumElems);
4692    return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
4693  }
4694
4695  if (Values.size() > 1 && VT.getSizeInBits() == 128) {
4696    // Check for a build vector of consecutive loads.
4697    for (unsigned i = 0; i < NumElems; ++i)
4698      V[i] = Op.getOperand(i);
4699
4700    // Check for elements which are consecutive loads.
4701    SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG);
4702    if (LD.getNode())
4703      return LD;
4704
4705    // For SSE 4.1, use insertps to put the high elements into the low element.
4706    if (getSubtarget()->hasSSE41()) {
4707      SDValue Result;
4708      if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
4709        Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
4710      else
4711        Result = DAG.getUNDEF(VT);
4712
4713      for (unsigned i = 1; i < NumElems; ++i) {
4714        if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
4715        Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
4716                             Op.getOperand(i), DAG.getIntPtrConstant(i));
4717      }
4718      return Result;
4719    }
4720
4721    // Otherwise, expand into a number of unpckl*, start by extending each of
4722    // our (non-undef) elements to the full vector width with the element in the
4723    // bottom slot of the vector (which generates no code for SSE).
4724    for (unsigned i = 0; i < NumElems; ++i) {
4725      if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
4726        V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
4727      else
4728        V[i] = DAG.getUNDEF(VT);
4729    }
4730
4731    // Next, we iteratively mix elements, e.g. for v4f32:
4732    //   Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
4733    //         : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
4734    //   Step 2: unpcklps X, Y ==>    <3, 2, 1, 0>
4735    unsigned EltStride = NumElems >> 1;
4736    while (EltStride != 0) {
4737      for (unsigned i = 0; i < EltStride; ++i) {
4738        // If V[i+EltStride] is undef and this is the first round of mixing,
4739        // then it is safe to just drop this shuffle: V[i] is already in the
4740        // right place, the one element (since it's the first round) being
4741        // inserted as undef can be dropped.  This isn't safe for successive
4742        // rounds because they will permute elements within both vectors.
4743        if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
4744            EltStride == NumElems/2)
4745          continue;
4746
4747        V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
4748      }
4749      EltStride >>= 1;
4750    }
4751    return V[0];
4752  }
4753  return SDValue();
4754}
4755
4756SDValue
4757X86TargetLowering::LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) const {
4758  // We support concatenate two MMX registers and place them in a MMX
4759  // register.  This is better than doing a stack convert.
4760  DebugLoc dl = Op.getDebugLoc();
4761  EVT ResVT = Op.getValueType();
4762  assert(Op.getNumOperands() == 2);
4763  assert(ResVT == MVT::v2i64 || ResVT == MVT::v4i32 ||
4764         ResVT == MVT::v8i16 || ResVT == MVT::v16i8);
4765  int Mask[2];
4766  SDValue InVec = DAG.getNode(ISD::BITCAST,dl, MVT::v1i64, Op.getOperand(0));
4767  SDValue VecOp = DAG.getNode(X86ISD::MOVQ2DQ, dl, MVT::v2i64, InVec);
4768  InVec = Op.getOperand(1);
4769  if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
4770    unsigned NumElts = ResVT.getVectorNumElements();
4771    VecOp = DAG.getNode(ISD::BITCAST, dl, ResVT, VecOp);
4772    VecOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ResVT, VecOp,
4773                       InVec.getOperand(0), DAG.getIntPtrConstant(NumElts/2+1));
4774  } else {
4775    InVec = DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, InVec);
4776    SDValue VecOp2 = DAG.getNode(X86ISD::MOVQ2DQ, dl, MVT::v2i64, InVec);
4777    Mask[0] = 0; Mask[1] = 2;
4778    VecOp = DAG.getVectorShuffle(MVT::v2i64, dl, VecOp, VecOp2, Mask);
4779  }
4780  return DAG.getNode(ISD::BITCAST, dl, ResVT, VecOp);
4781}
4782
4783// v8i16 shuffles - Prefer shuffles in the following order:
4784// 1. [all]   pshuflw, pshufhw, optional move
4785// 2. [ssse3] 1 x pshufb
4786// 3. [ssse3] 2 x pshufb + 1 x por
4787// 4. [all]   mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
4788SDValue
4789X86TargetLowering::LowerVECTOR_SHUFFLEv8i16(SDValue Op,
4790                                            SelectionDAG &DAG) const {
4791  ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
4792  SDValue V1 = SVOp->getOperand(0);
4793  SDValue V2 = SVOp->getOperand(1);
4794  DebugLoc dl = SVOp->getDebugLoc();
4795  SmallVector<int, 8> MaskVals;
4796
4797  // Determine if more than 1 of the words in each of the low and high quadwords
4798  // of the result come from the same quadword of one of the two inputs.  Undef
4799  // mask values count as coming from any quadword, for better codegen.
4800  SmallVector<unsigned, 4> LoQuad(4);
4801  SmallVector<unsigned, 4> HiQuad(4);
4802  BitVector InputQuads(4);
4803  for (unsigned i = 0; i < 8; ++i) {
4804    SmallVectorImpl<unsigned> &Quad = i < 4 ? LoQuad : HiQuad;
4805    int EltIdx = SVOp->getMaskElt(i);
4806    MaskVals.push_back(EltIdx);
4807    if (EltIdx < 0) {
4808      ++Quad[0];
4809      ++Quad[1];
4810      ++Quad[2];
4811      ++Quad[3];
4812      continue;
4813    }
4814    ++Quad[EltIdx / 4];
4815    InputQuads.set(EltIdx / 4);
4816  }
4817
4818  int BestLoQuad = -1;
4819  unsigned MaxQuad = 1;
4820  for (unsigned i = 0; i < 4; ++i) {
4821    if (LoQuad[i] > MaxQuad) {
4822      BestLoQuad = i;
4823      MaxQuad = LoQuad[i];
4824    }
4825  }
4826
4827  int BestHiQuad = -1;
4828  MaxQuad = 1;
4829  for (unsigned i = 0; i < 4; ++i) {
4830    if (HiQuad[i] > MaxQuad) {
4831      BestHiQuad = i;
4832      MaxQuad = HiQuad[i];
4833    }
4834  }
4835
4836  // For SSSE3, If all 8 words of the result come from only 1 quadword of each
4837  // of the two input vectors, shuffle them into one input vector so only a
4838  // single pshufb instruction is necessary. If There are more than 2 input
4839  // quads, disable the next transformation since it does not help SSSE3.
4840  bool V1Used = InputQuads[0] || InputQuads[1];
4841  bool V2Used = InputQuads[2] || InputQuads[3];
4842  if (Subtarget->hasSSSE3()) {
4843    if (InputQuads.count() == 2 && V1Used && V2Used) {
4844      BestLoQuad = InputQuads.find_first();
4845      BestHiQuad = InputQuads.find_next(BestLoQuad);
4846    }
4847    if (InputQuads.count() > 2) {
4848      BestLoQuad = -1;
4849      BestHiQuad = -1;
4850    }
4851  }
4852
4853  // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
4854  // the shuffle mask.  If a quad is scored as -1, that means that it contains
4855  // words from all 4 input quadwords.
4856  SDValue NewV;
4857  if (BestLoQuad >= 0 || BestHiQuad >= 0) {
4858    SmallVector<int, 8> MaskV;
4859    MaskV.push_back(BestLoQuad < 0 ? 0 : BestLoQuad);
4860    MaskV.push_back(BestHiQuad < 0 ? 1 : BestHiQuad);
4861    NewV = DAG.getVectorShuffle(MVT::v2i64, dl,
4862                  DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1),
4863                  DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2), &MaskV[0]);
4864    NewV = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, NewV);
4865
4866    // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
4867    // source words for the shuffle, to aid later transformations.
4868    bool AllWordsInNewV = true;
4869    bool InOrder[2] = { true, true };
4870    for (unsigned i = 0; i != 8; ++i) {
4871      int idx = MaskVals[i];
4872      if (idx != (int)i)
4873        InOrder[i/4] = false;
4874      if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
4875        continue;
4876      AllWordsInNewV = false;
4877      break;
4878    }
4879
4880    bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
4881    if (AllWordsInNewV) {
4882      for (int i = 0; i != 8; ++i) {
4883        int idx = MaskVals[i];
4884        if (idx < 0)
4885          continue;
4886        idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
4887        if ((idx != i) && idx < 4)
4888          pshufhw = false;
4889        if ((idx != i) && idx > 3)
4890          pshuflw = false;
4891      }
4892      V1 = NewV;
4893      V2Used = false;
4894      BestLoQuad = 0;
4895      BestHiQuad = 1;
4896    }
4897
4898    // If we've eliminated the use of V2, and the new mask is a pshuflw or
4899    // pshufhw, that's as cheap as it gets.  Return the new shuffle.
4900    if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
4901      unsigned Opc = pshufhw ? X86ISD::PSHUFHW : X86ISD::PSHUFLW;
4902      unsigned TargetMask = 0;
4903      NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV,
4904                                  DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
4905      TargetMask = pshufhw ? X86::getShufflePSHUFHWImmediate(NewV.getNode()):
4906                             X86::getShufflePSHUFLWImmediate(NewV.getNode());
4907      V1 = NewV.getOperand(0);
4908      return getTargetShuffleNode(Opc, dl, MVT::v8i16, V1, TargetMask, DAG);
4909    }
4910  }
4911
4912  // If we have SSSE3, and all words of the result are from 1 input vector,
4913  // case 2 is generated, otherwise case 3 is generated.  If no SSSE3
4914  // is present, fall back to case 4.
4915  if (Subtarget->hasSSSE3()) {
4916    SmallVector<SDValue,16> pshufbMask;
4917
4918    // If we have elements from both input vectors, set the high bit of the
4919    // shuffle mask element to zero out elements that come from V2 in the V1
4920    // mask, and elements that come from V1 in the V2 mask, so that the two
4921    // results can be OR'd together.
4922    bool TwoInputs = V1Used && V2Used;
4923    for (unsigned i = 0; i != 8; ++i) {
4924      int EltIdx = MaskVals[i] * 2;
4925      if (TwoInputs && (EltIdx >= 16)) {
4926        pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4927        pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4928        continue;
4929      }
4930      pshufbMask.push_back(DAG.getConstant(EltIdx,   MVT::i8));
4931      pshufbMask.push_back(DAG.getConstant(EltIdx+1, MVT::i8));
4932    }
4933    V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V1);
4934    V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
4935                     DAG.getNode(ISD::BUILD_VECTOR, dl,
4936                                 MVT::v16i8, &pshufbMask[0], 16));
4937    if (!TwoInputs)
4938      return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
4939
4940    // Calculate the shuffle mask for the second input, shuffle it, and
4941    // OR it with the first shuffled input.
4942    pshufbMask.clear();
4943    for (unsigned i = 0; i != 8; ++i) {
4944      int EltIdx = MaskVals[i] * 2;
4945      if (EltIdx < 16) {
4946        pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4947        pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4948        continue;
4949      }
4950      pshufbMask.push_back(DAG.getConstant(EltIdx - 16, MVT::i8));
4951      pshufbMask.push_back(DAG.getConstant(EltIdx - 15, MVT::i8));
4952    }
4953    V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V2);
4954    V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
4955                     DAG.getNode(ISD::BUILD_VECTOR, dl,
4956                                 MVT::v16i8, &pshufbMask[0], 16));
4957    V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
4958    return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
4959  }
4960
4961  // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
4962  // and update MaskVals with new element order.
4963  BitVector InOrder(8);
4964  if (BestLoQuad >= 0) {
4965    SmallVector<int, 8> MaskV;
4966    for (int i = 0; i != 4; ++i) {
4967      int idx = MaskVals[i];
4968      if (idx < 0) {
4969        MaskV.push_back(-1);
4970        InOrder.set(i);
4971      } else if ((idx / 4) == BestLoQuad) {
4972        MaskV.push_back(idx & 3);
4973        InOrder.set(i);
4974      } else {
4975        MaskV.push_back(-1);
4976      }
4977    }
4978    for (unsigned i = 4; i != 8; ++i)
4979      MaskV.push_back(i);
4980    NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
4981                                &MaskV[0]);
4982
4983    if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3())
4984      NewV = getTargetShuffleNode(X86ISD::PSHUFLW, dl, MVT::v8i16,
4985                               NewV.getOperand(0),
4986                               X86::getShufflePSHUFLWImmediate(NewV.getNode()),
4987                               DAG);
4988  }
4989
4990  // If BestHi >= 0, generate a pshufhw to put the high elements in order,
4991  // and update MaskVals with the new element order.
4992  if (BestHiQuad >= 0) {
4993    SmallVector<int, 8> MaskV;
4994    for (unsigned i = 0; i != 4; ++i)
4995      MaskV.push_back(i);
4996    for (unsigned i = 4; i != 8; ++i) {
4997      int idx = MaskVals[i];
4998      if (idx < 0) {
4999        MaskV.push_back(-1);
5000        InOrder.set(i);
5001      } else if ((idx / 4) == BestHiQuad) {
5002        MaskV.push_back((idx & 3) + 4);
5003        InOrder.set(i);
5004      } else {
5005        MaskV.push_back(-1);
5006      }
5007    }
5008    NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
5009                                &MaskV[0]);
5010
5011    if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3())
5012      NewV = getTargetShuffleNode(X86ISD::PSHUFHW, dl, MVT::v8i16,
5013                              NewV.getOperand(0),
5014                              X86::getShufflePSHUFHWImmediate(NewV.getNode()),
5015                              DAG);
5016  }
5017
5018  // In case BestHi & BestLo were both -1, which means each quadword has a word
5019  // from each of the four input quadwords, calculate the InOrder bitvector now
5020  // before falling through to the insert/extract cleanup.
5021  if (BestLoQuad == -1 && BestHiQuad == -1) {
5022    NewV = V1;
5023    for (int i = 0; i != 8; ++i)
5024      if (MaskVals[i] < 0 || MaskVals[i] == i)
5025        InOrder.set(i);
5026  }
5027
5028  // The other elements are put in the right place using pextrw and pinsrw.
5029  for (unsigned i = 0; i != 8; ++i) {
5030    if (InOrder[i])
5031      continue;
5032    int EltIdx = MaskVals[i];
5033    if (EltIdx < 0)
5034      continue;
5035    SDValue ExtOp = (EltIdx < 8)
5036    ? DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
5037                  DAG.getIntPtrConstant(EltIdx))
5038    : DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
5039                  DAG.getIntPtrConstant(EltIdx - 8));
5040    NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
5041                       DAG.getIntPtrConstant(i));
5042  }
5043  return NewV;
5044}
5045
5046// v16i8 shuffles - Prefer shuffles in the following order:
5047// 1. [ssse3] 1 x pshufb
5048// 2. [ssse3] 2 x pshufb + 1 x por
5049// 3. [all]   v8i16 shuffle + N x pextrw + rotate + pinsrw
5050static
5051SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
5052                                 SelectionDAG &DAG,
5053                                 const X86TargetLowering &TLI) {
5054  SDValue V1 = SVOp->getOperand(0);
5055  SDValue V2 = SVOp->getOperand(1);
5056  DebugLoc dl = SVOp->getDebugLoc();
5057  SmallVector<int, 16> MaskVals;
5058  SVOp->getMask(MaskVals);
5059
5060  // If we have SSSE3, case 1 is generated when all result bytes come from
5061  // one of  the inputs.  Otherwise, case 2 is generated.  If no SSSE3 is
5062  // present, fall back to case 3.
5063  // FIXME: kill V2Only once shuffles are canonizalized by getNode.
5064  bool V1Only = true;
5065  bool V2Only = true;
5066  for (unsigned i = 0; i < 16; ++i) {
5067    int EltIdx = MaskVals[i];
5068    if (EltIdx < 0)
5069      continue;
5070    if (EltIdx < 16)
5071      V2Only = false;
5072    else
5073      V1Only = false;
5074  }
5075
5076  // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
5077  if (TLI.getSubtarget()->hasSSSE3()) {
5078    SmallVector<SDValue,16> pshufbMask;
5079
5080    // If all result elements are from one input vector, then only translate
5081    // undef mask values to 0x80 (zero out result) in the pshufb mask.
5082    //
5083    // Otherwise, we have elements from both input vectors, and must zero out
5084    // elements that come from V2 in the first mask, and V1 in the second mask
5085    // so that we can OR them together.
5086    bool TwoInputs = !(V1Only || V2Only);
5087    for (unsigned i = 0; i != 16; ++i) {
5088      int EltIdx = MaskVals[i];
5089      if (EltIdx < 0 || (TwoInputs && EltIdx >= 16)) {
5090        pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
5091        continue;
5092      }
5093      pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
5094    }
5095    // If all the elements are from V2, assign it to V1 and return after
5096    // building the first pshufb.
5097    if (V2Only)
5098      V1 = V2;
5099    V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
5100                     DAG.getNode(ISD::BUILD_VECTOR, dl,
5101                                 MVT::v16i8, &pshufbMask[0], 16));
5102    if (!TwoInputs)
5103      return V1;
5104
5105    // Calculate the shuffle mask for the second input, shuffle it, and
5106    // OR it with the first shuffled input.
5107    pshufbMask.clear();
5108    for (unsigned i = 0; i != 16; ++i) {
5109      int EltIdx = MaskVals[i];
5110      if (EltIdx < 16) {
5111        pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
5112        continue;
5113      }
5114      pshufbMask.push_back(DAG.getConstant(EltIdx - 16, MVT::i8));
5115    }
5116    V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
5117                     DAG.getNode(ISD::BUILD_VECTOR, dl,
5118                                 MVT::v16i8, &pshufbMask[0], 16));
5119    return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
5120  }
5121
5122  // No SSSE3 - Calculate in place words and then fix all out of place words
5123  // With 0-16 extracts & inserts.  Worst case is 16 bytes out of order from
5124  // the 16 different words that comprise the two doublequadword input vectors.
5125  V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5126  V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
5127  SDValue NewV = V2Only ? V2 : V1;
5128  for (int i = 0; i != 8; ++i) {
5129    int Elt0 = MaskVals[i*2];
5130    int Elt1 = MaskVals[i*2+1];
5131
5132    // This word of the result is all undef, skip it.
5133    if (Elt0 < 0 && Elt1 < 0)
5134      continue;
5135
5136    // This word of the result is already in the correct place, skip it.
5137    if (V1Only && (Elt0 == i*2) && (Elt1 == i*2+1))
5138      continue;
5139    if (V2Only && (Elt0 == i*2+16) && (Elt1 == i*2+17))
5140      continue;
5141
5142    SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
5143    SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
5144    SDValue InsElt;
5145
5146    // If Elt0 and Elt1 are defined, are consecutive, and can be load
5147    // using a single extract together, load it and store it.
5148    if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
5149      InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
5150                           DAG.getIntPtrConstant(Elt1 / 2));
5151      NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
5152                        DAG.getIntPtrConstant(i));
5153      continue;
5154    }
5155
5156    // If Elt1 is defined, extract it from the appropriate source.  If the
5157    // source byte is not also odd, shift the extracted word left 8 bits
5158    // otherwise clear the bottom 8 bits if we need to do an or.
5159    if (Elt1 >= 0) {
5160      InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
5161                           DAG.getIntPtrConstant(Elt1 / 2));
5162      if ((Elt1 & 1) == 0)
5163        InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
5164                             DAG.getConstant(8,
5165                                  TLI.getShiftAmountTy(InsElt.getValueType())));
5166      else if (Elt0 >= 0)
5167        InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
5168                             DAG.getConstant(0xFF00, MVT::i16));
5169    }
5170    // If Elt0 is defined, extract it from the appropriate source.  If the
5171    // source byte is not also even, shift the extracted word right 8 bits. If
5172    // Elt1 was also defined, OR the extracted values together before
5173    // inserting them in the result.
5174    if (Elt0 >= 0) {
5175      SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
5176                                    Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
5177      if ((Elt0 & 1) != 0)
5178        InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
5179                              DAG.getConstant(8,
5180                                 TLI.getShiftAmountTy(InsElt0.getValueType())));
5181      else if (Elt1 >= 0)
5182        InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
5183                             DAG.getConstant(0x00FF, MVT::i16));
5184      InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
5185                         : InsElt0;
5186    }
5187    NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
5188                       DAG.getIntPtrConstant(i));
5189  }
5190  return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, NewV);
5191}
5192
5193/// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
5194/// ones, or rewriting v4i32 / v4f32 as 2 wide ones if possible. This can be
5195/// done when every pair / quad of shuffle mask elements point to elements in
5196/// the right sequence. e.g.
5197/// vector_shuffle X, Y, <2, 3, | 10, 11, | 0, 1, | 14, 15>
5198static
5199SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
5200                                 SelectionDAG &DAG, DebugLoc dl) {
5201  EVT VT = SVOp->getValueType(0);
5202  SDValue V1 = SVOp->getOperand(0);
5203  SDValue V2 = SVOp->getOperand(1);
5204  unsigned NumElems = VT.getVectorNumElements();
5205  unsigned NewWidth = (NumElems == 4) ? 2 : 4;
5206  EVT NewVT;
5207  switch (VT.getSimpleVT().SimpleTy) {
5208  default: assert(false && "Unexpected!");
5209  case MVT::v4f32: NewVT = MVT::v2f64; break;
5210  case MVT::v4i32: NewVT = MVT::v2i64; break;
5211  case MVT::v8i16: NewVT = MVT::v4i32; break;
5212  case MVT::v16i8: NewVT = MVT::v4i32; break;
5213  }
5214
5215  int Scale = NumElems / NewWidth;
5216  SmallVector<int, 8> MaskVec;
5217  for (unsigned i = 0; i < NumElems; i += Scale) {
5218    int StartIdx = -1;
5219    for (int j = 0; j < Scale; ++j) {
5220      int EltIdx = SVOp->getMaskElt(i+j);
5221      if (EltIdx < 0)
5222        continue;
5223      if (StartIdx == -1)
5224        StartIdx = EltIdx - (EltIdx % Scale);
5225      if (EltIdx != StartIdx + j)
5226        return SDValue();
5227    }
5228    if (StartIdx == -1)
5229      MaskVec.push_back(-1);
5230    else
5231      MaskVec.push_back(StartIdx / Scale);
5232  }
5233
5234  V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, V1);
5235  V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, V2);
5236  return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
5237}
5238
5239/// getVZextMovL - Return a zero-extending vector move low node.
5240///
5241static SDValue getVZextMovL(EVT VT, EVT OpVT,
5242                            SDValue SrcOp, SelectionDAG &DAG,
5243                            const X86Subtarget *Subtarget, DebugLoc dl) {
5244  if (VT == MVT::v2f64 || VT == MVT::v4f32) {
5245    LoadSDNode *LD = NULL;
5246    if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
5247      LD = dyn_cast<LoadSDNode>(SrcOp);
5248    if (!LD) {
5249      // movssrr and movsdrr do not clear top bits. Try to use movd, movq
5250      // instead.
5251      MVT ExtVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
5252      if ((ExtVT != MVT::i64 || Subtarget->is64Bit()) &&
5253          SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
5254          SrcOp.getOperand(0).getOpcode() == ISD::BITCAST &&
5255          SrcOp.getOperand(0).getOperand(0).getValueType() == ExtVT) {
5256        // PR2108
5257        OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
5258        return DAG.getNode(ISD::BITCAST, dl, VT,
5259                           DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
5260                                       DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
5261                                                   OpVT,
5262                                                   SrcOp.getOperand(0)
5263                                                          .getOperand(0))));
5264      }
5265    }
5266  }
5267
5268  return DAG.getNode(ISD::BITCAST, dl, VT,
5269                     DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
5270                                 DAG.getNode(ISD::BITCAST, dl,
5271                                             OpVT, SrcOp)));
5272}
5273
5274/// LowerVECTOR_SHUFFLE_4wide - Handle all 4 wide cases with a number of
5275/// shuffles.
5276static SDValue
5277LowerVECTOR_SHUFFLE_4wide(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
5278  SDValue V1 = SVOp->getOperand(0);
5279  SDValue V2 = SVOp->getOperand(1);
5280  DebugLoc dl = SVOp->getDebugLoc();
5281  EVT VT = SVOp->getValueType(0);
5282
5283  SmallVector<std::pair<int, int>, 8> Locs;
5284  Locs.resize(4);
5285  SmallVector<int, 8> Mask1(4U, -1);
5286  SmallVector<int, 8> PermMask;
5287  SVOp->getMask(PermMask);
5288
5289  unsigned NumHi = 0;
5290  unsigned NumLo = 0;
5291  for (unsigned i = 0; i != 4; ++i) {
5292    int Idx = PermMask[i];
5293    if (Idx < 0) {
5294      Locs[i] = std::make_pair(-1, -1);
5295    } else {
5296      assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
5297      if (Idx < 4) {
5298        Locs[i] = std::make_pair(0, NumLo);
5299        Mask1[NumLo] = Idx;
5300        NumLo++;
5301      } else {
5302        Locs[i] = std::make_pair(1, NumHi);
5303        if (2+NumHi < 4)
5304          Mask1[2+NumHi] = Idx;
5305        NumHi++;
5306      }
5307    }
5308  }
5309
5310  if (NumLo <= 2 && NumHi <= 2) {
5311    // If no more than two elements come from either vector. This can be
5312    // implemented with two shuffles. First shuffle gather the elements.
5313    // The second shuffle, which takes the first shuffle as both of its
5314    // vector operands, put the elements into the right order.
5315    V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
5316
5317    SmallVector<int, 8> Mask2(4U, -1);
5318
5319    for (unsigned i = 0; i != 4; ++i) {
5320      if (Locs[i].first == -1)
5321        continue;
5322      else {
5323        unsigned Idx = (i < 2) ? 0 : 4;
5324        Idx += Locs[i].first * 2 + Locs[i].second;
5325        Mask2[i] = Idx;
5326      }
5327    }
5328
5329    return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
5330  } else if (NumLo == 3 || NumHi == 3) {
5331    // Otherwise, we must have three elements from one vector, call it X, and
5332    // one element from the other, call it Y.  First, use a shufps to build an
5333    // intermediate vector with the one element from Y and the element from X
5334    // that will be in the same half in the final destination (the indexes don't
5335    // matter). Then, use a shufps to build the final vector, taking the half
5336    // containing the element from Y from the intermediate, and the other half
5337    // from X.
5338    if (NumHi == 3) {
5339      // Normalize it so the 3 elements come from V1.
5340      CommuteVectorShuffleMask(PermMask, VT);
5341      std::swap(V1, V2);
5342    }
5343
5344    // Find the element from V2.
5345    unsigned HiIndex;
5346    for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
5347      int Val = PermMask[HiIndex];
5348      if (Val < 0)
5349        continue;
5350      if (Val >= 4)
5351        break;
5352    }
5353
5354    Mask1[0] = PermMask[HiIndex];
5355    Mask1[1] = -1;
5356    Mask1[2] = PermMask[HiIndex^1];
5357    Mask1[3] = -1;
5358    V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
5359
5360    if (HiIndex >= 2) {
5361      Mask1[0] = PermMask[0];
5362      Mask1[1] = PermMask[1];
5363      Mask1[2] = HiIndex & 1 ? 6 : 4;
5364      Mask1[3] = HiIndex & 1 ? 4 : 6;
5365      return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
5366    } else {
5367      Mask1[0] = HiIndex & 1 ? 2 : 0;
5368      Mask1[1] = HiIndex & 1 ? 0 : 2;
5369      Mask1[2] = PermMask[2];
5370      Mask1[3] = PermMask[3];
5371      if (Mask1[2] >= 0)
5372        Mask1[2] += 4;
5373      if (Mask1[3] >= 0)
5374        Mask1[3] += 4;
5375      return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
5376    }
5377  }
5378
5379  // Break it into (shuffle shuffle_hi, shuffle_lo).
5380  Locs.clear();
5381  Locs.resize(4);
5382  SmallVector<int,8> LoMask(4U, -1);
5383  SmallVector<int,8> HiMask(4U, -1);
5384
5385  SmallVector<int,8> *MaskPtr = &LoMask;
5386  unsigned MaskIdx = 0;
5387  unsigned LoIdx = 0;
5388  unsigned HiIdx = 2;
5389  for (unsigned i = 0; i != 4; ++i) {
5390    if (i == 2) {
5391      MaskPtr = &HiMask;
5392      MaskIdx = 1;
5393      LoIdx = 0;
5394      HiIdx = 2;
5395    }
5396    int Idx = PermMask[i];
5397    if (Idx < 0) {
5398      Locs[i] = std::make_pair(-1, -1);
5399    } else if (Idx < 4) {
5400      Locs[i] = std::make_pair(MaskIdx, LoIdx);
5401      (*MaskPtr)[LoIdx] = Idx;
5402      LoIdx++;
5403    } else {
5404      Locs[i] = std::make_pair(MaskIdx, HiIdx);
5405      (*MaskPtr)[HiIdx] = Idx;
5406      HiIdx++;
5407    }
5408  }
5409
5410  SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
5411  SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
5412  SmallVector<int, 8> MaskOps;
5413  for (unsigned i = 0; i != 4; ++i) {
5414    if (Locs[i].first == -1) {
5415      MaskOps.push_back(-1);
5416    } else {
5417      unsigned Idx = Locs[i].first * 4 + Locs[i].second;
5418      MaskOps.push_back(Idx);
5419    }
5420  }
5421  return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
5422}
5423
5424static bool MayFoldVectorLoad(SDValue V) {
5425  if (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
5426    V = V.getOperand(0);
5427  if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
5428    V = V.getOperand(0);
5429  if (MayFoldLoad(V))
5430    return true;
5431  return false;
5432}
5433
5434// FIXME: the version above should always be used. Since there's
5435// a bug where several vector shuffles can't be folded because the
5436// DAG is not updated during lowering and a node claims to have two
5437// uses while it only has one, use this version, and let isel match
5438// another instruction if the load really happens to have more than
5439// one use. Remove this version after this bug get fixed.
5440// rdar://8434668, PR8156
5441static bool RelaxedMayFoldVectorLoad(SDValue V) {
5442  if (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
5443    V = V.getOperand(0);
5444  if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
5445    V = V.getOperand(0);
5446  if (ISD::isNormalLoad(V.getNode()))
5447    return true;
5448  return false;
5449}
5450
5451/// CanFoldShuffleIntoVExtract - Check if the current shuffle is used by
5452/// a vector extract, and if both can be later optimized into a single load.
5453/// This is done in visitEXTRACT_VECTOR_ELT and the conditions are checked
5454/// here because otherwise a target specific shuffle node is going to be
5455/// emitted for this shuffle, and the optimization not done.
5456/// FIXME: This is probably not the best approach, but fix the problem
5457/// until the right path is decided.
5458static
5459bool CanXFormVExtractWithShuffleIntoLoad(SDValue V, SelectionDAG &DAG,
5460                                         const TargetLowering &TLI) {
5461  EVT VT = V.getValueType();
5462  ShuffleVectorSDNode *SVOp = dyn_cast<ShuffleVectorSDNode>(V);
5463
5464  // Be sure that the vector shuffle is present in a pattern like this:
5465  // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), c) -> (f32 load $addr)
5466  if (!V.hasOneUse())
5467    return false;
5468
5469  SDNode *N = *V.getNode()->use_begin();
5470  if (N->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
5471    return false;
5472
5473  SDValue EltNo = N->getOperand(1);
5474  if (!isa<ConstantSDNode>(EltNo))
5475    return false;
5476
5477  // If the bit convert changed the number of elements, it is unsafe
5478  // to examine the mask.
5479  bool HasShuffleIntoBitcast = false;
5480  if (V.getOpcode() == ISD::BITCAST) {
5481    EVT SrcVT = V.getOperand(0).getValueType();
5482    if (SrcVT.getVectorNumElements() != VT.getVectorNumElements())
5483      return false;
5484    V = V.getOperand(0);
5485    HasShuffleIntoBitcast = true;
5486  }
5487
5488  // Select the input vector, guarding against out of range extract vector.
5489  unsigned NumElems = VT.getVectorNumElements();
5490  unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
5491  int Idx = (Elt > NumElems) ? -1 : SVOp->getMaskElt(Elt);
5492  V = (Idx < (int)NumElems) ? V.getOperand(0) : V.getOperand(1);
5493
5494  // Skip one more bit_convert if necessary
5495  if (V.getOpcode() == ISD::BITCAST)
5496    V = V.getOperand(0);
5497
5498  if (ISD::isNormalLoad(V.getNode())) {
5499    // Is the original load suitable?
5500    LoadSDNode *LN0 = cast<LoadSDNode>(V);
5501
5502    // FIXME: avoid the multi-use bug that is preventing lots of
5503    // of foldings to be detected, this is still wrong of course, but
5504    // give the temporary desired behavior, and if it happens that
5505    // the load has real more uses, during isel it will not fold, and
5506    // will generate poor code.
5507    if (!LN0 || LN0->isVolatile()) // || !LN0->hasOneUse()
5508      return false;
5509
5510    if (!HasShuffleIntoBitcast)
5511      return true;
5512
5513    // If there's a bitcast before the shuffle, check if the load type and
5514    // alignment is valid.
5515    unsigned Align = LN0->getAlignment();
5516    unsigned NewAlign =
5517      TLI.getTargetData()->getABITypeAlignment(
5518                                    VT.getTypeForEVT(*DAG.getContext()));
5519
5520    if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VT))
5521      return false;
5522  }
5523
5524  return true;
5525}
5526
5527static
5528SDValue getMOVDDup(SDValue &Op, DebugLoc &dl, SDValue V1, SelectionDAG &DAG) {
5529  EVT VT = Op.getValueType();
5530
5531  // Canonizalize to v2f64.
5532  V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
5533  return DAG.getNode(ISD::BITCAST, dl, VT,
5534                     getTargetShuffleNode(X86ISD::MOVDDUP, dl, MVT::v2f64,
5535                                          V1, DAG));
5536}
5537
5538static
5539SDValue getMOVLowToHigh(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG,
5540                        bool HasSSE2) {
5541  SDValue V1 = Op.getOperand(0);
5542  SDValue V2 = Op.getOperand(1);
5543  EVT VT = Op.getValueType();
5544
5545  assert(VT != MVT::v2i64 && "unsupported shuffle type");
5546
5547  if (HasSSE2 && VT == MVT::v2f64)
5548    return getTargetShuffleNode(X86ISD::MOVLHPD, dl, VT, V1, V2, DAG);
5549
5550  // v4f32 or v4i32
5551  return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V2, DAG);
5552}
5553
5554static
5555SDValue getMOVHighToLow(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG) {
5556  SDValue V1 = Op.getOperand(0);
5557  SDValue V2 = Op.getOperand(1);
5558  EVT VT = Op.getValueType();
5559
5560  assert((VT == MVT::v4i32 || VT == MVT::v4f32) &&
5561         "unsupported shuffle type");
5562
5563  if (V2.getOpcode() == ISD::UNDEF)
5564    V2 = V1;
5565
5566  // v4i32 or v4f32
5567  return getTargetShuffleNode(X86ISD::MOVHLPS, dl, VT, V1, V2, DAG);
5568}
5569
5570static
5571SDValue getMOVLP(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG, bool HasSSE2) {
5572  SDValue V1 = Op.getOperand(0);
5573  SDValue V2 = Op.getOperand(1);
5574  EVT VT = Op.getValueType();
5575  unsigned NumElems = VT.getVectorNumElements();
5576
5577  // Use MOVLPS and MOVLPD in case V1 or V2 are loads. During isel, the second
5578  // operand of these instructions is only memory, so check if there's a
5579  // potencial load folding here, otherwise use SHUFPS or MOVSD to match the
5580  // same masks.
5581  bool CanFoldLoad = false;
5582
5583  // Trivial case, when V2 comes from a load.
5584  if (MayFoldVectorLoad(V2))
5585    CanFoldLoad = true;
5586
5587  // When V1 is a load, it can be folded later into a store in isel, example:
5588  //  (store (v4f32 (X86Movlps (load addr:$src1), VR128:$src2)), addr:$src1)
5589  //    turns into:
5590  //  (MOVLPSmr addr:$src1, VR128:$src2)
5591  // So, recognize this potential and also use MOVLPS or MOVLPD
5592  if (MayFoldVectorLoad(V1) && MayFoldIntoStore(Op))
5593    CanFoldLoad = true;
5594
5595  // Both of them can't be memory operations though.
5596  if (MayFoldVectorLoad(V1) && MayFoldVectorLoad(V2))
5597    CanFoldLoad = false;
5598
5599  if (CanFoldLoad) {
5600    if (HasSSE2 && NumElems == 2)
5601      return getTargetShuffleNode(X86ISD::MOVLPD, dl, VT, V1, V2, DAG);
5602
5603    if (NumElems == 4)
5604      return getTargetShuffleNode(X86ISD::MOVLPS, dl, VT, V1, V2, DAG);
5605  }
5606
5607  ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5608  // movl and movlp will both match v2i64, but v2i64 is never matched by
5609  // movl earlier because we make it strict to avoid messing with the movlp load
5610  // folding logic (see the code above getMOVLP call). Match it here then,
5611  // this is horrible, but will stay like this until we move all shuffle
5612  // matching to x86 specific nodes. Note that for the 1st condition all
5613  // types are matched with movsd.
5614  if ((HasSSE2 && NumElems == 2) || !X86::isMOVLMask(SVOp))
5615    return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
5616  else if (HasSSE2)
5617    return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
5618
5619
5620  assert(VT != MVT::v4i32 && "unsupported shuffle type");
5621
5622  // Invert the operand order and use SHUFPS to match it.
5623  return getTargetShuffleNode(X86ISD::SHUFPS, dl, VT, V2, V1,
5624                              X86::getShuffleSHUFImmediate(SVOp), DAG);
5625}
5626
5627static inline unsigned getUNPCKLOpcode(EVT VT, const X86Subtarget *Subtarget) {
5628  switch(VT.getSimpleVT().SimpleTy) {
5629  case MVT::v4i32: return X86ISD::PUNPCKLDQ;
5630  case MVT::v2i64: return X86ISD::PUNPCKLQDQ;
5631  case MVT::v4f32:
5632    return Subtarget->hasAVX() ? X86ISD::VUNPCKLPS : X86ISD::UNPCKLPS;
5633  case MVT::v2f64:
5634    return Subtarget->hasAVX() ? X86ISD::VUNPCKLPD : X86ISD::UNPCKLPD;
5635  case MVT::v8f32: return X86ISD::VUNPCKLPSY;
5636  case MVT::v4f64: return X86ISD::VUNPCKLPDY;
5637  case MVT::v16i8: return X86ISD::PUNPCKLBW;
5638  case MVT::v8i16: return X86ISD::PUNPCKLWD;
5639  default:
5640    llvm_unreachable("Unknown type for unpckl");
5641  }
5642  return 0;
5643}
5644
5645static inline unsigned getUNPCKHOpcode(EVT VT) {
5646  switch(VT.getSimpleVT().SimpleTy) {
5647  case MVT::v4i32: return X86ISD::PUNPCKHDQ;
5648  case MVT::v2i64: return X86ISD::PUNPCKHQDQ;
5649  case MVT::v4f32: return X86ISD::UNPCKHPS;
5650  case MVT::v2f64: return X86ISD::UNPCKHPD;
5651  case MVT::v16i8: return X86ISD::PUNPCKHBW;
5652  case MVT::v8i16: return X86ISD::PUNPCKHWD;
5653  default:
5654    llvm_unreachable("Unknown type for unpckh");
5655  }
5656  return 0;
5657}
5658
5659static
5660SDValue NormalizeVectorShuffle(SDValue Op, SelectionDAG &DAG,
5661                               const TargetLowering &TLI,
5662                               const X86Subtarget *Subtarget) {
5663  ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5664  EVT VT = Op.getValueType();
5665  DebugLoc dl = Op.getDebugLoc();
5666  SDValue V1 = Op.getOperand(0);
5667  SDValue V2 = Op.getOperand(1);
5668
5669  if (isZeroShuffle(SVOp))
5670    return getZeroVector(VT, Subtarget->hasSSE2(), DAG, dl);
5671
5672  // Handle splat operations
5673  if (SVOp->isSplat()) {
5674    // Special case, this is the only place now where it's
5675    // allowed to return a vector_shuffle operation without
5676    // using a target specific node, because *hopefully* it
5677    // will be optimized away by the dag combiner.
5678    if (VT.getVectorNumElements() <= 4 &&
5679        CanXFormVExtractWithShuffleIntoLoad(Op, DAG, TLI))
5680      return Op;
5681
5682    // Handle splats by matching through known masks
5683    if (VT.getVectorNumElements() <= 4)
5684      return SDValue();
5685
5686    // Canonicalize all of the remaining to v4f32.
5687    return PromoteSplat(SVOp, DAG);
5688  }
5689
5690  // If the shuffle can be profitably rewritten as a narrower shuffle, then
5691  // do it!
5692  if (VT == MVT::v8i16 || VT == MVT::v16i8) {
5693    SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
5694    if (NewOp.getNode())
5695      return DAG.getNode(ISD::BITCAST, dl, VT, NewOp);
5696  } else if ((VT == MVT::v4i32 || (VT == MVT::v4f32 && Subtarget->hasSSE2()))) {
5697    // FIXME: Figure out a cleaner way to do this.
5698    // Try to make use of movq to zero out the top part.
5699    if (ISD::isBuildVectorAllZeros(V2.getNode())) {
5700      SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
5701      if (NewOp.getNode()) {
5702        if (isCommutedMOVL(cast<ShuffleVectorSDNode>(NewOp), true, false))
5703          return getVZextMovL(VT, NewOp.getValueType(), NewOp.getOperand(0),
5704                              DAG, Subtarget, dl);
5705      }
5706    } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
5707      SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
5708      if (NewOp.getNode() && X86::isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)))
5709        return getVZextMovL(VT, NewOp.getValueType(), NewOp.getOperand(1),
5710                            DAG, Subtarget, dl);
5711    }
5712  }
5713  return SDValue();
5714}
5715
5716SDValue
5717X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) const {
5718  ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5719  SDValue V1 = Op.getOperand(0);
5720  SDValue V2 = Op.getOperand(1);
5721  EVT VT = Op.getValueType();
5722  DebugLoc dl = Op.getDebugLoc();
5723  unsigned NumElems = VT.getVectorNumElements();
5724  bool isMMX = VT.getSizeInBits() == 64;
5725  bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
5726  bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
5727  bool V1IsSplat = false;
5728  bool V2IsSplat = false;
5729  bool HasSSE2 = Subtarget->hasSSE2() || Subtarget->hasAVX();
5730  bool HasSSE3 = Subtarget->hasSSE3() || Subtarget->hasAVX();
5731  bool HasSSSE3 = Subtarget->hasSSSE3() || Subtarget->hasAVX();
5732  MachineFunction &MF = DAG.getMachineFunction();
5733  bool OptForSize = MF.getFunction()->hasFnAttr(Attribute::OptimizeForSize);
5734
5735  // Shuffle operations on MMX not supported.
5736  if (isMMX)
5737    return Op;
5738
5739  // Vector shuffle lowering takes 3 steps:
5740  //
5741  // 1) Normalize the input vectors. Here splats, zeroed vectors, profitable
5742  //    narrowing and commutation of operands should be handled.
5743  // 2) Matching of shuffles with known shuffle masks to x86 target specific
5744  //    shuffle nodes.
5745  // 3) Rewriting of unmatched masks into new generic shuffle operations,
5746  //    so the shuffle can be broken into other shuffles and the legalizer can
5747  //    try the lowering again.
5748  //
5749  // The general ideia is that no vector_shuffle operation should be left to
5750  // be matched during isel, all of them must be converted to a target specific
5751  // node here.
5752
5753  // Normalize the input vectors. Here splats, zeroed vectors, profitable
5754  // narrowing and commutation of operands should be handled. The actual code
5755  // doesn't include all of those, work in progress...
5756  SDValue NewOp = NormalizeVectorShuffle(Op, DAG, *this, Subtarget);
5757  if (NewOp.getNode())
5758    return NewOp;
5759
5760  // NOTE: isPSHUFDMask can also match both masks below (unpckl_undef and
5761  // unpckh_undef). Only use pshufd if speed is more important than size.
5762  if (OptForSize && X86::isUNPCKL_v_undef_Mask(SVOp))
5763    if (VT != MVT::v2i64 && VT != MVT::v2f64)
5764      return getTargetShuffleNode(getUNPCKLOpcode(VT, getSubtarget()), dl, VT, V1, V1, DAG);
5765  if (OptForSize && X86::isUNPCKH_v_undef_Mask(SVOp))
5766    if (VT != MVT::v2i64 && VT != MVT::v2f64)
5767      return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V1, V1, DAG);
5768
5769  if (X86::isMOVDDUPMask(SVOp) && HasSSE3 && V2IsUndef &&
5770      RelaxedMayFoldVectorLoad(V1))
5771    return getMOVDDup(Op, dl, V1, DAG);
5772
5773  if (X86::isMOVHLPS_v_undef_Mask(SVOp))
5774    return getMOVHighToLow(Op, dl, DAG);
5775
5776  // Use to match splats
5777  if (HasSSE2 && X86::isUNPCKHMask(SVOp) && V2IsUndef &&
5778      (VT == MVT::v2f64 || VT == MVT::v2i64))
5779    return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V1, V1, DAG);
5780
5781  if (X86::isPSHUFDMask(SVOp)) {
5782    // The actual implementation will match the mask in the if above and then
5783    // during isel it can match several different instructions, not only pshufd
5784    // as its name says, sad but true, emulate the behavior for now...
5785    if (X86::isMOVDDUPMask(SVOp) && ((VT == MVT::v4f32 || VT == MVT::v2i64)))
5786        return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V1, DAG);
5787
5788    unsigned TargetMask = X86::getShuffleSHUFImmediate(SVOp);
5789
5790    if (HasSSE2 && (VT == MVT::v4f32 || VT == MVT::v4i32))
5791      return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1, TargetMask, DAG);
5792
5793    if (HasSSE2 && (VT == MVT::v2i64 || VT == MVT::v2f64))
5794      return getTargetShuffleNode(X86ISD::SHUFPD, dl, VT, V1, V1,
5795                                  TargetMask, DAG);
5796
5797    if (VT == MVT::v4f32)
5798      return getTargetShuffleNode(X86ISD::SHUFPS, dl, VT, V1, V1,
5799                                  TargetMask, DAG);
5800  }
5801
5802  // Check if this can be converted into a logical shift.
5803  bool isLeft = false;
5804  unsigned ShAmt = 0;
5805  SDValue ShVal;
5806  bool isShift = getSubtarget()->hasSSE2() &&
5807    isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
5808  if (isShift && ShVal.hasOneUse()) {
5809    // If the shifted value has multiple uses, it may be cheaper to use
5810    // v_set0 + movlhps or movhlps, etc.
5811    EVT EltVT = VT.getVectorElementType();
5812    ShAmt *= EltVT.getSizeInBits();
5813    return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
5814  }
5815
5816  if (X86::isMOVLMask(SVOp)) {
5817    if (V1IsUndef)
5818      return V2;
5819    if (ISD::isBuildVectorAllZeros(V1.getNode()))
5820      return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
5821    if (!X86::isMOVLPMask(SVOp)) {
5822      if (HasSSE2 && (VT == MVT::v2i64 || VT == MVT::v2f64))
5823        return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
5824
5825      if (VT == MVT::v4i32 || VT == MVT::v4f32)
5826        return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
5827    }
5828  }
5829
5830  // FIXME: fold these into legal mask.
5831  if (X86::isMOVLHPSMask(SVOp) && !X86::isUNPCKLMask(SVOp))
5832    return getMOVLowToHigh(Op, dl, DAG, HasSSE2);
5833
5834  if (X86::isMOVHLPSMask(SVOp))
5835    return getMOVHighToLow(Op, dl, DAG);
5836
5837  if (X86::isMOVSHDUPMask(SVOp) && HasSSE3 && V2IsUndef && NumElems == 4)
5838    return getTargetShuffleNode(X86ISD::MOVSHDUP, dl, VT, V1, DAG);
5839
5840  if (X86::isMOVSLDUPMask(SVOp) && HasSSE3 && V2IsUndef && NumElems == 4)
5841    return getTargetShuffleNode(X86ISD::MOVSLDUP, dl, VT, V1, DAG);
5842
5843  if (X86::isMOVLPMask(SVOp))
5844    return getMOVLP(Op, dl, DAG, HasSSE2);
5845
5846  if (ShouldXformToMOVHLPS(SVOp) ||
5847      ShouldXformToMOVLP(V1.getNode(), V2.getNode(), SVOp))
5848    return CommuteVectorShuffle(SVOp, DAG);
5849
5850  if (isShift) {
5851    // No better options. Use a vshl / vsrl.
5852    EVT EltVT = VT.getVectorElementType();
5853    ShAmt *= EltVT.getSizeInBits();
5854    return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
5855  }
5856
5857  bool Commuted = false;
5858  // FIXME: This should also accept a bitcast of a splat?  Be careful, not
5859  // 1,1,1,1 -> v8i16 though.
5860  V1IsSplat = isSplatVector(V1.getNode());
5861  V2IsSplat = isSplatVector(V2.getNode());
5862
5863  // Canonicalize the splat or undef, if present, to be on the RHS.
5864  if ((V1IsSplat || V1IsUndef) && !(V2IsSplat || V2IsUndef)) {
5865    Op = CommuteVectorShuffle(SVOp, DAG);
5866    SVOp = cast<ShuffleVectorSDNode>(Op);
5867    V1 = SVOp->getOperand(0);
5868    V2 = SVOp->getOperand(1);
5869    std::swap(V1IsSplat, V2IsSplat);
5870    std::swap(V1IsUndef, V2IsUndef);
5871    Commuted = true;
5872  }
5873
5874  if (isCommutedMOVL(SVOp, V2IsSplat, V2IsUndef)) {
5875    // Shuffling low element of v1 into undef, just return v1.
5876    if (V2IsUndef)
5877      return V1;
5878    // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
5879    // the instruction selector will not match, so get a canonical MOVL with
5880    // swapped operands to undo the commute.
5881    return getMOVL(DAG, dl, VT, V2, V1);
5882  }
5883
5884  if (X86::isUNPCKLMask(SVOp))
5885    return getTargetShuffleNode(getUNPCKLOpcode(VT, getSubtarget()),
5886                                dl, VT, V1, V2, DAG);
5887
5888  if (X86::isUNPCKHMask(SVOp))
5889    return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V1, V2, DAG);
5890
5891  if (V2IsSplat) {
5892    // Normalize mask so all entries that point to V2 points to its first
5893    // element then try to match unpck{h|l} again. If match, return a
5894    // new vector_shuffle with the corrected mask.
5895    SDValue NewMask = NormalizeMask(SVOp, DAG);
5896    ShuffleVectorSDNode *NSVOp = cast<ShuffleVectorSDNode>(NewMask);
5897    if (NSVOp != SVOp) {
5898      if (X86::isUNPCKLMask(NSVOp, true)) {
5899        return NewMask;
5900      } else if (X86::isUNPCKHMask(NSVOp, true)) {
5901        return NewMask;
5902      }
5903    }
5904  }
5905
5906  if (Commuted) {
5907    // Commute is back and try unpck* again.
5908    // FIXME: this seems wrong.
5909    SDValue NewOp = CommuteVectorShuffle(SVOp, DAG);
5910    ShuffleVectorSDNode *NewSVOp = cast<ShuffleVectorSDNode>(NewOp);
5911
5912    if (X86::isUNPCKLMask(NewSVOp))
5913      return getTargetShuffleNode(getUNPCKLOpcode(VT, getSubtarget()),
5914                                  dl, VT, V2, V1, DAG);
5915
5916    if (X86::isUNPCKHMask(NewSVOp))
5917      return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V2, V1, DAG);
5918  }
5919
5920  // Normalize the node to match x86 shuffle ops if needed
5921  if (V2.getOpcode() != ISD::UNDEF && isCommutedSHUFP(SVOp))
5922    return CommuteVectorShuffle(SVOp, DAG);
5923
5924  // The checks below are all present in isShuffleMaskLegal, but they are
5925  // inlined here right now to enable us to directly emit target specific
5926  // nodes, and remove one by one until they don't return Op anymore.
5927  SmallVector<int, 16> M;
5928  SVOp->getMask(M);
5929
5930  if (isPALIGNRMask(M, VT, HasSSSE3))
5931    return getTargetShuffleNode(X86ISD::PALIGN, dl, VT, V1, V2,
5932                                X86::getShufflePALIGNRImmediate(SVOp),
5933                                DAG);
5934
5935  if (ShuffleVectorSDNode::isSplatMask(&M[0], VT) &&
5936      SVOp->getSplatIndex() == 0 && V2IsUndef) {
5937    if (VT == MVT::v2f64) {
5938      X86ISD::NodeType Opcode =
5939        getSubtarget()->hasAVX() ? X86ISD::VUNPCKLPD : X86ISD::UNPCKLPD;
5940      return getTargetShuffleNode(Opcode, dl, VT, V1, V1, DAG);
5941    }
5942    if (VT == MVT::v2i64)
5943      return getTargetShuffleNode(X86ISD::PUNPCKLQDQ, dl, VT, V1, V1, DAG);
5944  }
5945
5946  if (isPSHUFHWMask(M, VT))
5947    return getTargetShuffleNode(X86ISD::PSHUFHW, dl, VT, V1,
5948                                X86::getShufflePSHUFHWImmediate(SVOp),
5949                                DAG);
5950
5951  if (isPSHUFLWMask(M, VT))
5952    return getTargetShuffleNode(X86ISD::PSHUFLW, dl, VT, V1,
5953                                X86::getShufflePSHUFLWImmediate(SVOp),
5954                                DAG);
5955
5956  if (isSHUFPMask(M, VT)) {
5957    unsigned TargetMask = X86::getShuffleSHUFImmediate(SVOp);
5958    if (VT == MVT::v4f32 || VT == MVT::v4i32)
5959      return getTargetShuffleNode(X86ISD::SHUFPS, dl, VT, V1, V2,
5960                                  TargetMask, DAG);
5961    if (VT == MVT::v2f64 || VT == MVT::v2i64)
5962      return getTargetShuffleNode(X86ISD::SHUFPD, dl, VT, V1, V2,
5963                                  TargetMask, DAG);
5964  }
5965
5966  if (X86::isUNPCKL_v_undef_Mask(SVOp))
5967    if (VT != MVT::v2i64 && VT != MVT::v2f64)
5968      return getTargetShuffleNode(getUNPCKLOpcode(VT, getSubtarget()),
5969                                  dl, VT, V1, V1, DAG);
5970  if (X86::isUNPCKH_v_undef_Mask(SVOp))
5971    if (VT != MVT::v2i64 && VT != MVT::v2f64)
5972      return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V1, V1, DAG);
5973
5974  // Handle v8i16 specifically since SSE can do byte extraction and insertion.
5975  if (VT == MVT::v8i16) {
5976    SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(Op, DAG);
5977    if (NewOp.getNode())
5978      return NewOp;
5979  }
5980
5981  if (VT == MVT::v16i8) {
5982    SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, DAG, *this);
5983    if (NewOp.getNode())
5984      return NewOp;
5985  }
5986
5987  // Handle all 4 wide cases with a number of shuffles.
5988  if (NumElems == 4)
5989    return LowerVECTOR_SHUFFLE_4wide(SVOp, DAG);
5990
5991  return SDValue();
5992}
5993
5994SDValue
5995X86TargetLowering::LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op,
5996                                                SelectionDAG &DAG) const {
5997  EVT VT = Op.getValueType();
5998  DebugLoc dl = Op.getDebugLoc();
5999  if (VT.getSizeInBits() == 8) {
6000    SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
6001                                    Op.getOperand(0), Op.getOperand(1));
6002    SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
6003                                    DAG.getValueType(VT));
6004    return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
6005  } else if (VT.getSizeInBits() == 16) {
6006    unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6007    // If Idx is 0, it's cheaper to do a move instead of a pextrw.
6008    if (Idx == 0)
6009      return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
6010                         DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
6011                                     DAG.getNode(ISD::BITCAST, dl,
6012                                                 MVT::v4i32,
6013                                                 Op.getOperand(0)),
6014                                     Op.getOperand(1)));
6015    SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
6016                                    Op.getOperand(0), Op.getOperand(1));
6017    SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
6018                                    DAG.getValueType(VT));
6019    return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
6020  } else if (VT == MVT::f32) {
6021    // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
6022    // the result back to FR32 register. It's only worth matching if the
6023    // result has a single use which is a store or a bitcast to i32.  And in
6024    // the case of a store, it's not worth it if the index is a constant 0,
6025    // because a MOVSSmr can be used instead, which is smaller and faster.
6026    if (!Op.hasOneUse())
6027      return SDValue();
6028    SDNode *User = *Op.getNode()->use_begin();
6029    if ((User->getOpcode() != ISD::STORE ||
6030         (isa<ConstantSDNode>(Op.getOperand(1)) &&
6031          cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
6032        (User->getOpcode() != ISD::BITCAST ||
6033         User->getValueType(0) != MVT::i32))
6034      return SDValue();
6035    SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
6036                                  DAG.getNode(ISD::BITCAST, dl, MVT::v4i32,
6037                                              Op.getOperand(0)),
6038                                              Op.getOperand(1));
6039    return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Extract);
6040  } else if (VT == MVT::i32) {
6041    // ExtractPS works with constant index.
6042    if (isa<ConstantSDNode>(Op.getOperand(1)))
6043      return Op;
6044  }
6045  return SDValue();
6046}
6047
6048
6049SDValue
6050X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
6051                                           SelectionDAG &DAG) const {
6052  if (!isa<ConstantSDNode>(Op.getOperand(1)))
6053    return SDValue();
6054
6055  SDValue Vec = Op.getOperand(0);
6056  EVT VecVT = Vec.getValueType();
6057
6058  // If this is a 256-bit vector result, first extract the 128-bit
6059  // vector and then extract from the 128-bit vector.
6060  if (VecVT.getSizeInBits() > 128) {
6061    DebugLoc dl = Op.getNode()->getDebugLoc();
6062    unsigned NumElems = VecVT.getVectorNumElements();
6063    SDValue Idx = Op.getOperand(1);
6064
6065    if (!isa<ConstantSDNode>(Idx))
6066      return SDValue();
6067
6068    unsigned ExtractNumElems = NumElems / (VecVT.getSizeInBits() / 128);
6069    unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
6070
6071    // Get the 128-bit vector.
6072    bool Upper = IdxVal >= ExtractNumElems;
6073    Vec = Extract128BitVector(Vec, Idx, DAG, dl);
6074
6075    // Extract from it.
6076    SDValue ScaledIdx = Idx;
6077    if (Upper)
6078      ScaledIdx = DAG.getNode(ISD::SUB, dl, Idx.getValueType(), Idx,
6079                              DAG.getConstant(ExtractNumElems,
6080                                              Idx.getValueType()));
6081    return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
6082                       ScaledIdx);
6083  }
6084
6085  assert(Vec.getValueSizeInBits() <= 128 && "Unexpected vector length");
6086
6087  if (Subtarget->hasSSE41()) {
6088    SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
6089    if (Res.getNode())
6090      return Res;
6091  }
6092
6093  EVT VT = Op.getValueType();
6094  DebugLoc dl = Op.getDebugLoc();
6095  // TODO: handle v16i8.
6096  if (VT.getSizeInBits() == 16) {
6097    SDValue Vec = Op.getOperand(0);
6098    unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6099    if (Idx == 0)
6100      return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
6101                         DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
6102                                     DAG.getNode(ISD::BITCAST, dl,
6103                                                 MVT::v4i32, Vec),
6104                                     Op.getOperand(1)));
6105    // Transform it so it match pextrw which produces a 32-bit result.
6106    EVT EltVT = MVT::i32;
6107    SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
6108                                    Op.getOperand(0), Op.getOperand(1));
6109    SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
6110                                    DAG.getValueType(VT));
6111    return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
6112  } else if (VT.getSizeInBits() == 32) {
6113    unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6114    if (Idx == 0)
6115      return Op;
6116
6117    // SHUFPS the element to the lowest double word, then movss.
6118    int Mask[4] = { Idx, -1, -1, -1 };
6119    EVT VVT = Op.getOperand(0).getValueType();
6120    SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
6121                                       DAG.getUNDEF(VVT), Mask);
6122    return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
6123                       DAG.getIntPtrConstant(0));
6124  } else if (VT.getSizeInBits() == 64) {
6125    // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
6126    // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
6127    //        to match extract_elt for f64.
6128    unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6129    if (Idx == 0)
6130      return Op;
6131
6132    // UNPCKHPD the element to the lowest double word, then movsd.
6133    // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
6134    // to a f64mem, the whole operation is folded into a single MOVHPDmr.
6135    int Mask[2] = { 1, -1 };
6136    EVT VVT = Op.getOperand(0).getValueType();
6137    SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
6138                                       DAG.getUNDEF(VVT), Mask);
6139    return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
6140                       DAG.getIntPtrConstant(0));
6141  }
6142
6143  return SDValue();
6144}
6145
6146SDValue
6147X86TargetLowering::LowerINSERT_VECTOR_ELT_SSE4(SDValue Op,
6148                                               SelectionDAG &DAG) const {
6149  EVT VT = Op.getValueType();
6150  EVT EltVT = VT.getVectorElementType();
6151  DebugLoc dl = Op.getDebugLoc();
6152
6153  SDValue N0 = Op.getOperand(0);
6154  SDValue N1 = Op.getOperand(1);
6155  SDValue N2 = Op.getOperand(2);
6156
6157  if ((EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) &&
6158      isa<ConstantSDNode>(N2)) {
6159    unsigned Opc;
6160    if (VT == MVT::v8i16)
6161      Opc = X86ISD::PINSRW;
6162    else if (VT == MVT::v16i8)
6163      Opc = X86ISD::PINSRB;
6164    else
6165      Opc = X86ISD::PINSRB;
6166
6167    // Transform it so it match pinsr{b,w} which expects a GR32 as its second
6168    // argument.
6169    if (N1.getValueType() != MVT::i32)
6170      N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
6171    if (N2.getValueType() != MVT::i32)
6172      N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
6173    return DAG.getNode(Opc, dl, VT, N0, N1, N2);
6174  } else if (EltVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
6175    // Bits [7:6] of the constant are the source select.  This will always be
6176    //  zero here.  The DAG Combiner may combine an extract_elt index into these
6177    //  bits.  For example (insert (extract, 3), 2) could be matched by putting
6178    //  the '3' into bits [7:6] of X86ISD::INSERTPS.
6179    // Bits [5:4] of the constant are the destination select.  This is the
6180    //  value of the incoming immediate.
6181    // Bits [3:0] of the constant are the zero mask.  The DAG Combiner may
6182    //   combine either bitwise AND or insert of float 0.0 to set these bits.
6183    N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
6184    // Create this as a scalar to vector..
6185    N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
6186    return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
6187  } else if (EltVT == MVT::i32 && isa<ConstantSDNode>(N2)) {
6188    // PINSR* works with constant index.
6189    return Op;
6190  }
6191  return SDValue();
6192}
6193
6194SDValue
6195X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) const {
6196  EVT VT = Op.getValueType();
6197  EVT EltVT = VT.getVectorElementType();
6198
6199  DebugLoc dl = Op.getDebugLoc();
6200  SDValue N0 = Op.getOperand(0);
6201  SDValue N1 = Op.getOperand(1);
6202  SDValue N2 = Op.getOperand(2);
6203
6204  // If this is a 256-bit vector result, first insert into a 128-bit
6205  // vector and then insert into the 256-bit vector.
6206  if (VT.getSizeInBits() > 128) {
6207    if (!isa<ConstantSDNode>(N2))
6208      return SDValue();
6209
6210    // Get the 128-bit vector.
6211    unsigned NumElems = VT.getVectorNumElements();
6212    unsigned IdxVal = cast<ConstantSDNode>(N2)->getZExtValue();
6213    bool Upper = IdxVal >= NumElems / 2;
6214
6215    SDValue SubN0 = Extract128BitVector(N0, N2, DAG, dl);
6216
6217    // Insert into it.
6218    SDValue ScaledN2 = N2;
6219    if (Upper)
6220      ScaledN2 = DAG.getNode(ISD::SUB, dl, N2.getValueType(), N2,
6221                             DAG.getConstant(NumElems /
6222                                             (VT.getSizeInBits() / 128),
6223                                             N2.getValueType()));
6224    Op = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, SubN0.getValueType(), SubN0,
6225                     N1, ScaledN2);
6226
6227    // Insert the 128-bit vector
6228    // FIXME: Why UNDEF?
6229    return Insert128BitVector(N0, Op, N2, DAG, dl);
6230  }
6231
6232  if (Subtarget->hasSSE41())
6233    return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
6234
6235  if (EltVT == MVT::i8)
6236    return SDValue();
6237
6238  if (EltVT.getSizeInBits() == 16 && isa<ConstantSDNode>(N2)) {
6239    // Transform it so it match pinsrw which expects a 16-bit value in a GR32
6240    // as its second argument.
6241    if (N1.getValueType() != MVT::i32)
6242      N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
6243    if (N2.getValueType() != MVT::i32)
6244      N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
6245    return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
6246  }
6247  return SDValue();
6248}
6249
6250SDValue
6251X86TargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) const {
6252  LLVMContext *Context = DAG.getContext();
6253  DebugLoc dl = Op.getDebugLoc();
6254  EVT OpVT = Op.getValueType();
6255
6256  // If this is a 256-bit vector result, first insert into a 128-bit
6257  // vector and then insert into the 256-bit vector.
6258  if (OpVT.getSizeInBits() > 128) {
6259    // Insert into a 128-bit vector.
6260    EVT VT128 = EVT::getVectorVT(*Context,
6261                                 OpVT.getVectorElementType(),
6262                                 OpVT.getVectorNumElements() / 2);
6263
6264    Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
6265
6266    // Insert the 128-bit vector.
6267    return Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, OpVT), Op,
6268                              DAG.getConstant(0, MVT::i32),
6269                              DAG, dl);
6270  }
6271
6272  if (Op.getValueType() == MVT::v1i64 &&
6273      Op.getOperand(0).getValueType() == MVT::i64)
6274    return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
6275
6276  SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
6277  assert(Op.getValueType().getSimpleVT().getSizeInBits() == 128 &&
6278         "Expected an SSE type!");
6279  return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(),
6280                     DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,AnyExt));
6281}
6282
6283// Lower a node with an EXTRACT_SUBVECTOR opcode.  This may result in
6284// a simple subregister reference or explicit instructions to grab
6285// upper bits of a vector.
6286SDValue
6287X86TargetLowering::LowerEXTRACT_SUBVECTOR(SDValue Op, SelectionDAG &DAG) const {
6288  if (Subtarget->hasAVX()) {
6289    DebugLoc dl = Op.getNode()->getDebugLoc();
6290    SDValue Vec = Op.getNode()->getOperand(0);
6291    SDValue Idx = Op.getNode()->getOperand(1);
6292
6293    if (Op.getNode()->getValueType(0).getSizeInBits() == 128
6294        && Vec.getNode()->getValueType(0).getSizeInBits() == 256) {
6295        return Extract128BitVector(Vec, Idx, DAG, dl);
6296    }
6297  }
6298  return SDValue();
6299}
6300
6301// Lower a node with an INSERT_SUBVECTOR opcode.  This may result in a
6302// simple superregister reference or explicit instructions to insert
6303// the upper bits of a vector.
6304SDValue
6305X86TargetLowering::LowerINSERT_SUBVECTOR(SDValue Op, SelectionDAG &DAG) const {
6306  if (Subtarget->hasAVX()) {
6307    DebugLoc dl = Op.getNode()->getDebugLoc();
6308    SDValue Vec = Op.getNode()->getOperand(0);
6309    SDValue SubVec = Op.getNode()->getOperand(1);
6310    SDValue Idx = Op.getNode()->getOperand(2);
6311
6312    if (Op.getNode()->getValueType(0).getSizeInBits() == 256
6313        && SubVec.getNode()->getValueType(0).getSizeInBits() == 128) {
6314      return Insert128BitVector(Vec, SubVec, Idx, DAG, dl);
6315    }
6316  }
6317  return SDValue();
6318}
6319
6320// ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
6321// their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
6322// one of the above mentioned nodes. It has to be wrapped because otherwise
6323// Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
6324// be used to form addressing mode. These wrapped nodes will be selected
6325// into MOV32ri.
6326SDValue
6327X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
6328  ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
6329
6330  // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
6331  // global base reg.
6332  unsigned char OpFlag = 0;
6333  unsigned WrapperKind = X86ISD::Wrapper;
6334  CodeModel::Model M = getTargetMachine().getCodeModel();
6335
6336  if (Subtarget->isPICStyleRIPRel() &&
6337      (M == CodeModel::Small || M == CodeModel::Kernel))
6338    WrapperKind = X86ISD::WrapperRIP;
6339  else if (Subtarget->isPICStyleGOT())
6340    OpFlag = X86II::MO_GOTOFF;
6341  else if (Subtarget->isPICStyleStubPIC())
6342    OpFlag = X86II::MO_PIC_BASE_OFFSET;
6343
6344  SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
6345                                             CP->getAlignment(),
6346                                             CP->getOffset(), OpFlag);
6347  DebugLoc DL = CP->getDebugLoc();
6348  Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
6349  // With PIC, the address is actually $g + Offset.
6350  if (OpFlag) {
6351    Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
6352                         DAG.getNode(X86ISD::GlobalBaseReg,
6353                                     DebugLoc(), getPointerTy()),
6354                         Result);
6355  }
6356
6357  return Result;
6358}
6359
6360SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
6361  JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
6362
6363  // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
6364  // global base reg.
6365  unsigned char OpFlag = 0;
6366  unsigned WrapperKind = X86ISD::Wrapper;
6367  CodeModel::Model M = getTargetMachine().getCodeModel();
6368
6369  if (Subtarget->isPICStyleRIPRel() &&
6370      (M == CodeModel::Small || M == CodeModel::Kernel))
6371    WrapperKind = X86ISD::WrapperRIP;
6372  else if (Subtarget->isPICStyleGOT())
6373    OpFlag = X86II::MO_GOTOFF;
6374  else if (Subtarget->isPICStyleStubPIC())
6375    OpFlag = X86II::MO_PIC_BASE_OFFSET;
6376
6377  SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
6378                                          OpFlag);
6379  DebugLoc DL = JT->getDebugLoc();
6380  Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
6381
6382  // With PIC, the address is actually $g + Offset.
6383  if (OpFlag)
6384    Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
6385                         DAG.getNode(X86ISD::GlobalBaseReg,
6386                                     DebugLoc(), getPointerTy()),
6387                         Result);
6388
6389  return Result;
6390}
6391
6392SDValue
6393X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
6394  const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
6395
6396  // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
6397  // global base reg.
6398  unsigned char OpFlag = 0;
6399  unsigned WrapperKind = X86ISD::Wrapper;
6400  CodeModel::Model M = getTargetMachine().getCodeModel();
6401
6402  if (Subtarget->isPICStyleRIPRel() &&
6403      (M == CodeModel::Small || M == CodeModel::Kernel))
6404    WrapperKind = X86ISD::WrapperRIP;
6405  else if (Subtarget->isPICStyleGOT())
6406    OpFlag = X86II::MO_GOTOFF;
6407  else if (Subtarget->isPICStyleStubPIC())
6408    OpFlag = X86II::MO_PIC_BASE_OFFSET;
6409
6410  SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
6411
6412  DebugLoc DL = Op.getDebugLoc();
6413  Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
6414
6415
6416  // With PIC, the address is actually $g + Offset.
6417  if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
6418      !Subtarget->is64Bit()) {
6419    Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
6420                         DAG.getNode(X86ISD::GlobalBaseReg,
6421                                     DebugLoc(), getPointerTy()),
6422                         Result);
6423  }
6424
6425  return Result;
6426}
6427
6428SDValue
6429X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
6430  // Create the TargetBlockAddressAddress node.
6431  unsigned char OpFlags =
6432    Subtarget->ClassifyBlockAddressReference();
6433  CodeModel::Model M = getTargetMachine().getCodeModel();
6434  const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
6435  DebugLoc dl = Op.getDebugLoc();
6436  SDValue Result = DAG.getBlockAddress(BA, getPointerTy(),
6437                                       /*isTarget=*/true, OpFlags);
6438
6439  if (Subtarget->isPICStyleRIPRel() &&
6440      (M == CodeModel::Small || M == CodeModel::Kernel))
6441    Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
6442  else
6443    Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
6444
6445  // With PIC, the address is actually $g + Offset.
6446  if (isGlobalRelativeToPICBase(OpFlags)) {
6447    Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
6448                         DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
6449                         Result);
6450  }
6451
6452  return Result;
6453}
6454
6455SDValue
6456X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, DebugLoc dl,
6457                                      int64_t Offset,
6458                                      SelectionDAG &DAG) const {
6459  // Create the TargetGlobalAddress node, folding in the constant
6460  // offset if it is legal.
6461  unsigned char OpFlags =
6462    Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
6463  CodeModel::Model M = getTargetMachine().getCodeModel();
6464  SDValue Result;
6465  if (OpFlags == X86II::MO_NO_FLAG &&
6466      X86::isOffsetSuitableForCodeModel(Offset, M)) {
6467    // A direct static reference to a global.
6468    Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
6469    Offset = 0;
6470  } else {
6471    Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
6472  }
6473
6474  if (Subtarget->isPICStyleRIPRel() &&
6475      (M == CodeModel::Small || M == CodeModel::Kernel))
6476    Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
6477  else
6478    Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
6479
6480  // With PIC, the address is actually $g + Offset.
6481  if (isGlobalRelativeToPICBase(OpFlags)) {
6482    Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
6483                         DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
6484                         Result);
6485  }
6486
6487  // For globals that require a load from a stub to get the address, emit the
6488  // load.
6489  if (isGlobalStubReference(OpFlags))
6490    Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
6491                         MachinePointerInfo::getGOT(), false, false, 0);
6492
6493  // If there was a non-zero offset that we didn't fold, create an explicit
6494  // addition for it.
6495  if (Offset != 0)
6496    Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
6497                         DAG.getConstant(Offset, getPointerTy()));
6498
6499  return Result;
6500}
6501
6502SDValue
6503X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
6504  const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
6505  int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
6506  return LowerGlobalAddress(GV, Op.getDebugLoc(), Offset, DAG);
6507}
6508
6509static SDValue
6510GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
6511           SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
6512           unsigned char OperandFlags) {
6513  MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
6514  SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
6515  DebugLoc dl = GA->getDebugLoc();
6516  SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
6517                                           GA->getValueType(0),
6518                                           GA->getOffset(),
6519                                           OperandFlags);
6520  if (InFlag) {
6521    SDValue Ops[] = { Chain,  TGA, *InFlag };
6522    Chain = DAG.getNode(X86ISD::TLSADDR, dl, NodeTys, Ops, 3);
6523  } else {
6524    SDValue Ops[]  = { Chain, TGA };
6525    Chain = DAG.getNode(X86ISD::TLSADDR, dl, NodeTys, Ops, 2);
6526  }
6527
6528  // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
6529  MFI->setAdjustsStack(true);
6530
6531  SDValue Flag = Chain.getValue(1);
6532  return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
6533}
6534
6535// Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
6536static SDValue
6537LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
6538                                const EVT PtrVT) {
6539  SDValue InFlag;
6540  DebugLoc dl = GA->getDebugLoc();  // ? function entry point might be better
6541  SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
6542                                     DAG.getNode(X86ISD::GlobalBaseReg,
6543                                                 DebugLoc(), PtrVT), InFlag);
6544  InFlag = Chain.getValue(1);
6545
6546  return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
6547}
6548
6549// Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
6550static SDValue
6551LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
6552                                const EVT PtrVT) {
6553  return GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT,
6554                    X86::RAX, X86II::MO_TLSGD);
6555}
6556
6557// Lower ISD::GlobalTLSAddress using the "initial exec" (for no-pic) or
6558// "local exec" model.
6559static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
6560                                   const EVT PtrVT, TLSModel::Model model,
6561                                   bool is64Bit) {
6562  DebugLoc dl = GA->getDebugLoc();
6563
6564  // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
6565  Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
6566                                                         is64Bit ? 257 : 256));
6567
6568  SDValue ThreadPointer = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
6569                                      DAG.getIntPtrConstant(0),
6570                                      MachinePointerInfo(Ptr), false, false, 0);
6571
6572  unsigned char OperandFlags = 0;
6573  // Most TLS accesses are not RIP relative, even on x86-64.  One exception is
6574  // initialexec.
6575  unsigned WrapperKind = X86ISD::Wrapper;
6576  if (model == TLSModel::LocalExec) {
6577    OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
6578  } else if (is64Bit) {
6579    assert(model == TLSModel::InitialExec);
6580    OperandFlags = X86II::MO_GOTTPOFF;
6581    WrapperKind = X86ISD::WrapperRIP;
6582  } else {
6583    assert(model == TLSModel::InitialExec);
6584    OperandFlags = X86II::MO_INDNTPOFF;
6585  }
6586
6587  // emit "addl x@ntpoff,%eax" (local exec) or "addl x@indntpoff,%eax" (initial
6588  // exec)
6589  SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
6590                                           GA->getValueType(0),
6591                                           GA->getOffset(), OperandFlags);
6592  SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
6593
6594  if (model == TLSModel::InitialExec)
6595    Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
6596                         MachinePointerInfo::getGOT(), false, false, 0);
6597
6598  // The address of the thread local variable is the add of the thread
6599  // pointer with the offset of the variable.
6600  return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
6601}
6602
6603SDValue
6604X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
6605
6606  GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
6607  const GlobalValue *GV = GA->getGlobal();
6608
6609  if (Subtarget->isTargetELF()) {
6610    // TODO: implement the "local dynamic" model
6611    // TODO: implement the "initial exec"model for pic executables
6612
6613    // If GV is an alias then use the aliasee for determining
6614    // thread-localness.
6615    if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
6616      GV = GA->resolveAliasedGlobal(false);
6617
6618    TLSModel::Model model
6619      = getTLSModel(GV, getTargetMachine().getRelocationModel());
6620
6621    switch (model) {
6622      case TLSModel::GeneralDynamic:
6623      case TLSModel::LocalDynamic: // not implemented
6624        if (Subtarget->is64Bit())
6625          return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
6626        return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
6627
6628      case TLSModel::InitialExec:
6629      case TLSModel::LocalExec:
6630        return LowerToTLSExecModel(GA, DAG, getPointerTy(), model,
6631                                   Subtarget->is64Bit());
6632    }
6633  } else if (Subtarget->isTargetDarwin()) {
6634    // Darwin only has one model of TLS.  Lower to that.
6635    unsigned char OpFlag = 0;
6636    unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
6637                           X86ISD::WrapperRIP : X86ISD::Wrapper;
6638
6639    // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
6640    // global base reg.
6641    bool PIC32 = (getTargetMachine().getRelocationModel() == Reloc::PIC_) &&
6642                  !Subtarget->is64Bit();
6643    if (PIC32)
6644      OpFlag = X86II::MO_TLVP_PIC_BASE;
6645    else
6646      OpFlag = X86II::MO_TLVP;
6647    DebugLoc DL = Op.getDebugLoc();
6648    SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
6649                                                GA->getValueType(0),
6650                                                GA->getOffset(), OpFlag);
6651    SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
6652
6653    // With PIC32, the address is actually $g + Offset.
6654    if (PIC32)
6655      Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
6656                           DAG.getNode(X86ISD::GlobalBaseReg,
6657                                       DebugLoc(), getPointerTy()),
6658                           Offset);
6659
6660    // Lowering the machine isd will make sure everything is in the right
6661    // location.
6662    SDValue Chain = DAG.getEntryNode();
6663    SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
6664    SDValue Args[] = { Chain, Offset };
6665    Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args, 2);
6666
6667    // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
6668    MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
6669    MFI->setAdjustsStack(true);
6670
6671    // And our return value (tls address) is in the standard call return value
6672    // location.
6673    unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
6674    return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy());
6675  }
6676
6677  assert(false &&
6678         "TLS not implemented for this target.");
6679
6680  llvm_unreachable("Unreachable");
6681  return SDValue();
6682}
6683
6684
6685/// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values and
6686/// take a 2 x i32 value to shift plus a shift amount.
6687SDValue X86TargetLowering::LowerShiftParts(SDValue Op, SelectionDAG &DAG) const {
6688  assert(Op.getNumOperands() == 3 && "Not a double-shift!");
6689  EVT VT = Op.getValueType();
6690  unsigned VTBits = VT.getSizeInBits();
6691  DebugLoc dl = Op.getDebugLoc();
6692  bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
6693  SDValue ShOpLo = Op.getOperand(0);
6694  SDValue ShOpHi = Op.getOperand(1);
6695  SDValue ShAmt  = Op.getOperand(2);
6696  SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
6697                                     DAG.getConstant(VTBits - 1, MVT::i8))
6698                       : DAG.getConstant(0, VT);
6699
6700  SDValue Tmp2, Tmp3;
6701  if (Op.getOpcode() == ISD::SHL_PARTS) {
6702    Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
6703    Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
6704  } else {
6705    Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
6706    Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, ShAmt);
6707  }
6708
6709  SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
6710                                DAG.getConstant(VTBits, MVT::i8));
6711  SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
6712                             AndNode, DAG.getConstant(0, MVT::i8));
6713
6714  SDValue Hi, Lo;
6715  SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
6716  SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
6717  SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
6718
6719  if (Op.getOpcode() == ISD::SHL_PARTS) {
6720    Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
6721    Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
6722  } else {
6723    Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
6724    Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
6725  }
6726
6727  SDValue Ops[2] = { Lo, Hi };
6728  return DAG.getMergeValues(Ops, 2, dl);
6729}
6730
6731SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
6732                                           SelectionDAG &DAG) const {
6733  EVT SrcVT = Op.getOperand(0).getValueType();
6734
6735  if (SrcVT.isVector())
6736    return SDValue();
6737
6738  assert(SrcVT.getSimpleVT() <= MVT::i64 && SrcVT.getSimpleVT() >= MVT::i16 &&
6739         "Unknown SINT_TO_FP to lower!");
6740
6741  // These are really Legal; return the operand so the caller accepts it as
6742  // Legal.
6743  if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
6744    return Op;
6745  if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
6746      Subtarget->is64Bit()) {
6747    return Op;
6748  }
6749
6750  DebugLoc dl = Op.getDebugLoc();
6751  unsigned Size = SrcVT.getSizeInBits()/8;
6752  MachineFunction &MF = DAG.getMachineFunction();
6753  int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
6754  SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
6755  SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
6756                               StackSlot,
6757                               MachinePointerInfo::getFixedStack(SSFI),
6758                               false, false, 0);
6759  return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
6760}
6761
6762SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
6763                                     SDValue StackSlot,
6764                                     SelectionDAG &DAG) const {
6765  // Build the FILD
6766  DebugLoc DL = Op.getDebugLoc();
6767  SDVTList Tys;
6768  bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
6769  if (useSSE)
6770    Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
6771  else
6772    Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
6773
6774  unsigned ByteSize = SrcVT.getSizeInBits()/8;
6775
6776  FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
6777  MachineMemOperand *MMO;
6778  if (FI) {
6779    int SSFI = FI->getIndex();
6780    MMO =
6781      DAG.getMachineFunction()
6782      .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
6783                            MachineMemOperand::MOLoad, ByteSize, ByteSize);
6784  } else {
6785    MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
6786    StackSlot = StackSlot.getOperand(1);
6787  }
6788  SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
6789  SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
6790                                           X86ISD::FILD, DL,
6791                                           Tys, Ops, array_lengthof(Ops),
6792                                           SrcVT, MMO);
6793
6794  if (useSSE) {
6795    Chain = Result.getValue(1);
6796    SDValue InFlag = Result.getValue(2);
6797
6798    // FIXME: Currently the FST is flagged to the FILD_FLAG. This
6799    // shouldn't be necessary except that RFP cannot be live across
6800    // multiple blocks. When stackifier is fixed, they can be uncoupled.
6801    MachineFunction &MF = DAG.getMachineFunction();
6802    unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
6803    int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
6804    SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
6805    Tys = DAG.getVTList(MVT::Other);
6806    SDValue Ops[] = {
6807      Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
6808    };
6809    MachineMemOperand *MMO =
6810      DAG.getMachineFunction()
6811      .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
6812                            MachineMemOperand::MOStore, SSFISize, SSFISize);
6813
6814    Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
6815                                    Ops, array_lengthof(Ops),
6816                                    Op.getValueType(), MMO);
6817    Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
6818                         MachinePointerInfo::getFixedStack(SSFI),
6819                         false, false, 0);
6820  }
6821
6822  return Result;
6823}
6824
6825// LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
6826SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
6827                                               SelectionDAG &DAG) const {
6828  // This algorithm is not obvious. Here it is in C code, more or less:
6829  /*
6830    double uint64_to_double( uint32_t hi, uint32_t lo ) {
6831      static const __m128i exp = { 0x4330000045300000ULL, 0 };
6832      static const __m128d bias = { 0x1.0p84, 0x1.0p52 };
6833
6834      // Copy ints to xmm registers.
6835      __m128i xh = _mm_cvtsi32_si128( hi );
6836      __m128i xl = _mm_cvtsi32_si128( lo );
6837
6838      // Combine into low half of a single xmm register.
6839      __m128i x = _mm_unpacklo_epi32( xh, xl );
6840      __m128d d;
6841      double sd;
6842
6843      // Merge in appropriate exponents to give the integer bits the right
6844      // magnitude.
6845      x = _mm_unpacklo_epi32( x, exp );
6846
6847      // Subtract away the biases to deal with the IEEE-754 double precision
6848      // implicit 1.
6849      d = _mm_sub_pd( (__m128d) x, bias );
6850
6851      // All conversions up to here are exact. The correctly rounded result is
6852      // calculated using the current rounding mode using the following
6853      // horizontal add.
6854      d = _mm_add_sd( d, _mm_unpackhi_pd( d, d ) );
6855      _mm_store_sd( &sd, d );   // Because we are returning doubles in XMM, this
6856                                // store doesn't really need to be here (except
6857                                // maybe to zero the other double)
6858      return sd;
6859    }
6860  */
6861
6862  DebugLoc dl = Op.getDebugLoc();
6863  LLVMContext *Context = DAG.getContext();
6864
6865  // Build some magic constants.
6866  std::vector<Constant*> CV0;
6867  CV0.push_back(ConstantInt::get(*Context, APInt(32, 0x45300000)));
6868  CV0.push_back(ConstantInt::get(*Context, APInt(32, 0x43300000)));
6869  CV0.push_back(ConstantInt::get(*Context, APInt(32, 0)));
6870  CV0.push_back(ConstantInt::get(*Context, APInt(32, 0)));
6871  Constant *C0 = ConstantVector::get(CV0);
6872  SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
6873
6874  std::vector<Constant*> CV1;
6875  CV1.push_back(
6876    ConstantFP::get(*Context, APFloat(APInt(64, 0x4530000000000000ULL))));
6877  CV1.push_back(
6878    ConstantFP::get(*Context, APFloat(APInt(64, 0x4330000000000000ULL))));
6879  Constant *C1 = ConstantVector::get(CV1);
6880  SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
6881
6882  SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
6883                            DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
6884                                        Op.getOperand(0),
6885                                        DAG.getIntPtrConstant(1)));
6886  SDValue XR2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
6887                            DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
6888                                        Op.getOperand(0),
6889                                        DAG.getIntPtrConstant(0)));
6890  SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32, XR1, XR2);
6891  SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
6892                              MachinePointerInfo::getConstantPool(),
6893                              false, false, 16);
6894  SDValue Unpck2 = getUnpackl(DAG, dl, MVT::v4i32, Unpck1, CLod0);
6895  SDValue XR2F = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Unpck2);
6896  SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
6897                              MachinePointerInfo::getConstantPool(),
6898                              false, false, 16);
6899  SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
6900
6901  // Add the halves; easiest way is to swap them into another reg first.
6902  int ShufMask[2] = { 1, -1 };
6903  SDValue Shuf = DAG.getVectorShuffle(MVT::v2f64, dl, Sub,
6904                                      DAG.getUNDEF(MVT::v2f64), ShufMask);
6905  SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::v2f64, Shuf, Sub);
6906  return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Add,
6907                     DAG.getIntPtrConstant(0));
6908}
6909
6910// LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
6911SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
6912                                               SelectionDAG &DAG) const {
6913  DebugLoc dl = Op.getDebugLoc();
6914  // FP constant to bias correct the final result.
6915  SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
6916                                   MVT::f64);
6917
6918  // Load the 32-bit value into an XMM register.
6919  SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
6920                             DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
6921                                         Op.getOperand(0),
6922                                         DAG.getIntPtrConstant(0)));
6923
6924  Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
6925                     DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Load),
6926                     DAG.getIntPtrConstant(0));
6927
6928  // Or the load with the bias.
6929  SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
6930                           DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
6931                                       DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6932                                                   MVT::v2f64, Load)),
6933                           DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
6934                                       DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6935                                                   MVT::v2f64, Bias)));
6936  Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
6937                   DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or),
6938                   DAG.getIntPtrConstant(0));
6939
6940  // Subtract the bias.
6941  SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
6942
6943  // Handle final rounding.
6944  EVT DestVT = Op.getValueType();
6945
6946  if (DestVT.bitsLT(MVT::f64)) {
6947    return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
6948                       DAG.getIntPtrConstant(0));
6949  } else if (DestVT.bitsGT(MVT::f64)) {
6950    return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
6951  }
6952
6953  // Handle final rounding.
6954  return Sub;
6955}
6956
6957SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
6958                                           SelectionDAG &DAG) const {
6959  SDValue N0 = Op.getOperand(0);
6960  DebugLoc dl = Op.getDebugLoc();
6961
6962  // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
6963  // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
6964  // the optimization here.
6965  if (DAG.SignBitIsZero(N0))
6966    return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
6967
6968  EVT SrcVT = N0.getValueType();
6969  EVT DstVT = Op.getValueType();
6970  if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
6971    return LowerUINT_TO_FP_i64(Op, DAG);
6972  else if (SrcVT == MVT::i32 && X86ScalarSSEf64)
6973    return LowerUINT_TO_FP_i32(Op, DAG);
6974
6975  // Make a 64-bit buffer, and use it to build an FILD.
6976  SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
6977  if (SrcVT == MVT::i32) {
6978    SDValue WordOff = DAG.getConstant(4, getPointerTy());
6979    SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
6980                                     getPointerTy(), StackSlot, WordOff);
6981    SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
6982                                  StackSlot, MachinePointerInfo(),
6983                                  false, false, 0);
6984    SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
6985                                  OffsetSlot, MachinePointerInfo(),
6986                                  false, false, 0);
6987    SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
6988    return Fild;
6989  }
6990
6991  assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
6992  SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
6993                                StackSlot, MachinePointerInfo(),
6994                               false, false, 0);
6995  // For i64 source, we need to add the appropriate power of 2 if the input
6996  // was negative.  This is the same as the optimization in
6997  // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
6998  // we must be careful to do the computation in x87 extended precision, not
6999  // in SSE. (The generic code can't know it's OK to do this, or how to.)
7000  int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
7001  MachineMemOperand *MMO =
7002    DAG.getMachineFunction()
7003    .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7004                          MachineMemOperand::MOLoad, 8, 8);
7005
7006  SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
7007  SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
7008  SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops, 3,
7009                                         MVT::i64, MMO);
7010
7011  APInt FF(32, 0x5F800000ULL);
7012
7013  // Check whether the sign bit is set.
7014  SDValue SignSet = DAG.getSetCC(dl, getSetCCResultType(MVT::i64),
7015                                 Op.getOperand(0), DAG.getConstant(0, MVT::i64),
7016                                 ISD::SETLT);
7017
7018  // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
7019  SDValue FudgePtr = DAG.getConstantPool(
7020                             ConstantInt::get(*DAG.getContext(), FF.zext(64)),
7021                                         getPointerTy());
7022
7023  // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
7024  SDValue Zero = DAG.getIntPtrConstant(0);
7025  SDValue Four = DAG.getIntPtrConstant(4);
7026  SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
7027                               Zero, Four);
7028  FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
7029
7030  // Load the value out, extending it from f32 to f80.
7031  // FIXME: Avoid the extend by constructing the right constant pool?
7032  SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(),
7033                                 FudgePtr, MachinePointerInfo::getConstantPool(),
7034                                 MVT::f32, false, false, 4);
7035  // Extend everything to 80 bits to force it to be done on x87.
7036  SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
7037  return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add, DAG.getIntPtrConstant(0));
7038}
7039
7040std::pair<SDValue,SDValue> X86TargetLowering::
7041FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG, bool IsSigned) const {
7042  DebugLoc DL = Op.getDebugLoc();
7043
7044  EVT DstTy = Op.getValueType();
7045
7046  if (!IsSigned) {
7047    assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
7048    DstTy = MVT::i64;
7049  }
7050
7051  assert(DstTy.getSimpleVT() <= MVT::i64 &&
7052         DstTy.getSimpleVT() >= MVT::i16 &&
7053         "Unknown FP_TO_SINT to lower!");
7054
7055  // These are really Legal.
7056  if (DstTy == MVT::i32 &&
7057      isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
7058    return std::make_pair(SDValue(), SDValue());
7059  if (Subtarget->is64Bit() &&
7060      DstTy == MVT::i64 &&
7061      isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
7062    return std::make_pair(SDValue(), SDValue());
7063
7064  // We lower FP->sint64 into FISTP64, followed by a load, all to a temporary
7065  // stack slot.
7066  MachineFunction &MF = DAG.getMachineFunction();
7067  unsigned MemSize = DstTy.getSizeInBits()/8;
7068  int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
7069  SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7070
7071
7072
7073  unsigned Opc;
7074  switch (DstTy.getSimpleVT().SimpleTy) {
7075  default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
7076  case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
7077  case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
7078  case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
7079  }
7080
7081  SDValue Chain = DAG.getEntryNode();
7082  SDValue Value = Op.getOperand(0);
7083  EVT TheVT = Op.getOperand(0).getValueType();
7084  if (isScalarFPTypeInSSEReg(TheVT)) {
7085    assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
7086    Chain = DAG.getStore(Chain, DL, Value, StackSlot,
7087                         MachinePointerInfo::getFixedStack(SSFI),
7088                         false, false, 0);
7089    SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
7090    SDValue Ops[] = {
7091      Chain, StackSlot, DAG.getValueType(TheVT)
7092    };
7093
7094    MachineMemOperand *MMO =
7095      MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7096                              MachineMemOperand::MOLoad, MemSize, MemSize);
7097    Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, 3,
7098                                    DstTy, MMO);
7099    Chain = Value.getValue(1);
7100    SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
7101    StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7102  }
7103
7104  MachineMemOperand *MMO =
7105    MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7106                            MachineMemOperand::MOStore, MemSize, MemSize);
7107
7108  // Build the FP_TO_INT*_IN_MEM
7109  SDValue Ops[] = { Chain, Value, StackSlot };
7110  SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
7111                                         Ops, 3, DstTy, MMO);
7112
7113  return std::make_pair(FIST, StackSlot);
7114}
7115
7116SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
7117                                           SelectionDAG &DAG) const {
7118  if (Op.getValueType().isVector())
7119    return SDValue();
7120
7121  std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG, true);
7122  SDValue FIST = Vals.first, StackSlot = Vals.second;
7123  // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
7124  if (FIST.getNode() == 0) return Op;
7125
7126  // Load the result.
7127  return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
7128                     FIST, StackSlot, MachinePointerInfo(), false, false, 0);
7129}
7130
7131SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
7132                                           SelectionDAG &DAG) const {
7133  std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG, false);
7134  SDValue FIST = Vals.first, StackSlot = Vals.second;
7135  assert(FIST.getNode() && "Unexpected failure");
7136
7137  // Load the result.
7138  return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
7139                     FIST, StackSlot, MachinePointerInfo(), false, false, 0);
7140}
7141
7142SDValue X86TargetLowering::LowerFABS(SDValue Op,
7143                                     SelectionDAG &DAG) const {
7144  LLVMContext *Context = DAG.getContext();
7145  DebugLoc dl = Op.getDebugLoc();
7146  EVT VT = Op.getValueType();
7147  EVT EltVT = VT;
7148  if (VT.isVector())
7149    EltVT = VT.getVectorElementType();
7150  std::vector<Constant*> CV;
7151  if (EltVT == MVT::f64) {
7152    Constant *C = ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63))));
7153    CV.push_back(C);
7154    CV.push_back(C);
7155  } else {
7156    Constant *C = ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31))));
7157    CV.push_back(C);
7158    CV.push_back(C);
7159    CV.push_back(C);
7160    CV.push_back(C);
7161  }
7162  Constant *C = ConstantVector::get(CV);
7163  SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
7164  SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
7165                             MachinePointerInfo::getConstantPool(),
7166                             false, false, 16);
7167  return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
7168}
7169
7170SDValue X86TargetLowering::LowerFNEG(SDValue Op, SelectionDAG &DAG) const {
7171  LLVMContext *Context = DAG.getContext();
7172  DebugLoc dl = Op.getDebugLoc();
7173  EVT VT = Op.getValueType();
7174  EVT EltVT = VT;
7175  if (VT.isVector())
7176    EltVT = VT.getVectorElementType();
7177  std::vector<Constant*> CV;
7178  if (EltVT == MVT::f64) {
7179    Constant *C = ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63)));
7180    CV.push_back(C);
7181    CV.push_back(C);
7182  } else {
7183    Constant *C = ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31)));
7184    CV.push_back(C);
7185    CV.push_back(C);
7186    CV.push_back(C);
7187    CV.push_back(C);
7188  }
7189  Constant *C = ConstantVector::get(CV);
7190  SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
7191  SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
7192                             MachinePointerInfo::getConstantPool(),
7193                             false, false, 16);
7194  if (VT.isVector()) {
7195    return DAG.getNode(ISD::BITCAST, dl, VT,
7196                       DAG.getNode(ISD::XOR, dl, MVT::v2i64,
7197                    DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
7198                                Op.getOperand(0)),
7199                    DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, Mask)));
7200  } else {
7201    return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
7202  }
7203}
7204
7205SDValue X86TargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
7206  LLVMContext *Context = DAG.getContext();
7207  SDValue Op0 = Op.getOperand(0);
7208  SDValue Op1 = Op.getOperand(1);
7209  DebugLoc dl = Op.getDebugLoc();
7210  EVT VT = Op.getValueType();
7211  EVT SrcVT = Op1.getValueType();
7212
7213  // If second operand is smaller, extend it first.
7214  if (SrcVT.bitsLT(VT)) {
7215    Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
7216    SrcVT = VT;
7217  }
7218  // And if it is bigger, shrink it first.
7219  if (SrcVT.bitsGT(VT)) {
7220    Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
7221    SrcVT = VT;
7222  }
7223
7224  // At this point the operands and the result should have the same
7225  // type, and that won't be f80 since that is not custom lowered.
7226
7227  // First get the sign bit of second operand.
7228  std::vector<Constant*> CV;
7229  if (SrcVT == MVT::f64) {
7230    CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63))));
7231    CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
7232  } else {
7233    CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31))));
7234    CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
7235    CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
7236    CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
7237  }
7238  Constant *C = ConstantVector::get(CV);
7239  SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
7240  SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
7241                              MachinePointerInfo::getConstantPool(),
7242                              false, false, 16);
7243  SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
7244
7245  // Shift sign bit right or left if the two operands have different types.
7246  if (SrcVT.bitsGT(VT)) {
7247    // Op0 is MVT::f32, Op1 is MVT::f64.
7248    SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
7249    SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
7250                          DAG.getConstant(32, MVT::i32));
7251    SignBit = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, SignBit);
7252    SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
7253                          DAG.getIntPtrConstant(0));
7254  }
7255
7256  // Clear first operand sign bit.
7257  CV.clear();
7258  if (VT == MVT::f64) {
7259    CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63)))));
7260    CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
7261  } else {
7262    CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31)))));
7263    CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
7264    CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
7265    CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
7266  }
7267  C = ConstantVector::get(CV);
7268  CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
7269  SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
7270                              MachinePointerInfo::getConstantPool(),
7271                              false, false, 16);
7272  SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
7273
7274  // Or the value with the sign bit.
7275  return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
7276}
7277
7278SDValue X86TargetLowering::LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) const {
7279  SDValue N0 = Op.getOperand(0);
7280  DebugLoc dl = Op.getDebugLoc();
7281  EVT VT = Op.getValueType();
7282
7283  // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
7284  SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
7285                                  DAG.getConstant(1, VT));
7286  return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, VT));
7287}
7288
7289/// Emit nodes that will be selected as "test Op0,Op0", or something
7290/// equivalent.
7291SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC,
7292                                    SelectionDAG &DAG) const {
7293  DebugLoc dl = Op.getDebugLoc();
7294
7295  // CF and OF aren't always set the way we want. Determine which
7296  // of these we need.
7297  bool NeedCF = false;
7298  bool NeedOF = false;
7299  switch (X86CC) {
7300  default: break;
7301  case X86::COND_A: case X86::COND_AE:
7302  case X86::COND_B: case X86::COND_BE:
7303    NeedCF = true;
7304    break;
7305  case X86::COND_G: case X86::COND_GE:
7306  case X86::COND_L: case X86::COND_LE:
7307  case X86::COND_O: case X86::COND_NO:
7308    NeedOF = true;
7309    break;
7310  }
7311
7312  // See if we can use the EFLAGS value from the operand instead of
7313  // doing a separate TEST. TEST always sets OF and CF to 0, so unless
7314  // we prove that the arithmetic won't overflow, we can't use OF or CF.
7315  if (Op.getResNo() != 0 || NeedOF || NeedCF)
7316    // Emit a CMP with 0, which is the TEST pattern.
7317    return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
7318                       DAG.getConstant(0, Op.getValueType()));
7319
7320  unsigned Opcode = 0;
7321  unsigned NumOperands = 0;
7322  switch (Op.getNode()->getOpcode()) {
7323  case ISD::ADD:
7324    // Due to an isel shortcoming, be conservative if this add is likely to be
7325    // selected as part of a load-modify-store instruction. When the root node
7326    // in a match is a store, isel doesn't know how to remap non-chain non-flag
7327    // uses of other nodes in the match, such as the ADD in this case. This
7328    // leads to the ADD being left around and reselected, with the result being
7329    // two adds in the output.  Alas, even if none our users are stores, that
7330    // doesn't prove we're O.K.  Ergo, if we have any parents that aren't
7331    // CopyToReg or SETCC, eschew INC/DEC.  A better fix seems to require
7332    // climbing the DAG back to the root, and it doesn't seem to be worth the
7333    // effort.
7334    for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
7335           UE = Op.getNode()->use_end(); UI != UE; ++UI)
7336      if (UI->getOpcode() != ISD::CopyToReg && UI->getOpcode() != ISD::SETCC)
7337        goto default_case;
7338
7339    if (ConstantSDNode *C =
7340        dyn_cast<ConstantSDNode>(Op.getNode()->getOperand(1))) {
7341      // An add of one will be selected as an INC.
7342      if (C->getAPIntValue() == 1) {
7343        Opcode = X86ISD::INC;
7344        NumOperands = 1;
7345        break;
7346      }
7347
7348      // An add of negative one (subtract of one) will be selected as a DEC.
7349      if (C->getAPIntValue().isAllOnesValue()) {
7350        Opcode = X86ISD::DEC;
7351        NumOperands = 1;
7352        break;
7353      }
7354    }
7355
7356    // Otherwise use a regular EFLAGS-setting add.
7357    Opcode = X86ISD::ADD;
7358    NumOperands = 2;
7359    break;
7360  case ISD::AND: {
7361    // If the primary and result isn't used, don't bother using X86ISD::AND,
7362    // because a TEST instruction will be better.
7363    bool NonFlagUse = false;
7364    for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
7365           UE = Op.getNode()->use_end(); UI != UE; ++UI) {
7366      SDNode *User = *UI;
7367      unsigned UOpNo = UI.getOperandNo();
7368      if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
7369        // Look pass truncate.
7370        UOpNo = User->use_begin().getOperandNo();
7371        User = *User->use_begin();
7372      }
7373
7374      if (User->getOpcode() != ISD::BRCOND &&
7375          User->getOpcode() != ISD::SETCC &&
7376          (User->getOpcode() != ISD::SELECT || UOpNo != 0)) {
7377        NonFlagUse = true;
7378        break;
7379      }
7380    }
7381
7382    if (!NonFlagUse)
7383      break;
7384  }
7385    // FALL THROUGH
7386  case ISD::SUB:
7387  case ISD::OR:
7388  case ISD::XOR:
7389    // Due to the ISEL shortcoming noted above, be conservative if this op is
7390    // likely to be selected as part of a load-modify-store instruction.
7391    for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
7392           UE = Op.getNode()->use_end(); UI != UE; ++UI)
7393      if (UI->getOpcode() == ISD::STORE)
7394        goto default_case;
7395
7396    // Otherwise use a regular EFLAGS-setting instruction.
7397    switch (Op.getNode()->getOpcode()) {
7398    default: llvm_unreachable("unexpected operator!");
7399    case ISD::SUB: Opcode = X86ISD::SUB; break;
7400    case ISD::OR:  Opcode = X86ISD::OR;  break;
7401    case ISD::XOR: Opcode = X86ISD::XOR; break;
7402    case ISD::AND: Opcode = X86ISD::AND; break;
7403    }
7404
7405    NumOperands = 2;
7406    break;
7407  case X86ISD::ADD:
7408  case X86ISD::SUB:
7409  case X86ISD::INC:
7410  case X86ISD::DEC:
7411  case X86ISD::OR:
7412  case X86ISD::XOR:
7413  case X86ISD::AND:
7414    return SDValue(Op.getNode(), 1);
7415  default:
7416  default_case:
7417    break;
7418  }
7419
7420  if (Opcode == 0)
7421    // Emit a CMP with 0, which is the TEST pattern.
7422    return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
7423                       DAG.getConstant(0, Op.getValueType()));
7424
7425  SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
7426  SmallVector<SDValue, 4> Ops;
7427  for (unsigned i = 0; i != NumOperands; ++i)
7428    Ops.push_back(Op.getOperand(i));
7429
7430  SDValue New = DAG.getNode(Opcode, dl, VTs, &Ops[0], NumOperands);
7431  DAG.ReplaceAllUsesWith(Op, New);
7432  return SDValue(New.getNode(), 1);
7433}
7434
7435/// Emit nodes that will be selected as "cmp Op0,Op1", or something
7436/// equivalent.
7437SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
7438                                   SelectionDAG &DAG) const {
7439  if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1))
7440    if (C->getAPIntValue() == 0)
7441      return EmitTest(Op0, X86CC, DAG);
7442
7443  DebugLoc dl = Op0.getDebugLoc();
7444  return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
7445}
7446
7447/// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
7448/// if it's possible.
7449SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
7450                                     DebugLoc dl, SelectionDAG &DAG) const {
7451  SDValue Op0 = And.getOperand(0);
7452  SDValue Op1 = And.getOperand(1);
7453  if (Op0.getOpcode() == ISD::TRUNCATE)
7454    Op0 = Op0.getOperand(0);
7455  if (Op1.getOpcode() == ISD::TRUNCATE)
7456    Op1 = Op1.getOperand(0);
7457
7458  SDValue LHS, RHS;
7459  if (Op1.getOpcode() == ISD::SHL)
7460    std::swap(Op0, Op1);
7461  if (Op0.getOpcode() == ISD::SHL) {
7462    if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
7463      if (And00C->getZExtValue() == 1) {
7464        // If we looked past a truncate, check that it's only truncating away
7465        // known zeros.
7466        unsigned BitWidth = Op0.getValueSizeInBits();
7467        unsigned AndBitWidth = And.getValueSizeInBits();
7468        if (BitWidth > AndBitWidth) {
7469          APInt Mask = APInt::getAllOnesValue(BitWidth), Zeros, Ones;
7470          DAG.ComputeMaskedBits(Op0, Mask, Zeros, Ones);
7471          if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
7472            return SDValue();
7473        }
7474        LHS = Op1;
7475        RHS = Op0.getOperand(1);
7476      }
7477  } else if (Op1.getOpcode() == ISD::Constant) {
7478    ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
7479    SDValue AndLHS = Op0;
7480    if (AndRHS->getZExtValue() == 1 && AndLHS.getOpcode() == ISD::SRL) {
7481      LHS = AndLHS.getOperand(0);
7482      RHS = AndLHS.getOperand(1);
7483    }
7484  }
7485
7486  if (LHS.getNode()) {
7487    // If LHS is i8, promote it to i32 with any_extend.  There is no i8 BT
7488    // instruction.  Since the shift amount is in-range-or-undefined, we know
7489    // that doing a bittest on the i32 value is ok.  We extend to i32 because
7490    // the encoding for the i16 version is larger than the i32 version.
7491    // Also promote i16 to i32 for performance / code size reason.
7492    if (LHS.getValueType() == MVT::i8 ||
7493        LHS.getValueType() == MVT::i16)
7494      LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
7495
7496    // If the operand types disagree, extend the shift amount to match.  Since
7497    // BT ignores high bits (like shifts) we can use anyextend.
7498    if (LHS.getValueType() != RHS.getValueType())
7499      RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
7500
7501    SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
7502    unsigned Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
7503    return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
7504                       DAG.getConstant(Cond, MVT::i8), BT);
7505  }
7506
7507  return SDValue();
7508}
7509
7510SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
7511  assert(Op.getValueType() == MVT::i8 && "SetCC type must be 8-bit integer");
7512  SDValue Op0 = Op.getOperand(0);
7513  SDValue Op1 = Op.getOperand(1);
7514  DebugLoc dl = Op.getDebugLoc();
7515  ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
7516
7517  // Optimize to BT if possible.
7518  // Lower (X & (1 << N)) == 0 to BT(X, N).
7519  // Lower ((X >>u N) & 1) != 0 to BT(X, N).
7520  // Lower ((X >>s N) & 1) != 0 to BT(X, N).
7521  if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
7522      Op1.getOpcode() == ISD::Constant &&
7523      cast<ConstantSDNode>(Op1)->isNullValue() &&
7524      (CC == ISD::SETEQ || CC == ISD::SETNE)) {
7525    SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
7526    if (NewSetCC.getNode())
7527      return NewSetCC;
7528  }
7529
7530  // Look for X == 0, X == 1, X != 0, or X != 1.  We can simplify some forms of
7531  // these.
7532  if (Op1.getOpcode() == ISD::Constant &&
7533      (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
7534       cast<ConstantSDNode>(Op1)->isNullValue()) &&
7535      (CC == ISD::SETEQ || CC == ISD::SETNE)) {
7536
7537    // If the input is a setcc, then reuse the input setcc or use a new one with
7538    // the inverted condition.
7539    if (Op0.getOpcode() == X86ISD::SETCC) {
7540      X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
7541      bool Invert = (CC == ISD::SETNE) ^
7542        cast<ConstantSDNode>(Op1)->isNullValue();
7543      if (!Invert) return Op0;
7544
7545      CCode = X86::GetOppositeBranchCondition(CCode);
7546      return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
7547                         DAG.getConstant(CCode, MVT::i8), Op0.getOperand(1));
7548    }
7549  }
7550
7551  bool isFP = Op1.getValueType().isFloatingPoint();
7552  unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
7553  if (X86CC == X86::COND_INVALID)
7554    return SDValue();
7555
7556  SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, DAG);
7557  return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
7558                     DAG.getConstant(X86CC, MVT::i8), EFLAGS);
7559}
7560
7561SDValue X86TargetLowering::LowerVSETCC(SDValue Op, SelectionDAG &DAG) const {
7562  SDValue Cond;
7563  SDValue Op0 = Op.getOperand(0);
7564  SDValue Op1 = Op.getOperand(1);
7565  SDValue CC = Op.getOperand(2);
7566  EVT VT = Op.getValueType();
7567  ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
7568  bool isFP = Op.getOperand(1).getValueType().isFloatingPoint();
7569  DebugLoc dl = Op.getDebugLoc();
7570
7571  if (isFP) {
7572    unsigned SSECC = 8;
7573    EVT VT0 = Op0.getValueType();
7574    assert(VT0 == MVT::v4f32 || VT0 == MVT::v2f64);
7575    unsigned Opc = VT0 == MVT::v4f32 ? X86ISD::CMPPS : X86ISD::CMPPD;
7576    bool Swap = false;
7577
7578    switch (SetCCOpcode) {
7579    default: break;
7580    case ISD::SETOEQ:
7581    case ISD::SETEQ:  SSECC = 0; break;
7582    case ISD::SETOGT:
7583    case ISD::SETGT: Swap = true; // Fallthrough
7584    case ISD::SETLT:
7585    case ISD::SETOLT: SSECC = 1; break;
7586    case ISD::SETOGE:
7587    case ISD::SETGE: Swap = true; // Fallthrough
7588    case ISD::SETLE:
7589    case ISD::SETOLE: SSECC = 2; break;
7590    case ISD::SETUO:  SSECC = 3; break;
7591    case ISD::SETUNE:
7592    case ISD::SETNE:  SSECC = 4; break;
7593    case ISD::SETULE: Swap = true;
7594    case ISD::SETUGE: SSECC = 5; break;
7595    case ISD::SETULT: Swap = true;
7596    case ISD::SETUGT: SSECC = 6; break;
7597    case ISD::SETO:   SSECC = 7; break;
7598    }
7599    if (Swap)
7600      std::swap(Op0, Op1);
7601
7602    // In the two special cases we can't handle, emit two comparisons.
7603    if (SSECC == 8) {
7604      if (SetCCOpcode == ISD::SETUEQ) {
7605        SDValue UNORD, EQ;
7606        UNORD = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(3, MVT::i8));
7607        EQ = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(0, MVT::i8));
7608        return DAG.getNode(ISD::OR, dl, VT, UNORD, EQ);
7609      }
7610      else if (SetCCOpcode == ISD::SETONE) {
7611        SDValue ORD, NEQ;
7612        ORD = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(7, MVT::i8));
7613        NEQ = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(4, MVT::i8));
7614        return DAG.getNode(ISD::AND, dl, VT, ORD, NEQ);
7615      }
7616      llvm_unreachable("Illegal FP comparison");
7617    }
7618    // Handle all other FP comparisons here.
7619    return DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(SSECC, MVT::i8));
7620  }
7621
7622  // We are handling one of the integer comparisons here.  Since SSE only has
7623  // GT and EQ comparisons for integer, swapping operands and multiple
7624  // operations may be required for some comparisons.
7625  unsigned Opc = 0, EQOpc = 0, GTOpc = 0;
7626  bool Swap = false, Invert = false, FlipSigns = false;
7627
7628  switch (VT.getSimpleVT().SimpleTy) {
7629  default: break;
7630  case MVT::v16i8: EQOpc = X86ISD::PCMPEQB; GTOpc = X86ISD::PCMPGTB; break;
7631  case MVT::v8i16: EQOpc = X86ISD::PCMPEQW; GTOpc = X86ISD::PCMPGTW; break;
7632  case MVT::v4i32: EQOpc = X86ISD::PCMPEQD; GTOpc = X86ISD::PCMPGTD; break;
7633  case MVT::v2i64: EQOpc = X86ISD::PCMPEQQ; GTOpc = X86ISD::PCMPGTQ; break;
7634  }
7635
7636  switch (SetCCOpcode) {
7637  default: break;
7638  case ISD::SETNE:  Invert = true;
7639  case ISD::SETEQ:  Opc = EQOpc; break;
7640  case ISD::SETLT:  Swap = true;
7641  case ISD::SETGT:  Opc = GTOpc; break;
7642  case ISD::SETGE:  Swap = true;
7643  case ISD::SETLE:  Opc = GTOpc; Invert = true; break;
7644  case ISD::SETULT: Swap = true;
7645  case ISD::SETUGT: Opc = GTOpc; FlipSigns = true; break;
7646  case ISD::SETUGE: Swap = true;
7647  case ISD::SETULE: Opc = GTOpc; FlipSigns = true; Invert = true; break;
7648  }
7649  if (Swap)
7650    std::swap(Op0, Op1);
7651
7652  // Since SSE has no unsigned integer comparisons, we need to flip  the sign
7653  // bits of the inputs before performing those operations.
7654  if (FlipSigns) {
7655    EVT EltVT = VT.getVectorElementType();
7656    SDValue SignBit = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()),
7657                                      EltVT);
7658    std::vector<SDValue> SignBits(VT.getVectorNumElements(), SignBit);
7659    SDValue SignVec = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &SignBits[0],
7660                                    SignBits.size());
7661    Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SignVec);
7662    Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SignVec);
7663  }
7664
7665  SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
7666
7667  // If the logical-not of the result is required, perform that now.
7668  if (Invert)
7669    Result = DAG.getNOT(dl, Result, VT);
7670
7671  return Result;
7672}
7673
7674// isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
7675static bool isX86LogicalCmp(SDValue Op) {
7676  unsigned Opc = Op.getNode()->getOpcode();
7677  if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI)
7678    return true;
7679  if (Op.getResNo() == 1 &&
7680      (Opc == X86ISD::ADD ||
7681       Opc == X86ISD::SUB ||
7682       Opc == X86ISD::ADC ||
7683       Opc == X86ISD::SBB ||
7684       Opc == X86ISD::SMUL ||
7685       Opc == X86ISD::UMUL ||
7686       Opc == X86ISD::INC ||
7687       Opc == X86ISD::DEC ||
7688       Opc == X86ISD::OR ||
7689       Opc == X86ISD::XOR ||
7690       Opc == X86ISD::AND))
7691    return true;
7692
7693  if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
7694    return true;
7695
7696  return false;
7697}
7698
7699static bool isZero(SDValue V) {
7700  ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
7701  return C && C->isNullValue();
7702}
7703
7704static bool isAllOnes(SDValue V) {
7705  ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
7706  return C && C->isAllOnesValue();
7707}
7708
7709SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
7710  bool addTest = true;
7711  SDValue Cond  = Op.getOperand(0);
7712  SDValue Op1 = Op.getOperand(1);
7713  SDValue Op2 = Op.getOperand(2);
7714  DebugLoc DL = Op.getDebugLoc();
7715  SDValue CC;
7716
7717  if (Cond.getOpcode() == ISD::SETCC) {
7718    SDValue NewCond = LowerSETCC(Cond, DAG);
7719    if (NewCond.getNode())
7720      Cond = NewCond;
7721  }
7722
7723  // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
7724  // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
7725  // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
7726  // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
7727  if (Cond.getOpcode() == X86ISD::SETCC &&
7728      Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
7729      isZero(Cond.getOperand(1).getOperand(1))) {
7730    SDValue Cmp = Cond.getOperand(1);
7731
7732    unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
7733
7734    if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
7735        (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
7736      SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
7737
7738      SDValue CmpOp0 = Cmp.getOperand(0);
7739      Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
7740                        CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
7741
7742      SDValue Res =   // Res = 0 or -1.
7743        DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
7744                    DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
7745
7746      if (isAllOnes(Op1) != (CondCode == X86::COND_E))
7747        Res = DAG.getNOT(DL, Res, Res.getValueType());
7748
7749      ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
7750      if (N2C == 0 || !N2C->isNullValue())
7751        Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
7752      return Res;
7753    }
7754  }
7755
7756  // Look past (and (setcc_carry (cmp ...)), 1).
7757  if (Cond.getOpcode() == ISD::AND &&
7758      Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
7759    ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
7760    if (C && C->getAPIntValue() == 1)
7761      Cond = Cond.getOperand(0);
7762  }
7763
7764  // If condition flag is set by a X86ISD::CMP, then use it as the condition
7765  // setting operand in place of the X86ISD::SETCC.
7766  if (Cond.getOpcode() == X86ISD::SETCC ||
7767      Cond.getOpcode() == X86ISD::SETCC_CARRY) {
7768    CC = Cond.getOperand(0);
7769
7770    SDValue Cmp = Cond.getOperand(1);
7771    unsigned Opc = Cmp.getOpcode();
7772    EVT VT = Op.getValueType();
7773
7774    bool IllegalFPCMov = false;
7775    if (VT.isFloatingPoint() && !VT.isVector() &&
7776        !isScalarFPTypeInSSEReg(VT))  // FPStack?
7777      IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
7778
7779    if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
7780        Opc == X86ISD::BT) { // FIXME
7781      Cond = Cmp;
7782      addTest = false;
7783    }
7784  }
7785
7786  if (addTest) {
7787    // Look pass the truncate.
7788    if (Cond.getOpcode() == ISD::TRUNCATE)
7789      Cond = Cond.getOperand(0);
7790
7791    // We know the result of AND is compared against zero. Try to match
7792    // it to BT.
7793    if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
7794      SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
7795      if (NewSetCC.getNode()) {
7796        CC = NewSetCC.getOperand(0);
7797        Cond = NewSetCC.getOperand(1);
7798        addTest = false;
7799      }
7800    }
7801  }
7802
7803  if (addTest) {
7804    CC = DAG.getConstant(X86::COND_NE, MVT::i8);
7805    Cond = EmitTest(Cond, X86::COND_NE, DAG);
7806  }
7807
7808  // a <  b ? -1 :  0 -> RES = ~setcc_carry
7809  // a <  b ?  0 : -1 -> RES = setcc_carry
7810  // a >= b ? -1 :  0 -> RES = setcc_carry
7811  // a >= b ?  0 : -1 -> RES = ~setcc_carry
7812  if (Cond.getOpcode() == X86ISD::CMP) {
7813    unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
7814
7815    if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
7816        (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
7817      SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
7818                                DAG.getConstant(X86::COND_B, MVT::i8), Cond);
7819      if (isAllOnes(Op1) != (CondCode == X86::COND_B))
7820        return DAG.getNOT(DL, Res, Res.getValueType());
7821      return Res;
7822    }
7823  }
7824
7825  // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
7826  // condition is true.
7827  SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
7828  SDValue Ops[] = { Op2, Op1, CC, Cond };
7829  return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops, array_lengthof(Ops));
7830}
7831
7832// isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
7833// ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
7834// from the AND / OR.
7835static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
7836  Opc = Op.getOpcode();
7837  if (Opc != ISD::OR && Opc != ISD::AND)
7838    return false;
7839  return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
7840          Op.getOperand(0).hasOneUse() &&
7841          Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
7842          Op.getOperand(1).hasOneUse());
7843}
7844
7845// isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
7846// 1 and that the SETCC node has a single use.
7847static bool isXor1OfSetCC(SDValue Op) {
7848  if (Op.getOpcode() != ISD::XOR)
7849    return false;
7850  ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
7851  if (N1C && N1C->getAPIntValue() == 1) {
7852    return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
7853      Op.getOperand(0).hasOneUse();
7854  }
7855  return false;
7856}
7857
7858SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
7859  bool addTest = true;
7860  SDValue Chain = Op.getOperand(0);
7861  SDValue Cond  = Op.getOperand(1);
7862  SDValue Dest  = Op.getOperand(2);
7863  DebugLoc dl = Op.getDebugLoc();
7864  SDValue CC;
7865
7866  if (Cond.getOpcode() == ISD::SETCC) {
7867    SDValue NewCond = LowerSETCC(Cond, DAG);
7868    if (NewCond.getNode())
7869      Cond = NewCond;
7870  }
7871#if 0
7872  // FIXME: LowerXALUO doesn't handle these!!
7873  else if (Cond.getOpcode() == X86ISD::ADD  ||
7874           Cond.getOpcode() == X86ISD::SUB  ||
7875           Cond.getOpcode() == X86ISD::SMUL ||
7876           Cond.getOpcode() == X86ISD::UMUL)
7877    Cond = LowerXALUO(Cond, DAG);
7878#endif
7879
7880  // Look pass (and (setcc_carry (cmp ...)), 1).
7881  if (Cond.getOpcode() == ISD::AND &&
7882      Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
7883    ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
7884    if (C && C->getAPIntValue() == 1)
7885      Cond = Cond.getOperand(0);
7886  }
7887
7888  // If condition flag is set by a X86ISD::CMP, then use it as the condition
7889  // setting operand in place of the X86ISD::SETCC.
7890  if (Cond.getOpcode() == X86ISD::SETCC ||
7891      Cond.getOpcode() == X86ISD::SETCC_CARRY) {
7892    CC = Cond.getOperand(0);
7893
7894    SDValue Cmp = Cond.getOperand(1);
7895    unsigned Opc = Cmp.getOpcode();
7896    // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
7897    if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
7898      Cond = Cmp;
7899      addTest = false;
7900    } else {
7901      switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
7902      default: break;
7903      case X86::COND_O:
7904      case X86::COND_B:
7905        // These can only come from an arithmetic instruction with overflow,
7906        // e.g. SADDO, UADDO.
7907        Cond = Cond.getNode()->getOperand(1);
7908        addTest = false;
7909        break;
7910      }
7911    }
7912  } else {
7913    unsigned CondOpc;
7914    if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
7915      SDValue Cmp = Cond.getOperand(0).getOperand(1);
7916      if (CondOpc == ISD::OR) {
7917        // Also, recognize the pattern generated by an FCMP_UNE. We can emit
7918        // two branches instead of an explicit OR instruction with a
7919        // separate test.
7920        if (Cmp == Cond.getOperand(1).getOperand(1) &&
7921            isX86LogicalCmp(Cmp)) {
7922          CC = Cond.getOperand(0).getOperand(0);
7923          Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
7924                              Chain, Dest, CC, Cmp);
7925          CC = Cond.getOperand(1).getOperand(0);
7926          Cond = Cmp;
7927          addTest = false;
7928        }
7929      } else { // ISD::AND
7930        // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
7931        // two branches instead of an explicit AND instruction with a
7932        // separate test. However, we only do this if this block doesn't
7933        // have a fall-through edge, because this requires an explicit
7934        // jmp when the condition is false.
7935        if (Cmp == Cond.getOperand(1).getOperand(1) &&
7936            isX86LogicalCmp(Cmp) &&
7937            Op.getNode()->hasOneUse()) {
7938          X86::CondCode CCode =
7939            (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
7940          CCode = X86::GetOppositeBranchCondition(CCode);
7941          CC = DAG.getConstant(CCode, MVT::i8);
7942          SDNode *User = *Op.getNode()->use_begin();
7943          // Look for an unconditional branch following this conditional branch.
7944          // We need this because we need to reverse the successors in order
7945          // to implement FCMP_OEQ.
7946          if (User->getOpcode() == ISD::BR) {
7947            SDValue FalseBB = User->getOperand(1);
7948            SDNode *NewBR =
7949              DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
7950            assert(NewBR == User);
7951            (void)NewBR;
7952            Dest = FalseBB;
7953
7954            Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
7955                                Chain, Dest, CC, Cmp);
7956            X86::CondCode CCode =
7957              (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
7958            CCode = X86::GetOppositeBranchCondition(CCode);
7959            CC = DAG.getConstant(CCode, MVT::i8);
7960            Cond = Cmp;
7961            addTest = false;
7962          }
7963        }
7964      }
7965    } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
7966      // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
7967      // It should be transformed during dag combiner except when the condition
7968      // is set by a arithmetics with overflow node.
7969      X86::CondCode CCode =
7970        (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
7971      CCode = X86::GetOppositeBranchCondition(CCode);
7972      CC = DAG.getConstant(CCode, MVT::i8);
7973      Cond = Cond.getOperand(0).getOperand(1);
7974      addTest = false;
7975    }
7976  }
7977
7978  if (addTest) {
7979    // Look pass the truncate.
7980    if (Cond.getOpcode() == ISD::TRUNCATE)
7981      Cond = Cond.getOperand(0);
7982
7983    // We know the result of AND is compared against zero. Try to match
7984    // it to BT.
7985    if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
7986      SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
7987      if (NewSetCC.getNode()) {
7988        CC = NewSetCC.getOperand(0);
7989        Cond = NewSetCC.getOperand(1);
7990        addTest = false;
7991      }
7992    }
7993  }
7994
7995  if (addTest) {
7996    CC = DAG.getConstant(X86::COND_NE, MVT::i8);
7997    Cond = EmitTest(Cond, X86::COND_NE, DAG);
7998  }
7999  return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
8000                     Chain, Dest, CC, Cond);
8001}
8002
8003
8004// Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
8005// Calls to _alloca is needed to probe the stack when allocating more than 4k
8006// bytes in one go. Touching the stack at 4K increments is necessary to ensure
8007// that the guard pages used by the OS virtual memory manager are allocated in
8008// correct sequence.
8009SDValue
8010X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
8011                                           SelectionDAG &DAG) const {
8012  assert((Subtarget->isTargetCygMing() || Subtarget->isTargetWindows()) &&
8013         "This should be used only on Windows targets");
8014  assert(!Subtarget->isTargetEnvMacho());
8015  DebugLoc dl = Op.getDebugLoc();
8016
8017  // Get the inputs.
8018  SDValue Chain = Op.getOperand(0);
8019  SDValue Size  = Op.getOperand(1);
8020  // FIXME: Ensure alignment here
8021
8022  SDValue Flag;
8023
8024  EVT SPTy = Subtarget->is64Bit() ? MVT::i64 : MVT::i32;
8025  unsigned Reg = (Subtarget->is64Bit() ? X86::RAX : X86::EAX);
8026
8027  Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
8028  Flag = Chain.getValue(1);
8029
8030  SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
8031
8032  Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
8033  Flag = Chain.getValue(1);
8034
8035  Chain = DAG.getCopyFromReg(Chain, dl, X86StackPtr, SPTy).getValue(1);
8036
8037  SDValue Ops1[2] = { Chain.getValue(0), Chain };
8038  return DAG.getMergeValues(Ops1, 2, dl);
8039}
8040
8041SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
8042  MachineFunction &MF = DAG.getMachineFunction();
8043  X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
8044
8045  const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
8046  DebugLoc DL = Op.getDebugLoc();
8047
8048  if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
8049    // vastart just stores the address of the VarArgsFrameIndex slot into the
8050    // memory location argument.
8051    SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
8052                                   getPointerTy());
8053    return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
8054                        MachinePointerInfo(SV), false, false, 0);
8055  }
8056
8057  // __va_list_tag:
8058  //   gp_offset         (0 - 6 * 8)
8059  //   fp_offset         (48 - 48 + 8 * 16)
8060  //   overflow_arg_area (point to parameters coming in memory).
8061  //   reg_save_area
8062  SmallVector<SDValue, 8> MemOps;
8063  SDValue FIN = Op.getOperand(1);
8064  // Store gp_offset
8065  SDValue Store = DAG.getStore(Op.getOperand(0), DL,
8066                               DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
8067                                               MVT::i32),
8068                               FIN, MachinePointerInfo(SV), false, false, 0);
8069  MemOps.push_back(Store);
8070
8071  // Store fp_offset
8072  FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
8073                    FIN, DAG.getIntPtrConstant(4));
8074  Store = DAG.getStore(Op.getOperand(0), DL,
8075                       DAG.getConstant(FuncInfo->getVarArgsFPOffset(),
8076                                       MVT::i32),
8077                       FIN, MachinePointerInfo(SV, 4), false, false, 0);
8078  MemOps.push_back(Store);
8079
8080  // Store ptr to overflow_arg_area
8081  FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
8082                    FIN, DAG.getIntPtrConstant(4));
8083  SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
8084                                    getPointerTy());
8085  Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
8086                       MachinePointerInfo(SV, 8),
8087                       false, false, 0);
8088  MemOps.push_back(Store);
8089
8090  // Store ptr to reg_save_area.
8091  FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
8092                    FIN, DAG.getIntPtrConstant(8));
8093  SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
8094                                    getPointerTy());
8095  Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
8096                       MachinePointerInfo(SV, 16), false, false, 0);
8097  MemOps.push_back(Store);
8098  return DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
8099                     &MemOps[0], MemOps.size());
8100}
8101
8102SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
8103  assert(Subtarget->is64Bit() &&
8104         "LowerVAARG only handles 64-bit va_arg!");
8105  assert((Subtarget->isTargetLinux() ||
8106          Subtarget->isTargetDarwin()) &&
8107          "Unhandled target in LowerVAARG");
8108  assert(Op.getNode()->getNumOperands() == 4);
8109  SDValue Chain = Op.getOperand(0);
8110  SDValue SrcPtr = Op.getOperand(1);
8111  const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
8112  unsigned Align = Op.getConstantOperandVal(3);
8113  DebugLoc dl = Op.getDebugLoc();
8114
8115  EVT ArgVT = Op.getNode()->getValueType(0);
8116  const Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
8117  uint32_t ArgSize = getTargetData()->getTypeAllocSize(ArgTy);
8118  uint8_t ArgMode;
8119
8120  // Decide which area this value should be read from.
8121  // TODO: Implement the AMD64 ABI in its entirety. This simple
8122  // selection mechanism works only for the basic types.
8123  if (ArgVT == MVT::f80) {
8124    llvm_unreachable("va_arg for f80 not yet implemented");
8125  } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
8126    ArgMode = 2;  // Argument passed in XMM register. Use fp_offset.
8127  } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
8128    ArgMode = 1;  // Argument passed in GPR64 register(s). Use gp_offset.
8129  } else {
8130    llvm_unreachable("Unhandled argument type in LowerVAARG");
8131  }
8132
8133  if (ArgMode == 2) {
8134    // Sanity Check: Make sure using fp_offset makes sense.
8135    assert(!UseSoftFloat &&
8136           !(DAG.getMachineFunction()
8137                .getFunction()->hasFnAttr(Attribute::NoImplicitFloat)) &&
8138           Subtarget->hasXMM());
8139  }
8140
8141  // Insert VAARG_64 node into the DAG
8142  // VAARG_64 returns two values: Variable Argument Address, Chain
8143  SmallVector<SDValue, 11> InstOps;
8144  InstOps.push_back(Chain);
8145  InstOps.push_back(SrcPtr);
8146  InstOps.push_back(DAG.getConstant(ArgSize, MVT::i32));
8147  InstOps.push_back(DAG.getConstant(ArgMode, MVT::i8));
8148  InstOps.push_back(DAG.getConstant(Align, MVT::i32));
8149  SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other);
8150  SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
8151                                          VTs, &InstOps[0], InstOps.size(),
8152                                          MVT::i64,
8153                                          MachinePointerInfo(SV),
8154                                          /*Align=*/0,
8155                                          /*Volatile=*/false,
8156                                          /*ReadMem=*/true,
8157                                          /*WriteMem=*/true);
8158  Chain = VAARG.getValue(1);
8159
8160  // Load the next argument and return it
8161  return DAG.getLoad(ArgVT, dl,
8162                     Chain,
8163                     VAARG,
8164                     MachinePointerInfo(),
8165                     false, false, 0);
8166}
8167
8168SDValue X86TargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) const {
8169  // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
8170  assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
8171  SDValue Chain = Op.getOperand(0);
8172  SDValue DstPtr = Op.getOperand(1);
8173  SDValue SrcPtr = Op.getOperand(2);
8174  const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
8175  const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
8176  DebugLoc DL = Op.getDebugLoc();
8177
8178  return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
8179                       DAG.getIntPtrConstant(24), 8, /*isVolatile*/false,
8180                       false,
8181                       MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
8182}
8183
8184SDValue
8185X86TargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) const {
8186  DebugLoc dl = Op.getDebugLoc();
8187  unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
8188  switch (IntNo) {
8189  default: return SDValue();    // Don't custom lower most intrinsics.
8190  // Comparison intrinsics.
8191  case Intrinsic::x86_sse_comieq_ss:
8192  case Intrinsic::x86_sse_comilt_ss:
8193  case Intrinsic::x86_sse_comile_ss:
8194  case Intrinsic::x86_sse_comigt_ss:
8195  case Intrinsic::x86_sse_comige_ss:
8196  case Intrinsic::x86_sse_comineq_ss:
8197  case Intrinsic::x86_sse_ucomieq_ss:
8198  case Intrinsic::x86_sse_ucomilt_ss:
8199  case Intrinsic::x86_sse_ucomile_ss:
8200  case Intrinsic::x86_sse_ucomigt_ss:
8201  case Intrinsic::x86_sse_ucomige_ss:
8202  case Intrinsic::x86_sse_ucomineq_ss:
8203  case Intrinsic::x86_sse2_comieq_sd:
8204  case Intrinsic::x86_sse2_comilt_sd:
8205  case Intrinsic::x86_sse2_comile_sd:
8206  case Intrinsic::x86_sse2_comigt_sd:
8207  case Intrinsic::x86_sse2_comige_sd:
8208  case Intrinsic::x86_sse2_comineq_sd:
8209  case Intrinsic::x86_sse2_ucomieq_sd:
8210  case Intrinsic::x86_sse2_ucomilt_sd:
8211  case Intrinsic::x86_sse2_ucomile_sd:
8212  case Intrinsic::x86_sse2_ucomigt_sd:
8213  case Intrinsic::x86_sse2_ucomige_sd:
8214  case Intrinsic::x86_sse2_ucomineq_sd: {
8215    unsigned Opc = 0;
8216    ISD::CondCode CC = ISD::SETCC_INVALID;
8217    switch (IntNo) {
8218    default: break;
8219    case Intrinsic::x86_sse_comieq_ss:
8220    case Intrinsic::x86_sse2_comieq_sd:
8221      Opc = X86ISD::COMI;
8222      CC = ISD::SETEQ;
8223      break;
8224    case Intrinsic::x86_sse_comilt_ss:
8225    case Intrinsic::x86_sse2_comilt_sd:
8226      Opc = X86ISD::COMI;
8227      CC = ISD::SETLT;
8228      break;
8229    case Intrinsic::x86_sse_comile_ss:
8230    case Intrinsic::x86_sse2_comile_sd:
8231      Opc = X86ISD::COMI;
8232      CC = ISD::SETLE;
8233      break;
8234    case Intrinsic::x86_sse_comigt_ss:
8235    case Intrinsic::x86_sse2_comigt_sd:
8236      Opc = X86ISD::COMI;
8237      CC = ISD::SETGT;
8238      break;
8239    case Intrinsic::x86_sse_comige_ss:
8240    case Intrinsic::x86_sse2_comige_sd:
8241      Opc = X86ISD::COMI;
8242      CC = ISD::SETGE;
8243      break;
8244    case Intrinsic::x86_sse_comineq_ss:
8245    case Intrinsic::x86_sse2_comineq_sd:
8246      Opc = X86ISD::COMI;
8247      CC = ISD::SETNE;
8248      break;
8249    case Intrinsic::x86_sse_ucomieq_ss:
8250    case Intrinsic::x86_sse2_ucomieq_sd:
8251      Opc = X86ISD::UCOMI;
8252      CC = ISD::SETEQ;
8253      break;
8254    case Intrinsic::x86_sse_ucomilt_ss:
8255    case Intrinsic::x86_sse2_ucomilt_sd:
8256      Opc = X86ISD::UCOMI;
8257      CC = ISD::SETLT;
8258      break;
8259    case Intrinsic::x86_sse_ucomile_ss:
8260    case Intrinsic::x86_sse2_ucomile_sd:
8261      Opc = X86ISD::UCOMI;
8262      CC = ISD::SETLE;
8263      break;
8264    case Intrinsic::x86_sse_ucomigt_ss:
8265    case Intrinsic::x86_sse2_ucomigt_sd:
8266      Opc = X86ISD::UCOMI;
8267      CC = ISD::SETGT;
8268      break;
8269    case Intrinsic::x86_sse_ucomige_ss:
8270    case Intrinsic::x86_sse2_ucomige_sd:
8271      Opc = X86ISD::UCOMI;
8272      CC = ISD::SETGE;
8273      break;
8274    case Intrinsic::x86_sse_ucomineq_ss:
8275    case Intrinsic::x86_sse2_ucomineq_sd:
8276      Opc = X86ISD::UCOMI;
8277      CC = ISD::SETNE;
8278      break;
8279    }
8280
8281    SDValue LHS = Op.getOperand(1);
8282    SDValue RHS = Op.getOperand(2);
8283    unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
8284    assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
8285    SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS);
8286    SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
8287                                DAG.getConstant(X86CC, MVT::i8), Cond);
8288    return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
8289  }
8290  // ptest and testp intrinsics. The intrinsic these come from are designed to
8291  // return an integer value, not just an instruction so lower it to the ptest
8292  // or testp pattern and a setcc for the result.
8293  case Intrinsic::x86_sse41_ptestz:
8294  case Intrinsic::x86_sse41_ptestc:
8295  case Intrinsic::x86_sse41_ptestnzc:
8296  case Intrinsic::x86_avx_ptestz_256:
8297  case Intrinsic::x86_avx_ptestc_256:
8298  case Intrinsic::x86_avx_ptestnzc_256:
8299  case Intrinsic::x86_avx_vtestz_ps:
8300  case Intrinsic::x86_avx_vtestc_ps:
8301  case Intrinsic::x86_avx_vtestnzc_ps:
8302  case Intrinsic::x86_avx_vtestz_pd:
8303  case Intrinsic::x86_avx_vtestc_pd:
8304  case Intrinsic::x86_avx_vtestnzc_pd:
8305  case Intrinsic::x86_avx_vtestz_ps_256:
8306  case Intrinsic::x86_avx_vtestc_ps_256:
8307  case Intrinsic::x86_avx_vtestnzc_ps_256:
8308  case Intrinsic::x86_avx_vtestz_pd_256:
8309  case Intrinsic::x86_avx_vtestc_pd_256:
8310  case Intrinsic::x86_avx_vtestnzc_pd_256: {
8311    bool IsTestPacked = false;
8312    unsigned X86CC = 0;
8313    switch (IntNo) {
8314    default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
8315    case Intrinsic::x86_avx_vtestz_ps:
8316    case Intrinsic::x86_avx_vtestz_pd:
8317    case Intrinsic::x86_avx_vtestz_ps_256:
8318    case Intrinsic::x86_avx_vtestz_pd_256:
8319      IsTestPacked = true; // Fallthrough
8320    case Intrinsic::x86_sse41_ptestz:
8321    case Intrinsic::x86_avx_ptestz_256:
8322      // ZF = 1
8323      X86CC = X86::COND_E;
8324      break;
8325    case Intrinsic::x86_avx_vtestc_ps:
8326    case Intrinsic::x86_avx_vtestc_pd:
8327    case Intrinsic::x86_avx_vtestc_ps_256:
8328    case Intrinsic::x86_avx_vtestc_pd_256:
8329      IsTestPacked = true; // Fallthrough
8330    case Intrinsic::x86_sse41_ptestc:
8331    case Intrinsic::x86_avx_ptestc_256:
8332      // CF = 1
8333      X86CC = X86::COND_B;
8334      break;
8335    case Intrinsic::x86_avx_vtestnzc_ps:
8336    case Intrinsic::x86_avx_vtestnzc_pd:
8337    case Intrinsic::x86_avx_vtestnzc_ps_256:
8338    case Intrinsic::x86_avx_vtestnzc_pd_256:
8339      IsTestPacked = true; // Fallthrough
8340    case Intrinsic::x86_sse41_ptestnzc:
8341    case Intrinsic::x86_avx_ptestnzc_256:
8342      // ZF and CF = 0
8343      X86CC = X86::COND_A;
8344      break;
8345    }
8346
8347    SDValue LHS = Op.getOperand(1);
8348    SDValue RHS = Op.getOperand(2);
8349    unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
8350    SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
8351    SDValue CC = DAG.getConstant(X86CC, MVT::i8);
8352    SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
8353    return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
8354  }
8355
8356  // Fix vector shift instructions where the last operand is a non-immediate
8357  // i32 value.
8358  case Intrinsic::x86_sse2_pslli_w:
8359  case Intrinsic::x86_sse2_pslli_d:
8360  case Intrinsic::x86_sse2_pslli_q:
8361  case Intrinsic::x86_sse2_psrli_w:
8362  case Intrinsic::x86_sse2_psrli_d:
8363  case Intrinsic::x86_sse2_psrli_q:
8364  case Intrinsic::x86_sse2_psrai_w:
8365  case Intrinsic::x86_sse2_psrai_d:
8366  case Intrinsic::x86_mmx_pslli_w:
8367  case Intrinsic::x86_mmx_pslli_d:
8368  case Intrinsic::x86_mmx_pslli_q:
8369  case Intrinsic::x86_mmx_psrli_w:
8370  case Intrinsic::x86_mmx_psrli_d:
8371  case Intrinsic::x86_mmx_psrli_q:
8372  case Intrinsic::x86_mmx_psrai_w:
8373  case Intrinsic::x86_mmx_psrai_d: {
8374    SDValue ShAmt = Op.getOperand(2);
8375    if (isa<ConstantSDNode>(ShAmt))
8376      return SDValue();
8377
8378    unsigned NewIntNo = 0;
8379    EVT ShAmtVT = MVT::v4i32;
8380    switch (IntNo) {
8381    case Intrinsic::x86_sse2_pslli_w:
8382      NewIntNo = Intrinsic::x86_sse2_psll_w;
8383      break;
8384    case Intrinsic::x86_sse2_pslli_d:
8385      NewIntNo = Intrinsic::x86_sse2_psll_d;
8386      break;
8387    case Intrinsic::x86_sse2_pslli_q:
8388      NewIntNo = Intrinsic::x86_sse2_psll_q;
8389      break;
8390    case Intrinsic::x86_sse2_psrli_w:
8391      NewIntNo = Intrinsic::x86_sse2_psrl_w;
8392      break;
8393    case Intrinsic::x86_sse2_psrli_d:
8394      NewIntNo = Intrinsic::x86_sse2_psrl_d;
8395      break;
8396    case Intrinsic::x86_sse2_psrli_q:
8397      NewIntNo = Intrinsic::x86_sse2_psrl_q;
8398      break;
8399    case Intrinsic::x86_sse2_psrai_w:
8400      NewIntNo = Intrinsic::x86_sse2_psra_w;
8401      break;
8402    case Intrinsic::x86_sse2_psrai_d:
8403      NewIntNo = Intrinsic::x86_sse2_psra_d;
8404      break;
8405    default: {
8406      ShAmtVT = MVT::v2i32;
8407      switch (IntNo) {
8408      case Intrinsic::x86_mmx_pslli_w:
8409        NewIntNo = Intrinsic::x86_mmx_psll_w;
8410        break;
8411      case Intrinsic::x86_mmx_pslli_d:
8412        NewIntNo = Intrinsic::x86_mmx_psll_d;
8413        break;
8414      case Intrinsic::x86_mmx_pslli_q:
8415        NewIntNo = Intrinsic::x86_mmx_psll_q;
8416        break;
8417      case Intrinsic::x86_mmx_psrli_w:
8418        NewIntNo = Intrinsic::x86_mmx_psrl_w;
8419        break;
8420      case Intrinsic::x86_mmx_psrli_d:
8421        NewIntNo = Intrinsic::x86_mmx_psrl_d;
8422        break;
8423      case Intrinsic::x86_mmx_psrli_q:
8424        NewIntNo = Intrinsic::x86_mmx_psrl_q;
8425        break;
8426      case Intrinsic::x86_mmx_psrai_w:
8427        NewIntNo = Intrinsic::x86_mmx_psra_w;
8428        break;
8429      case Intrinsic::x86_mmx_psrai_d:
8430        NewIntNo = Intrinsic::x86_mmx_psra_d;
8431        break;
8432      default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
8433      }
8434      break;
8435    }
8436    }
8437
8438    // The vector shift intrinsics with scalars uses 32b shift amounts but
8439    // the sse2/mmx shift instructions reads 64 bits. Set the upper 32 bits
8440    // to be zero.
8441    SDValue ShOps[4];
8442    ShOps[0] = ShAmt;
8443    ShOps[1] = DAG.getConstant(0, MVT::i32);
8444    if (ShAmtVT == MVT::v4i32) {
8445      ShOps[2] = DAG.getUNDEF(MVT::i32);
8446      ShOps[3] = DAG.getUNDEF(MVT::i32);
8447      ShAmt =  DAG.getNode(ISD::BUILD_VECTOR, dl, ShAmtVT, &ShOps[0], 4);
8448    } else {
8449      ShAmt =  DAG.getNode(ISD::BUILD_VECTOR, dl, ShAmtVT, &ShOps[0], 2);
8450// FIXME this must be lowered to get rid of the invalid type.
8451    }
8452
8453    EVT VT = Op.getValueType();
8454    ShAmt = DAG.getNode(ISD::BITCAST, dl, VT, ShAmt);
8455    return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8456                       DAG.getConstant(NewIntNo, MVT::i32),
8457                       Op.getOperand(1), ShAmt);
8458  }
8459  }
8460}
8461
8462SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
8463                                           SelectionDAG &DAG) const {
8464  MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
8465  MFI->setReturnAddressIsTaken(true);
8466
8467  unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
8468  DebugLoc dl = Op.getDebugLoc();
8469
8470  if (Depth > 0) {
8471    SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
8472    SDValue Offset =
8473      DAG.getConstant(TD->getPointerSize(),
8474                      Subtarget->is64Bit() ? MVT::i64 : MVT::i32);
8475    return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
8476                       DAG.getNode(ISD::ADD, dl, getPointerTy(),
8477                                   FrameAddr, Offset),
8478                       MachinePointerInfo(), false, false, 0);
8479  }
8480
8481  // Just load the return address.
8482  SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
8483  return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
8484                     RetAddrFI, MachinePointerInfo(), false, false, 0);
8485}
8486
8487SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
8488  MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
8489  MFI->setFrameAddressIsTaken(true);
8490
8491  EVT VT = Op.getValueType();
8492  DebugLoc dl = Op.getDebugLoc();  // FIXME probably not meaningful
8493  unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
8494  unsigned FrameReg = Subtarget->is64Bit() ? X86::RBP : X86::EBP;
8495  SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
8496  while (Depth--)
8497    FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
8498                            MachinePointerInfo(),
8499                            false, false, 0);
8500  return FrameAddr;
8501}
8502
8503SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
8504                                                     SelectionDAG &DAG) const {
8505  return DAG.getIntPtrConstant(2*TD->getPointerSize());
8506}
8507
8508SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
8509  MachineFunction &MF = DAG.getMachineFunction();
8510  SDValue Chain     = Op.getOperand(0);
8511  SDValue Offset    = Op.getOperand(1);
8512  SDValue Handler   = Op.getOperand(2);
8513  DebugLoc dl       = Op.getDebugLoc();
8514
8515  SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl,
8516                                     Subtarget->is64Bit() ? X86::RBP : X86::EBP,
8517                                     getPointerTy());
8518  unsigned StoreAddrReg = (Subtarget->is64Bit() ? X86::RCX : X86::ECX);
8519
8520  SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), Frame,
8521                                  DAG.getIntPtrConstant(TD->getPointerSize()));
8522  StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), StoreAddr, Offset);
8523  Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
8524                       false, false, 0);
8525  Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
8526  MF.getRegInfo().addLiveOut(StoreAddrReg);
8527
8528  return DAG.getNode(X86ISD::EH_RETURN, dl,
8529                     MVT::Other,
8530                     Chain, DAG.getRegister(StoreAddrReg, getPointerTy()));
8531}
8532
8533SDValue X86TargetLowering::LowerTRAMPOLINE(SDValue Op,
8534                                             SelectionDAG &DAG) const {
8535  SDValue Root = Op.getOperand(0);
8536  SDValue Trmp = Op.getOperand(1); // trampoline
8537  SDValue FPtr = Op.getOperand(2); // nested function
8538  SDValue Nest = Op.getOperand(3); // 'nest' parameter value
8539  DebugLoc dl  = Op.getDebugLoc();
8540
8541  const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
8542
8543  if (Subtarget->is64Bit()) {
8544    SDValue OutChains[6];
8545
8546    // Large code-model.
8547    const unsigned char JMP64r  = 0xFF; // 64-bit jmp through register opcode.
8548    const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
8549
8550    const unsigned char N86R10 = RegInfo->getX86RegNum(X86::R10);
8551    const unsigned char N86R11 = RegInfo->getX86RegNum(X86::R11);
8552
8553    const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
8554
8555    // Load the pointer to the nested function into R11.
8556    unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
8557    SDValue Addr = Trmp;
8558    OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
8559                                Addr, MachinePointerInfo(TrmpAddr),
8560                                false, false, 0);
8561
8562    Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
8563                       DAG.getConstant(2, MVT::i64));
8564    OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
8565                                MachinePointerInfo(TrmpAddr, 2),
8566                                false, false, 2);
8567
8568    // Load the 'nest' parameter value into R10.
8569    // R10 is specified in X86CallingConv.td
8570    OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
8571    Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
8572                       DAG.getConstant(10, MVT::i64));
8573    OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
8574                                Addr, MachinePointerInfo(TrmpAddr, 10),
8575                                false, false, 0);
8576
8577    Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
8578                       DAG.getConstant(12, MVT::i64));
8579    OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
8580                                MachinePointerInfo(TrmpAddr, 12),
8581                                false, false, 2);
8582
8583    // Jump to the nested function.
8584    OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
8585    Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
8586                       DAG.getConstant(20, MVT::i64));
8587    OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
8588                                Addr, MachinePointerInfo(TrmpAddr, 20),
8589                                false, false, 0);
8590
8591    unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
8592    Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
8593                       DAG.getConstant(22, MVT::i64));
8594    OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
8595                                MachinePointerInfo(TrmpAddr, 22),
8596                                false, false, 0);
8597
8598    SDValue Ops[] =
8599      { Trmp, DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 6) };
8600    return DAG.getMergeValues(Ops, 2, dl);
8601  } else {
8602    const Function *Func =
8603      cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
8604    CallingConv::ID CC = Func->getCallingConv();
8605    unsigned NestReg;
8606
8607    switch (CC) {
8608    default:
8609      llvm_unreachable("Unsupported calling convention");
8610    case CallingConv::C:
8611    case CallingConv::X86_StdCall: {
8612      // Pass 'nest' parameter in ECX.
8613      // Must be kept in sync with X86CallingConv.td
8614      NestReg = X86::ECX;
8615
8616      // Check that ECX wasn't needed by an 'inreg' parameter.
8617      const FunctionType *FTy = Func->getFunctionType();
8618      const AttrListPtr &Attrs = Func->getAttributes();
8619
8620      if (!Attrs.isEmpty() && !Func->isVarArg()) {
8621        unsigned InRegCount = 0;
8622        unsigned Idx = 1;
8623
8624        for (FunctionType::param_iterator I = FTy->param_begin(),
8625             E = FTy->param_end(); I != E; ++I, ++Idx)
8626          if (Attrs.paramHasAttr(Idx, Attribute::InReg))
8627            // FIXME: should only count parameters that are lowered to integers.
8628            InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
8629
8630        if (InRegCount > 2) {
8631          report_fatal_error("Nest register in use - reduce number of inreg"
8632                             " parameters!");
8633        }
8634      }
8635      break;
8636    }
8637    case CallingConv::X86_FastCall:
8638    case CallingConv::X86_ThisCall:
8639    case CallingConv::Fast:
8640      // Pass 'nest' parameter in EAX.
8641      // Must be kept in sync with X86CallingConv.td
8642      NestReg = X86::EAX;
8643      break;
8644    }
8645
8646    SDValue OutChains[4];
8647    SDValue Addr, Disp;
8648
8649    Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
8650                       DAG.getConstant(10, MVT::i32));
8651    Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
8652
8653    // This is storing the opcode for MOV32ri.
8654    const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
8655    const unsigned char N86Reg = RegInfo->getX86RegNum(NestReg);
8656    OutChains[0] = DAG.getStore(Root, dl,
8657                                DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
8658                                Trmp, MachinePointerInfo(TrmpAddr),
8659                                false, false, 0);
8660
8661    Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
8662                       DAG.getConstant(1, MVT::i32));
8663    OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
8664                                MachinePointerInfo(TrmpAddr, 1),
8665                                false, false, 1);
8666
8667    const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
8668    Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
8669                       DAG.getConstant(5, MVT::i32));
8670    OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
8671                                MachinePointerInfo(TrmpAddr, 5),
8672                                false, false, 1);
8673
8674    Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
8675                       DAG.getConstant(6, MVT::i32));
8676    OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
8677                                MachinePointerInfo(TrmpAddr, 6),
8678                                false, false, 1);
8679
8680    SDValue Ops[] =
8681      { Trmp, DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 4) };
8682    return DAG.getMergeValues(Ops, 2, dl);
8683  }
8684}
8685
8686SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
8687                                            SelectionDAG &DAG) const {
8688  /*
8689   The rounding mode is in bits 11:10 of FPSR, and has the following
8690   settings:
8691     00 Round to nearest
8692     01 Round to -inf
8693     10 Round to +inf
8694     11 Round to 0
8695
8696  FLT_ROUNDS, on the other hand, expects the following:
8697    -1 Undefined
8698     0 Round to 0
8699     1 Round to nearest
8700     2 Round to +inf
8701     3 Round to -inf
8702
8703  To perform the conversion, we do:
8704    (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
8705  */
8706
8707  MachineFunction &MF = DAG.getMachineFunction();
8708  const TargetMachine &TM = MF.getTarget();
8709  const TargetFrameLowering &TFI = *TM.getFrameLowering();
8710  unsigned StackAlignment = TFI.getStackAlignment();
8711  EVT VT = Op.getValueType();
8712  DebugLoc DL = Op.getDebugLoc();
8713
8714  // Save FP Control Word to stack slot
8715  int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
8716  SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8717
8718
8719  MachineMemOperand *MMO =
8720   MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8721                           MachineMemOperand::MOStore, 2, 2);
8722
8723  SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
8724  SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
8725                                          DAG.getVTList(MVT::Other),
8726                                          Ops, 2, MVT::i16, MMO);
8727
8728  // Load FP Control Word from stack slot
8729  SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
8730                            MachinePointerInfo(), false, false, 0);
8731
8732  // Transform as necessary
8733  SDValue CWD1 =
8734    DAG.getNode(ISD::SRL, DL, MVT::i16,
8735                DAG.getNode(ISD::AND, DL, MVT::i16,
8736                            CWD, DAG.getConstant(0x800, MVT::i16)),
8737                DAG.getConstant(11, MVT::i8));
8738  SDValue CWD2 =
8739    DAG.getNode(ISD::SRL, DL, MVT::i16,
8740                DAG.getNode(ISD::AND, DL, MVT::i16,
8741                            CWD, DAG.getConstant(0x400, MVT::i16)),
8742                DAG.getConstant(9, MVT::i8));
8743
8744  SDValue RetVal =
8745    DAG.getNode(ISD::AND, DL, MVT::i16,
8746                DAG.getNode(ISD::ADD, DL, MVT::i16,
8747                            DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
8748                            DAG.getConstant(1, MVT::i16)),
8749                DAG.getConstant(3, MVT::i16));
8750
8751
8752  return DAG.getNode((VT.getSizeInBits() < 16 ?
8753                      ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
8754}
8755
8756SDValue X86TargetLowering::LowerCTLZ(SDValue Op, SelectionDAG &DAG) const {
8757  EVT VT = Op.getValueType();
8758  EVT OpVT = VT;
8759  unsigned NumBits = VT.getSizeInBits();
8760  DebugLoc dl = Op.getDebugLoc();
8761
8762  Op = Op.getOperand(0);
8763  if (VT == MVT::i8) {
8764    // Zero extend to i32 since there is not an i8 bsr.
8765    OpVT = MVT::i32;
8766    Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
8767  }
8768
8769  // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
8770  SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
8771  Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
8772
8773  // If src is zero (i.e. bsr sets ZF), returns NumBits.
8774  SDValue Ops[] = {
8775    Op,
8776    DAG.getConstant(NumBits+NumBits-1, OpVT),
8777    DAG.getConstant(X86::COND_E, MVT::i8),
8778    Op.getValue(1)
8779  };
8780  Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
8781
8782  // Finally xor with NumBits-1.
8783  Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
8784
8785  if (VT == MVT::i8)
8786    Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
8787  return Op;
8788}
8789
8790SDValue X86TargetLowering::LowerCTTZ(SDValue Op, SelectionDAG &DAG) const {
8791  EVT VT = Op.getValueType();
8792  EVT OpVT = VT;
8793  unsigned NumBits = VT.getSizeInBits();
8794  DebugLoc dl = Op.getDebugLoc();
8795
8796  Op = Op.getOperand(0);
8797  if (VT == MVT::i8) {
8798    OpVT = MVT::i32;
8799    Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
8800  }
8801
8802  // Issue a bsf (scan bits forward) which also sets EFLAGS.
8803  SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
8804  Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
8805
8806  // If src is zero (i.e. bsf sets ZF), returns NumBits.
8807  SDValue Ops[] = {
8808    Op,
8809    DAG.getConstant(NumBits, OpVT),
8810    DAG.getConstant(X86::COND_E, MVT::i8),
8811    Op.getValue(1)
8812  };
8813  Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
8814
8815  if (VT == MVT::i8)
8816    Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
8817  return Op;
8818}
8819
8820SDValue X86TargetLowering::LowerMUL_V2I64(SDValue Op, SelectionDAG &DAG) const {
8821  EVT VT = Op.getValueType();
8822  assert(VT == MVT::v2i64 && "Only know how to lower V2I64 multiply");
8823  DebugLoc dl = Op.getDebugLoc();
8824
8825  //  ulong2 Ahi = __builtin_ia32_psrlqi128( a, 32);
8826  //  ulong2 Bhi = __builtin_ia32_psrlqi128( b, 32);
8827  //  ulong2 AloBlo = __builtin_ia32_pmuludq128( a, b );
8828  //  ulong2 AloBhi = __builtin_ia32_pmuludq128( a, Bhi );
8829  //  ulong2 AhiBlo = __builtin_ia32_pmuludq128( Ahi, b );
8830  //
8831  //  AloBhi = __builtin_ia32_psllqi128( AloBhi, 32 );
8832  //  AhiBlo = __builtin_ia32_psllqi128( AhiBlo, 32 );
8833  //  return AloBlo + AloBhi + AhiBlo;
8834
8835  SDValue A = Op.getOperand(0);
8836  SDValue B = Op.getOperand(1);
8837
8838  SDValue Ahi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8839                       DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
8840                       A, DAG.getConstant(32, MVT::i32));
8841  SDValue Bhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8842                       DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
8843                       B, DAG.getConstant(32, MVT::i32));
8844  SDValue AloBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8845                       DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
8846                       A, B);
8847  SDValue AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8848                       DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
8849                       A, Bhi);
8850  SDValue AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8851                       DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
8852                       Ahi, B);
8853  AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8854                       DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
8855                       AloBhi, DAG.getConstant(32, MVT::i32));
8856  AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8857                       DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
8858                       AhiBlo, DAG.getConstant(32, MVT::i32));
8859  SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
8860  Res = DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
8861  return Res;
8862}
8863
8864SDValue X86TargetLowering::LowerShift(SDValue Op, SelectionDAG &DAG) const {
8865
8866  EVT VT = Op.getValueType();
8867  DebugLoc dl = Op.getDebugLoc();
8868  SDValue R = Op.getOperand(0);
8869  SDValue Amt = Op.getOperand(1);
8870
8871  LLVMContext *Context = DAG.getContext();
8872
8873  // Must have SSE2.
8874  if (!Subtarget->hasSSE2()) return SDValue();
8875
8876  // Optimize shl/srl/sra with constant shift amount.
8877  if (isSplatVector(Amt.getNode())) {
8878    SDValue SclrAmt = Amt->getOperand(0);
8879    if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt)) {
8880      uint64_t ShiftAmt = C->getZExtValue();
8881
8882      if (VT == MVT::v2i64 && Op.getOpcode() == ISD::SHL)
8883       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8884                     DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
8885                     R, DAG.getConstant(ShiftAmt, MVT::i32));
8886
8887      if (VT == MVT::v4i32 && Op.getOpcode() == ISD::SHL)
8888       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8889                     DAG.getConstant(Intrinsic::x86_sse2_pslli_d, MVT::i32),
8890                     R, DAG.getConstant(ShiftAmt, MVT::i32));
8891
8892      if (VT == MVT::v8i16 && Op.getOpcode() == ISD::SHL)
8893       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8894                     DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32),
8895                     R, DAG.getConstant(ShiftAmt, MVT::i32));
8896
8897      if (VT == MVT::v2i64 && Op.getOpcode() == ISD::SRL)
8898       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8899                     DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
8900                     R, DAG.getConstant(ShiftAmt, MVT::i32));
8901
8902      if (VT == MVT::v4i32 && Op.getOpcode() == ISD::SRL)
8903       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8904                     DAG.getConstant(Intrinsic::x86_sse2_psrli_d, MVT::i32),
8905                     R, DAG.getConstant(ShiftAmt, MVT::i32));
8906
8907      if (VT == MVT::v8i16 && Op.getOpcode() == ISD::SRL)
8908       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8909                     DAG.getConstant(Intrinsic::x86_sse2_psrli_w, MVT::i32),
8910                     R, DAG.getConstant(ShiftAmt, MVT::i32));
8911
8912      if (VT == MVT::v4i32 && Op.getOpcode() == ISD::SRA)
8913       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8914                     DAG.getConstant(Intrinsic::x86_sse2_psrai_d, MVT::i32),
8915                     R, DAG.getConstant(ShiftAmt, MVT::i32));
8916
8917      if (VT == MVT::v8i16 && Op.getOpcode() == ISD::SRA)
8918       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8919                     DAG.getConstant(Intrinsic::x86_sse2_psrai_w, MVT::i32),
8920                     R, DAG.getConstant(ShiftAmt, MVT::i32));
8921    }
8922  }
8923
8924  // Lower SHL with variable shift amount.
8925  // Cannot lower SHL without SSE4.1 or later.
8926  if (!Subtarget->hasSSE41()) return SDValue();
8927
8928  if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
8929    Op = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8930                     DAG.getConstant(Intrinsic::x86_sse2_pslli_d, MVT::i32),
8931                     Op.getOperand(1), DAG.getConstant(23, MVT::i32));
8932
8933    ConstantInt *CI = ConstantInt::get(*Context, APInt(32, 0x3f800000U));
8934
8935    std::vector<Constant*> CV(4, CI);
8936    Constant *C = ConstantVector::get(CV);
8937    SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8938    SDValue Addend = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8939                                 MachinePointerInfo::getConstantPool(),
8940                                 false, false, 16);
8941
8942    Op = DAG.getNode(ISD::ADD, dl, VT, Op, Addend);
8943    Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, Op);
8944    Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
8945    return DAG.getNode(ISD::MUL, dl, VT, Op, R);
8946  }
8947  if (VT == MVT::v16i8 && Op->getOpcode() == ISD::SHL) {
8948    // a = a << 5;
8949    Op = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8950                     DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32),
8951                     Op.getOperand(1), DAG.getConstant(5, MVT::i32));
8952
8953    ConstantInt *CM1 = ConstantInt::get(*Context, APInt(8, 15));
8954    ConstantInt *CM2 = ConstantInt::get(*Context, APInt(8, 63));
8955
8956    std::vector<Constant*> CVM1(16, CM1);
8957    std::vector<Constant*> CVM2(16, CM2);
8958    Constant *C = ConstantVector::get(CVM1);
8959    SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8960    SDValue M = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8961                            MachinePointerInfo::getConstantPool(),
8962                            false, false, 16);
8963
8964    // r = pblendv(r, psllw(r & (char16)15, 4), a);
8965    M = DAG.getNode(ISD::AND, dl, VT, R, M);
8966    M = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8967                    DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32), M,
8968                    DAG.getConstant(4, MVT::i32));
8969    R = DAG.getNode(X86ISD::PBLENDVB, dl, VT, R, M, Op);
8970    // a += a
8971    Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
8972
8973    C = ConstantVector::get(CVM2);
8974    CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8975    M = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8976                    MachinePointerInfo::getConstantPool(),
8977                    false, false, 16);
8978
8979    // r = pblendv(r, psllw(r & (char16)63, 2), a);
8980    M = DAG.getNode(ISD::AND, dl, VT, R, M);
8981    M = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8982                    DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32), M,
8983                    DAG.getConstant(2, MVT::i32));
8984    R = DAG.getNode(X86ISD::PBLENDVB, dl, VT, R, M, Op);
8985    // a += a
8986    Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
8987
8988    // return pblendv(r, r+r, a);
8989    R = DAG.getNode(X86ISD::PBLENDVB, dl, VT,
8990                    R, DAG.getNode(ISD::ADD, dl, VT, R, R), Op);
8991    return R;
8992  }
8993  return SDValue();
8994}
8995
8996SDValue X86TargetLowering::LowerXALUO(SDValue Op, SelectionDAG &DAG) const {
8997  // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
8998  // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
8999  // looks for this combo and may remove the "setcc" instruction if the "setcc"
9000  // has only one use.
9001  SDNode *N = Op.getNode();
9002  SDValue LHS = N->getOperand(0);
9003  SDValue RHS = N->getOperand(1);
9004  unsigned BaseOp = 0;
9005  unsigned Cond = 0;
9006  DebugLoc DL = Op.getDebugLoc();
9007  switch (Op.getOpcode()) {
9008  default: llvm_unreachable("Unknown ovf instruction!");
9009  case ISD::SADDO:
9010    // A subtract of one will be selected as a INC. Note that INC doesn't
9011    // set CF, so we can't do this for UADDO.
9012    if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
9013      if (C->isOne()) {
9014        BaseOp = X86ISD::INC;
9015        Cond = X86::COND_O;
9016        break;
9017      }
9018    BaseOp = X86ISD::ADD;
9019    Cond = X86::COND_O;
9020    break;
9021  case ISD::UADDO:
9022    BaseOp = X86ISD::ADD;
9023    Cond = X86::COND_B;
9024    break;
9025  case ISD::SSUBO:
9026    // A subtract of one will be selected as a DEC. Note that DEC doesn't
9027    // set CF, so we can't do this for USUBO.
9028    if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
9029      if (C->isOne()) {
9030        BaseOp = X86ISD::DEC;
9031        Cond = X86::COND_O;
9032        break;
9033      }
9034    BaseOp = X86ISD::SUB;
9035    Cond = X86::COND_O;
9036    break;
9037  case ISD::USUBO:
9038    BaseOp = X86ISD::SUB;
9039    Cond = X86::COND_B;
9040    break;
9041  case ISD::SMULO:
9042    BaseOp = X86ISD::SMUL;
9043    Cond = X86::COND_O;
9044    break;
9045  case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
9046    SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
9047                                 MVT::i32);
9048    SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
9049
9050    SDValue SetCC =
9051      DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
9052                  DAG.getConstant(X86::COND_O, MVT::i32),
9053                  SDValue(Sum.getNode(), 2));
9054
9055    DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), SetCC);
9056    return Sum;
9057  }
9058  }
9059
9060  // Also sets EFLAGS.
9061  SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
9062  SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
9063
9064  SDValue SetCC =
9065    DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
9066                DAG.getConstant(Cond, MVT::i32),
9067                SDValue(Sum.getNode(), 1));
9068
9069  DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), SetCC);
9070  return Sum;
9071}
9072
9073SDValue X86TargetLowering::LowerMEMBARRIER(SDValue Op, SelectionDAG &DAG) const{
9074  DebugLoc dl = Op.getDebugLoc();
9075
9076  // Go ahead and emit the fence on x86-64 even if we asked for no-sse2.
9077  // There isn't any reason to disable it if the target processor supports it.
9078  if (!Subtarget->hasSSE2() && !Subtarget->is64Bit()) {
9079    SDValue Chain = Op.getOperand(0);
9080    SDValue Zero = DAG.getConstant(0, MVT::i32);
9081    SDValue Ops[] = {
9082      DAG.getRegister(X86::ESP, MVT::i32), // Base
9083      DAG.getTargetConstant(1, MVT::i8),   // Scale
9084      DAG.getRegister(0, MVT::i32),        // Index
9085      DAG.getTargetConstant(0, MVT::i32),  // Disp
9086      DAG.getRegister(0, MVT::i32),        // Segment.
9087      Zero,
9088      Chain
9089    };
9090    SDNode *Res =
9091      DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops,
9092                          array_lengthof(Ops));
9093    return SDValue(Res, 0);
9094  }
9095
9096  unsigned isDev = cast<ConstantSDNode>(Op.getOperand(5))->getZExtValue();
9097  if (!isDev)
9098    return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
9099
9100  unsigned Op1 = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
9101  unsigned Op2 = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
9102  unsigned Op3 = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue();
9103  unsigned Op4 = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
9104
9105  // def : Pat<(membarrier (i8 0), (i8 0), (i8 0), (i8 1), (i8 1)), (SFENCE)>;
9106  if (!Op1 && !Op2 && !Op3 && Op4)
9107    return DAG.getNode(X86ISD::SFENCE, dl, MVT::Other, Op.getOperand(0));
9108
9109  // def : Pat<(membarrier (i8 1), (i8 0), (i8 0), (i8 0), (i8 1)), (LFENCE)>;
9110  if (Op1 && !Op2 && !Op3 && !Op4)
9111    return DAG.getNode(X86ISD::LFENCE, dl, MVT::Other, Op.getOperand(0));
9112
9113  // def : Pat<(membarrier (i8 imm), (i8 imm), (i8 imm), (i8 imm), (i8 1)),
9114  //           (MFENCE)>;
9115  return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
9116}
9117
9118SDValue X86TargetLowering::LowerCMP_SWAP(SDValue Op, SelectionDAG &DAG) const {
9119  EVT T = Op.getValueType();
9120  DebugLoc DL = Op.getDebugLoc();
9121  unsigned Reg = 0;
9122  unsigned size = 0;
9123  switch(T.getSimpleVT().SimpleTy) {
9124  default:
9125    assert(false && "Invalid value type!");
9126  case MVT::i8:  Reg = X86::AL;  size = 1; break;
9127  case MVT::i16: Reg = X86::AX;  size = 2; break;
9128  case MVT::i32: Reg = X86::EAX; size = 4; break;
9129  case MVT::i64:
9130    assert(Subtarget->is64Bit() && "Node not type legal!");
9131    Reg = X86::RAX; size = 8;
9132    break;
9133  }
9134  SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
9135                                    Op.getOperand(2), SDValue());
9136  SDValue Ops[] = { cpIn.getValue(0),
9137                    Op.getOperand(1),
9138                    Op.getOperand(3),
9139                    DAG.getTargetConstant(size, MVT::i8),
9140                    cpIn.getValue(1) };
9141  SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
9142  MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
9143  SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
9144                                           Ops, 5, T, MMO);
9145  SDValue cpOut =
9146    DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
9147  return cpOut;
9148}
9149
9150SDValue X86TargetLowering::LowerREADCYCLECOUNTER(SDValue Op,
9151                                                 SelectionDAG &DAG) const {
9152  assert(Subtarget->is64Bit() && "Result not type legalized?");
9153  SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
9154  SDValue TheChain = Op.getOperand(0);
9155  DebugLoc dl = Op.getDebugLoc();
9156  SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
9157  SDValue rax = DAG.getCopyFromReg(rd, dl, X86::RAX, MVT::i64, rd.getValue(1));
9158  SDValue rdx = DAG.getCopyFromReg(rax.getValue(1), dl, X86::RDX, MVT::i64,
9159                                   rax.getValue(2));
9160  SDValue Tmp = DAG.getNode(ISD::SHL, dl, MVT::i64, rdx,
9161                            DAG.getConstant(32, MVT::i8));
9162  SDValue Ops[] = {
9163    DAG.getNode(ISD::OR, dl, MVT::i64, rax, Tmp),
9164    rdx.getValue(1)
9165  };
9166  return DAG.getMergeValues(Ops, 2, dl);
9167}
9168
9169SDValue X86TargetLowering::LowerBITCAST(SDValue Op,
9170                                            SelectionDAG &DAG) const {
9171  EVT SrcVT = Op.getOperand(0).getValueType();
9172  EVT DstVT = Op.getValueType();
9173  assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
9174         Subtarget->hasMMX() && "Unexpected custom BITCAST");
9175  assert((DstVT == MVT::i64 ||
9176          (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
9177         "Unexpected custom BITCAST");
9178  // i64 <=> MMX conversions are Legal.
9179  if (SrcVT==MVT::i64 && DstVT.isVector())
9180    return Op;
9181  if (DstVT==MVT::i64 && SrcVT.isVector())
9182    return Op;
9183  // MMX <=> MMX conversions are Legal.
9184  if (SrcVT.isVector() && DstVT.isVector())
9185    return Op;
9186  // All other conversions need to be expanded.
9187  return SDValue();
9188}
9189
9190SDValue X86TargetLowering::LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) const {
9191  SDNode *Node = Op.getNode();
9192  DebugLoc dl = Node->getDebugLoc();
9193  EVT T = Node->getValueType(0);
9194  SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
9195                              DAG.getConstant(0, T), Node->getOperand(2));
9196  return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
9197                       cast<AtomicSDNode>(Node)->getMemoryVT(),
9198                       Node->getOperand(0),
9199                       Node->getOperand(1), negOp,
9200                       cast<AtomicSDNode>(Node)->getSrcValue(),
9201                       cast<AtomicSDNode>(Node)->getAlignment());
9202}
9203
9204static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
9205  EVT VT = Op.getNode()->getValueType(0);
9206
9207  // Let legalize expand this if it isn't a legal type yet.
9208  if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
9209    return SDValue();
9210
9211  SDVTList VTs = DAG.getVTList(VT, MVT::i32);
9212
9213  unsigned Opc;
9214  bool ExtraOp = false;
9215  switch (Op.getOpcode()) {
9216  default: assert(0 && "Invalid code");
9217  case ISD::ADDC: Opc = X86ISD::ADD; break;
9218  case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
9219  case ISD::SUBC: Opc = X86ISD::SUB; break;
9220  case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
9221  }
9222
9223  if (!ExtraOp)
9224    return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
9225                       Op.getOperand(1));
9226  return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
9227                     Op.getOperand(1), Op.getOperand(2));
9228}
9229
9230/// LowerOperation - Provide custom lowering hooks for some operations.
9231///
9232SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
9233  switch (Op.getOpcode()) {
9234  default: llvm_unreachable("Should not custom lower this!");
9235  case ISD::MEMBARRIER:         return LowerMEMBARRIER(Op,DAG);
9236  case ISD::ATOMIC_CMP_SWAP:    return LowerCMP_SWAP(Op,DAG);
9237  case ISD::ATOMIC_LOAD_SUB:    return LowerLOAD_SUB(Op,DAG);
9238  case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
9239  case ISD::CONCAT_VECTORS:     return LowerCONCAT_VECTORS(Op, DAG);
9240  case ISD::VECTOR_SHUFFLE:     return LowerVECTOR_SHUFFLE(Op, DAG);
9241  case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
9242  case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
9243  case ISD::EXTRACT_SUBVECTOR:  return LowerEXTRACT_SUBVECTOR(Op, DAG);
9244  case ISD::INSERT_SUBVECTOR:   return LowerINSERT_SUBVECTOR(Op, DAG);
9245  case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
9246  case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
9247  case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
9248  case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
9249  case ISD::ExternalSymbol:     return LowerExternalSymbol(Op, DAG);
9250  case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
9251  case ISD::SHL_PARTS:
9252  case ISD::SRA_PARTS:
9253  case ISD::SRL_PARTS:          return LowerShiftParts(Op, DAG);
9254  case ISD::SINT_TO_FP:         return LowerSINT_TO_FP(Op, DAG);
9255  case ISD::UINT_TO_FP:         return LowerUINT_TO_FP(Op, DAG);
9256  case ISD::FP_TO_SINT:         return LowerFP_TO_SINT(Op, DAG);
9257  case ISD::FP_TO_UINT:         return LowerFP_TO_UINT(Op, DAG);
9258  case ISD::FABS:               return LowerFABS(Op, DAG);
9259  case ISD::FNEG:               return LowerFNEG(Op, DAG);
9260  case ISD::FCOPYSIGN:          return LowerFCOPYSIGN(Op, DAG);
9261  case ISD::FGETSIGN:           return LowerFGETSIGN(Op, DAG);
9262  case ISD::SETCC:              return LowerSETCC(Op, DAG);
9263  case ISD::VSETCC:             return LowerVSETCC(Op, DAG);
9264  case ISD::SELECT:             return LowerSELECT(Op, DAG);
9265  case ISD::BRCOND:             return LowerBRCOND(Op, DAG);
9266  case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
9267  case ISD::VASTART:            return LowerVASTART(Op, DAG);
9268  case ISD::VAARG:              return LowerVAARG(Op, DAG);
9269  case ISD::VACOPY:             return LowerVACOPY(Op, DAG);
9270  case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
9271  case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
9272  case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
9273  case ISD::FRAME_TO_ARGS_OFFSET:
9274                                return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
9275  case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
9276  case ISD::EH_RETURN:          return LowerEH_RETURN(Op, DAG);
9277  case ISD::TRAMPOLINE:         return LowerTRAMPOLINE(Op, DAG);
9278  case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
9279  case ISD::CTLZ:               return LowerCTLZ(Op, DAG);
9280  case ISD::CTTZ:               return LowerCTTZ(Op, DAG);
9281  case ISD::MUL:                return LowerMUL_V2I64(Op, DAG);
9282  case ISD::SRA:
9283  case ISD::SRL:
9284  case ISD::SHL:                return LowerShift(Op, DAG);
9285  case ISD::SADDO:
9286  case ISD::UADDO:
9287  case ISD::SSUBO:
9288  case ISD::USUBO:
9289  case ISD::SMULO:
9290  case ISD::UMULO:              return LowerXALUO(Op, DAG);
9291  case ISD::READCYCLECOUNTER:   return LowerREADCYCLECOUNTER(Op, DAG);
9292  case ISD::BITCAST:            return LowerBITCAST(Op, DAG);
9293  case ISD::ADDC:
9294  case ISD::ADDE:
9295  case ISD::SUBC:
9296  case ISD::SUBE:               return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
9297  }
9298}
9299
9300void X86TargetLowering::
9301ReplaceATOMIC_BINARY_64(SDNode *Node, SmallVectorImpl<SDValue>&Results,
9302                        SelectionDAG &DAG, unsigned NewOp) const {
9303  EVT T = Node->getValueType(0);
9304  DebugLoc dl = Node->getDebugLoc();
9305  assert (T == MVT::i64 && "Only know how to expand i64 atomics");
9306
9307  SDValue Chain = Node->getOperand(0);
9308  SDValue In1 = Node->getOperand(1);
9309  SDValue In2L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
9310                             Node->getOperand(2), DAG.getIntPtrConstant(0));
9311  SDValue In2H = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
9312                             Node->getOperand(2), DAG.getIntPtrConstant(1));
9313  SDValue Ops[] = { Chain, In1, In2L, In2H };
9314  SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
9315  SDValue Result =
9316    DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops, 4, MVT::i64,
9317                            cast<MemSDNode>(Node)->getMemOperand());
9318  SDValue OpsF[] = { Result.getValue(0), Result.getValue(1)};
9319  Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
9320  Results.push_back(Result.getValue(2));
9321}
9322
9323/// ReplaceNodeResults - Replace a node with an illegal result type
9324/// with a new node built out of custom code.
9325void X86TargetLowering::ReplaceNodeResults(SDNode *N,
9326                                           SmallVectorImpl<SDValue>&Results,
9327                                           SelectionDAG &DAG) const {
9328  DebugLoc dl = N->getDebugLoc();
9329  switch (N->getOpcode()) {
9330  default:
9331    assert(false && "Do not know how to custom type legalize this operation!");
9332    return;
9333  case ISD::ADDC:
9334  case ISD::ADDE:
9335  case ISD::SUBC:
9336  case ISD::SUBE:
9337    // We don't want to expand or promote these.
9338    return;
9339  case ISD::FP_TO_SINT: {
9340    std::pair<SDValue,SDValue> Vals =
9341        FP_TO_INTHelper(SDValue(N, 0), DAG, true);
9342    SDValue FIST = Vals.first, StackSlot = Vals.second;
9343    if (FIST.getNode() != 0) {
9344      EVT VT = N->getValueType(0);
9345      // Return a load from the stack slot.
9346      Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
9347                                    MachinePointerInfo(), false, false, 0));
9348    }
9349    return;
9350  }
9351  case ISD::READCYCLECOUNTER: {
9352    SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
9353    SDValue TheChain = N->getOperand(0);
9354    SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
9355    SDValue eax = DAG.getCopyFromReg(rd, dl, X86::EAX, MVT::i32,
9356                                     rd.getValue(1));
9357    SDValue edx = DAG.getCopyFromReg(eax.getValue(1), dl, X86::EDX, MVT::i32,
9358                                     eax.getValue(2));
9359    // Use a buildpair to merge the two 32-bit values into a 64-bit one.
9360    SDValue Ops[] = { eax, edx };
9361    Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Ops, 2));
9362    Results.push_back(edx.getValue(1));
9363    return;
9364  }
9365  case ISD::ATOMIC_CMP_SWAP: {
9366    EVT T = N->getValueType(0);
9367    assert (T == MVT::i64 && "Only know how to expand i64 Cmp and Swap");
9368    SDValue cpInL, cpInH;
9369    cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(2),
9370                        DAG.getConstant(0, MVT::i32));
9371    cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(2),
9372                        DAG.getConstant(1, MVT::i32));
9373    cpInL = DAG.getCopyToReg(N->getOperand(0), dl, X86::EAX, cpInL, SDValue());
9374    cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl, X86::EDX, cpInH,
9375                             cpInL.getValue(1));
9376    SDValue swapInL, swapInH;
9377    swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(3),
9378                          DAG.getConstant(0, MVT::i32));
9379    swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(3),
9380                          DAG.getConstant(1, MVT::i32));
9381    swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl, X86::EBX, swapInL,
9382                               cpInH.getValue(1));
9383    swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl, X86::ECX, swapInH,
9384                               swapInL.getValue(1));
9385    SDValue Ops[] = { swapInH.getValue(0),
9386                      N->getOperand(1),
9387                      swapInH.getValue(1) };
9388    SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
9389    MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
9390    SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG8_DAG, dl, Tys,
9391                                             Ops, 3, T, MMO);
9392    SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl, X86::EAX,
9393                                        MVT::i32, Result.getValue(1));
9394    SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl, X86::EDX,
9395                                        MVT::i32, cpOutL.getValue(2));
9396    SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
9397    Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
9398    Results.push_back(cpOutH.getValue(1));
9399    return;
9400  }
9401  case ISD::ATOMIC_LOAD_ADD:
9402    ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMADD64_DAG);
9403    return;
9404  case ISD::ATOMIC_LOAD_AND:
9405    ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMAND64_DAG);
9406    return;
9407  case ISD::ATOMIC_LOAD_NAND:
9408    ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMNAND64_DAG);
9409    return;
9410  case ISD::ATOMIC_LOAD_OR:
9411    ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMOR64_DAG);
9412    return;
9413  case ISD::ATOMIC_LOAD_SUB:
9414    ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSUB64_DAG);
9415    return;
9416  case ISD::ATOMIC_LOAD_XOR:
9417    ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMXOR64_DAG);
9418    return;
9419  case ISD::ATOMIC_SWAP:
9420    ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSWAP64_DAG);
9421    return;
9422  }
9423}
9424
9425const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
9426  switch (Opcode) {
9427  default: return NULL;
9428  case X86ISD::BSF:                return "X86ISD::BSF";
9429  case X86ISD::BSR:                return "X86ISD::BSR";
9430  case X86ISD::SHLD:               return "X86ISD::SHLD";
9431  case X86ISD::SHRD:               return "X86ISD::SHRD";
9432  case X86ISD::FAND:               return "X86ISD::FAND";
9433  case X86ISD::FOR:                return "X86ISD::FOR";
9434  case X86ISD::FXOR:               return "X86ISD::FXOR";
9435  case X86ISD::FSRL:               return "X86ISD::FSRL";
9436  case X86ISD::FILD:               return "X86ISD::FILD";
9437  case X86ISD::FILD_FLAG:          return "X86ISD::FILD_FLAG";
9438  case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
9439  case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
9440  case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
9441  case X86ISD::FLD:                return "X86ISD::FLD";
9442  case X86ISD::FST:                return "X86ISD::FST";
9443  case X86ISD::CALL:               return "X86ISD::CALL";
9444  case X86ISD::RDTSC_DAG:          return "X86ISD::RDTSC_DAG";
9445  case X86ISD::BT:                 return "X86ISD::BT";
9446  case X86ISD::CMP:                return "X86ISD::CMP";
9447  case X86ISD::COMI:               return "X86ISD::COMI";
9448  case X86ISD::UCOMI:              return "X86ISD::UCOMI";
9449  case X86ISD::SETCC:              return "X86ISD::SETCC";
9450  case X86ISD::SETCC_CARRY:        return "X86ISD::SETCC_CARRY";
9451  case X86ISD::FSETCCsd:           return "X86ISD::FSETCCsd";
9452  case X86ISD::FSETCCss:           return "X86ISD::FSETCCss";
9453  case X86ISD::CMOV:               return "X86ISD::CMOV";
9454  case X86ISD::BRCOND:             return "X86ISD::BRCOND";
9455  case X86ISD::RET_FLAG:           return "X86ISD::RET_FLAG";
9456  case X86ISD::REP_STOS:           return "X86ISD::REP_STOS";
9457  case X86ISD::REP_MOVS:           return "X86ISD::REP_MOVS";
9458  case X86ISD::GlobalBaseReg:      return "X86ISD::GlobalBaseReg";
9459  case X86ISD::Wrapper:            return "X86ISD::Wrapper";
9460  case X86ISD::WrapperRIP:         return "X86ISD::WrapperRIP";
9461  case X86ISD::PEXTRB:             return "X86ISD::PEXTRB";
9462  case X86ISD::PEXTRW:             return "X86ISD::PEXTRW";
9463  case X86ISD::INSERTPS:           return "X86ISD::INSERTPS";
9464  case X86ISD::PINSRB:             return "X86ISD::PINSRB";
9465  case X86ISD::PINSRW:             return "X86ISD::PINSRW";
9466  case X86ISD::PSHUFB:             return "X86ISD::PSHUFB";
9467  case X86ISD::PANDN:              return "X86ISD::PANDN";
9468  case X86ISD::PSIGNB:             return "X86ISD::PSIGNB";
9469  case X86ISD::PSIGNW:             return "X86ISD::PSIGNW";
9470  case X86ISD::PSIGND:             return "X86ISD::PSIGND";
9471  case X86ISD::PBLENDVB:           return "X86ISD::PBLENDVB";
9472  case X86ISD::FMAX:               return "X86ISD::FMAX";
9473  case X86ISD::FMIN:               return "X86ISD::FMIN";
9474  case X86ISD::FRSQRT:             return "X86ISD::FRSQRT";
9475  case X86ISD::FRCP:               return "X86ISD::FRCP";
9476  case X86ISD::TLSADDR:            return "X86ISD::TLSADDR";
9477  case X86ISD::TLSCALL:            return "X86ISD::TLSCALL";
9478  case X86ISD::EH_RETURN:          return "X86ISD::EH_RETURN";
9479  case X86ISD::TC_RETURN:          return "X86ISD::TC_RETURN";
9480  case X86ISD::FNSTCW16m:          return "X86ISD::FNSTCW16m";
9481  case X86ISD::LCMPXCHG_DAG:       return "X86ISD::LCMPXCHG_DAG";
9482  case X86ISD::LCMPXCHG8_DAG:      return "X86ISD::LCMPXCHG8_DAG";
9483  case X86ISD::ATOMADD64_DAG:      return "X86ISD::ATOMADD64_DAG";
9484  case X86ISD::ATOMSUB64_DAG:      return "X86ISD::ATOMSUB64_DAG";
9485  case X86ISD::ATOMOR64_DAG:       return "X86ISD::ATOMOR64_DAG";
9486  case X86ISD::ATOMXOR64_DAG:      return "X86ISD::ATOMXOR64_DAG";
9487  case X86ISD::ATOMAND64_DAG:      return "X86ISD::ATOMAND64_DAG";
9488  case X86ISD::ATOMNAND64_DAG:     return "X86ISD::ATOMNAND64_DAG";
9489  case X86ISD::VZEXT_MOVL:         return "X86ISD::VZEXT_MOVL";
9490  case X86ISD::VZEXT_LOAD:         return "X86ISD::VZEXT_LOAD";
9491  case X86ISD::VSHL:               return "X86ISD::VSHL";
9492  case X86ISD::VSRL:               return "X86ISD::VSRL";
9493  case X86ISD::CMPPD:              return "X86ISD::CMPPD";
9494  case X86ISD::CMPPS:              return "X86ISD::CMPPS";
9495  case X86ISD::PCMPEQB:            return "X86ISD::PCMPEQB";
9496  case X86ISD::PCMPEQW:            return "X86ISD::PCMPEQW";
9497  case X86ISD::PCMPEQD:            return "X86ISD::PCMPEQD";
9498  case X86ISD::PCMPEQQ:            return "X86ISD::PCMPEQQ";
9499  case X86ISD::PCMPGTB:            return "X86ISD::PCMPGTB";
9500  case X86ISD::PCMPGTW:            return "X86ISD::PCMPGTW";
9501  case X86ISD::PCMPGTD:            return "X86ISD::PCMPGTD";
9502  case X86ISD::PCMPGTQ:            return "X86ISD::PCMPGTQ";
9503  case X86ISD::ADD:                return "X86ISD::ADD";
9504  case X86ISD::SUB:                return "X86ISD::SUB";
9505  case X86ISD::ADC:                return "X86ISD::ADC";
9506  case X86ISD::SBB:                return "X86ISD::SBB";
9507  case X86ISD::SMUL:               return "X86ISD::SMUL";
9508  case X86ISD::UMUL:               return "X86ISD::UMUL";
9509  case X86ISD::INC:                return "X86ISD::INC";
9510  case X86ISD::DEC:                return "X86ISD::DEC";
9511  case X86ISD::OR:                 return "X86ISD::OR";
9512  case X86ISD::XOR:                return "X86ISD::XOR";
9513  case X86ISD::AND:                return "X86ISD::AND";
9514  case X86ISD::MUL_IMM:            return "X86ISD::MUL_IMM";
9515  case X86ISD::PTEST:              return "X86ISD::PTEST";
9516  case X86ISD::TESTP:              return "X86ISD::TESTP";
9517  case X86ISD::PALIGN:             return "X86ISD::PALIGN";
9518  case X86ISD::PSHUFD:             return "X86ISD::PSHUFD";
9519  case X86ISD::PSHUFHW:            return "X86ISD::PSHUFHW";
9520  case X86ISD::PSHUFHW_LD:         return "X86ISD::PSHUFHW_LD";
9521  case X86ISD::PSHUFLW:            return "X86ISD::PSHUFLW";
9522  case X86ISD::PSHUFLW_LD:         return "X86ISD::PSHUFLW_LD";
9523  case X86ISD::SHUFPS:             return "X86ISD::SHUFPS";
9524  case X86ISD::SHUFPD:             return "X86ISD::SHUFPD";
9525  case X86ISD::MOVLHPS:            return "X86ISD::MOVLHPS";
9526  case X86ISD::MOVLHPD:            return "X86ISD::MOVLHPD";
9527  case X86ISD::MOVHLPS:            return "X86ISD::MOVHLPS";
9528  case X86ISD::MOVHLPD:            return "X86ISD::MOVHLPD";
9529  case X86ISD::MOVLPS:             return "X86ISD::MOVLPS";
9530  case X86ISD::MOVLPD:             return "X86ISD::MOVLPD";
9531  case X86ISD::MOVDDUP:            return "X86ISD::MOVDDUP";
9532  case X86ISD::MOVSHDUP:           return "X86ISD::MOVSHDUP";
9533  case X86ISD::MOVSLDUP:           return "X86ISD::MOVSLDUP";
9534  case X86ISD::MOVSHDUP_LD:        return "X86ISD::MOVSHDUP_LD";
9535  case X86ISD::MOVSLDUP_LD:        return "X86ISD::MOVSLDUP_LD";
9536  case X86ISD::MOVSD:              return "X86ISD::MOVSD";
9537  case X86ISD::MOVSS:              return "X86ISD::MOVSS";
9538  case X86ISD::UNPCKLPS:           return "X86ISD::UNPCKLPS";
9539  case X86ISD::UNPCKLPD:           return "X86ISD::UNPCKLPD";
9540  case X86ISD::VUNPCKLPS:          return "X86ISD::VUNPCKLPS";
9541  case X86ISD::VUNPCKLPD:          return "X86ISD::VUNPCKLPD";
9542  case X86ISD::VUNPCKLPSY:         return "X86ISD::VUNPCKLPSY";
9543  case X86ISD::VUNPCKLPDY:         return "X86ISD::VUNPCKLPDY";
9544  case X86ISD::UNPCKHPS:           return "X86ISD::UNPCKHPS";
9545  case X86ISD::UNPCKHPD:           return "X86ISD::UNPCKHPD";
9546  case X86ISD::PUNPCKLBW:          return "X86ISD::PUNPCKLBW";
9547  case X86ISD::PUNPCKLWD:          return "X86ISD::PUNPCKLWD";
9548  case X86ISD::PUNPCKLDQ:          return "X86ISD::PUNPCKLDQ";
9549  case X86ISD::PUNPCKLQDQ:         return "X86ISD::PUNPCKLQDQ";
9550  case X86ISD::PUNPCKHBW:          return "X86ISD::PUNPCKHBW";
9551  case X86ISD::PUNPCKHWD:          return "X86ISD::PUNPCKHWD";
9552  case X86ISD::PUNPCKHDQ:          return "X86ISD::PUNPCKHDQ";
9553  case X86ISD::PUNPCKHQDQ:         return "X86ISD::PUNPCKHQDQ";
9554  case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
9555  case X86ISD::VAARG_64:           return "X86ISD::VAARG_64";
9556  case X86ISD::WIN_ALLOCA:         return "X86ISD::WIN_ALLOCA";
9557  }
9558}
9559
9560// isLegalAddressingMode - Return true if the addressing mode represented
9561// by AM is legal for this target, for a load/store of the specified type.
9562bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
9563                                              const Type *Ty) const {
9564  // X86 supports extremely general addressing modes.
9565  CodeModel::Model M = getTargetMachine().getCodeModel();
9566  Reloc::Model R = getTargetMachine().getRelocationModel();
9567
9568  // X86 allows a sign-extended 32-bit immediate field as a displacement.
9569  if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != NULL))
9570    return false;
9571
9572  if (AM.BaseGV) {
9573    unsigned GVFlags =
9574      Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
9575
9576    // If a reference to this global requires an extra load, we can't fold it.
9577    if (isGlobalStubReference(GVFlags))
9578      return false;
9579
9580    // If BaseGV requires a register for the PIC base, we cannot also have a
9581    // BaseReg specified.
9582    if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
9583      return false;
9584
9585    // If lower 4G is not available, then we must use rip-relative addressing.
9586    if ((M != CodeModel::Small || R != Reloc::Static) &&
9587        Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
9588      return false;
9589  }
9590
9591  switch (AM.Scale) {
9592  case 0:
9593  case 1:
9594  case 2:
9595  case 4:
9596  case 8:
9597    // These scales always work.
9598    break;
9599  case 3:
9600  case 5:
9601  case 9:
9602    // These scales are formed with basereg+scalereg.  Only accept if there is
9603    // no basereg yet.
9604    if (AM.HasBaseReg)
9605      return false;
9606    break;
9607  default:  // Other stuff never works.
9608    return false;
9609  }
9610
9611  return true;
9612}
9613
9614
9615bool X86TargetLowering::isTruncateFree(const Type *Ty1, const Type *Ty2) const {
9616  if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
9617    return false;
9618  unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
9619  unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
9620  if (NumBits1 <= NumBits2)
9621    return false;
9622  return true;
9623}
9624
9625bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
9626  if (!VT1.isInteger() || !VT2.isInteger())
9627    return false;
9628  unsigned NumBits1 = VT1.getSizeInBits();
9629  unsigned NumBits2 = VT2.getSizeInBits();
9630  if (NumBits1 <= NumBits2)
9631    return false;
9632  return true;
9633}
9634
9635bool X86TargetLowering::isZExtFree(const Type *Ty1, const Type *Ty2) const {
9636  // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
9637  return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
9638}
9639
9640bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
9641  // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
9642  return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
9643}
9644
9645bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
9646  // i16 instructions are longer (0x66 prefix) and potentially slower.
9647  return !(VT1 == MVT::i32 && VT2 == MVT::i16);
9648}
9649
9650/// isShuffleMaskLegal - Targets can use this to indicate that they only
9651/// support *some* VECTOR_SHUFFLE operations, those with specific masks.
9652/// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
9653/// are assumed to be legal.
9654bool
9655X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
9656                                      EVT VT) const {
9657  // Very little shuffling can be done for 64-bit vectors right now.
9658  if (VT.getSizeInBits() == 64)
9659    return isPALIGNRMask(M, VT, Subtarget->hasSSSE3());
9660
9661  // FIXME: pshufb, blends, shifts.
9662  return (VT.getVectorNumElements() == 2 ||
9663          ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
9664          isMOVLMask(M, VT) ||
9665          isSHUFPMask(M, VT) ||
9666          isPSHUFDMask(M, VT) ||
9667          isPSHUFHWMask(M, VT) ||
9668          isPSHUFLWMask(M, VT) ||
9669          isPALIGNRMask(M, VT, Subtarget->hasSSSE3()) ||
9670          isUNPCKLMask(M, VT) ||
9671          isUNPCKHMask(M, VT) ||
9672          isUNPCKL_v_undef_Mask(M, VT) ||
9673          isUNPCKH_v_undef_Mask(M, VT));
9674}
9675
9676bool
9677X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
9678                                          EVT VT) const {
9679  unsigned NumElts = VT.getVectorNumElements();
9680  // FIXME: This collection of masks seems suspect.
9681  if (NumElts == 2)
9682    return true;
9683  if (NumElts == 4 && VT.getSizeInBits() == 128) {
9684    return (isMOVLMask(Mask, VT)  ||
9685            isCommutedMOVLMask(Mask, VT, true) ||
9686            isSHUFPMask(Mask, VT) ||
9687            isCommutedSHUFPMask(Mask, VT));
9688  }
9689  return false;
9690}
9691
9692//===----------------------------------------------------------------------===//
9693//                           X86 Scheduler Hooks
9694//===----------------------------------------------------------------------===//
9695
9696// private utility function
9697MachineBasicBlock *
9698X86TargetLowering::EmitAtomicBitwiseWithCustomInserter(MachineInstr *bInstr,
9699                                                       MachineBasicBlock *MBB,
9700                                                       unsigned regOpc,
9701                                                       unsigned immOpc,
9702                                                       unsigned LoadOpc,
9703                                                       unsigned CXchgOpc,
9704                                                       unsigned notOpc,
9705                                                       unsigned EAXreg,
9706                                                       TargetRegisterClass *RC,
9707                                                       bool invSrc) const {
9708  // For the atomic bitwise operator, we generate
9709  //   thisMBB:
9710  //   newMBB:
9711  //     ld  t1 = [bitinstr.addr]
9712  //     op  t2 = t1, [bitinstr.val]
9713  //     mov EAX = t1
9714  //     lcs dest = [bitinstr.addr], t2  [EAX is implicit]
9715  //     bz  newMBB
9716  //     fallthrough -->nextMBB
9717  const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
9718  const BasicBlock *LLVM_BB = MBB->getBasicBlock();
9719  MachineFunction::iterator MBBIter = MBB;
9720  ++MBBIter;
9721
9722  /// First build the CFG
9723  MachineFunction *F = MBB->getParent();
9724  MachineBasicBlock *thisMBB = MBB;
9725  MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
9726  MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
9727  F->insert(MBBIter, newMBB);
9728  F->insert(MBBIter, nextMBB);
9729
9730  // Transfer the remainder of thisMBB and its successor edges to nextMBB.
9731  nextMBB->splice(nextMBB->begin(), thisMBB,
9732                  llvm::next(MachineBasicBlock::iterator(bInstr)),
9733                  thisMBB->end());
9734  nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
9735
9736  // Update thisMBB to fall through to newMBB
9737  thisMBB->addSuccessor(newMBB);
9738
9739  // newMBB jumps to itself and fall through to nextMBB
9740  newMBB->addSuccessor(nextMBB);
9741  newMBB->addSuccessor(newMBB);
9742
9743  // Insert instructions into newMBB based on incoming instruction
9744  assert(bInstr->getNumOperands() < X86::AddrNumOperands + 4 &&
9745         "unexpected number of operands");
9746  DebugLoc dl = bInstr->getDebugLoc();
9747  MachineOperand& destOper = bInstr->getOperand(0);
9748  MachineOperand* argOpers[2 + X86::AddrNumOperands];
9749  int numArgs = bInstr->getNumOperands() - 1;
9750  for (int i=0; i < numArgs; ++i)
9751    argOpers[i] = &bInstr->getOperand(i+1);
9752
9753  // x86 address has 4 operands: base, index, scale, and displacement
9754  int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
9755  int valArgIndx = lastAddrIndx + 1;
9756
9757  unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
9758  MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(LoadOpc), t1);
9759  for (int i=0; i <= lastAddrIndx; ++i)
9760    (*MIB).addOperand(*argOpers[i]);
9761
9762  unsigned tt = F->getRegInfo().createVirtualRegister(RC);
9763  if (invSrc) {
9764    MIB = BuildMI(newMBB, dl, TII->get(notOpc), tt).addReg(t1);
9765  }
9766  else
9767    tt = t1;
9768
9769  unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
9770  assert((argOpers[valArgIndx]->isReg() ||
9771          argOpers[valArgIndx]->isImm()) &&
9772         "invalid operand");
9773  if (argOpers[valArgIndx]->isReg())
9774    MIB = BuildMI(newMBB, dl, TII->get(regOpc), t2);
9775  else
9776    MIB = BuildMI(newMBB, dl, TII->get(immOpc), t2);
9777  MIB.addReg(tt);
9778  (*MIB).addOperand(*argOpers[valArgIndx]);
9779
9780  MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), EAXreg);
9781  MIB.addReg(t1);
9782
9783  MIB = BuildMI(newMBB, dl, TII->get(CXchgOpc));
9784  for (int i=0; i <= lastAddrIndx; ++i)
9785    (*MIB).addOperand(*argOpers[i]);
9786  MIB.addReg(t2);
9787  assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
9788  (*MIB).setMemRefs(bInstr->memoperands_begin(),
9789                    bInstr->memoperands_end());
9790
9791  MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), destOper.getReg());
9792  MIB.addReg(EAXreg);
9793
9794  // insert branch
9795  BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
9796
9797  bInstr->eraseFromParent();   // The pseudo instruction is gone now.
9798  return nextMBB;
9799}
9800
9801// private utility function:  64 bit atomics on 32 bit host.
9802MachineBasicBlock *
9803X86TargetLowering::EmitAtomicBit6432WithCustomInserter(MachineInstr *bInstr,
9804                                                       MachineBasicBlock *MBB,
9805                                                       unsigned regOpcL,
9806                                                       unsigned regOpcH,
9807                                                       unsigned immOpcL,
9808                                                       unsigned immOpcH,
9809                                                       bool invSrc) const {
9810  // For the atomic bitwise operator, we generate
9811  //   thisMBB (instructions are in pairs, except cmpxchg8b)
9812  //     ld t1,t2 = [bitinstr.addr]
9813  //   newMBB:
9814  //     out1, out2 = phi (thisMBB, t1/t2) (newMBB, t3/t4)
9815  //     op  t5, t6 <- out1, out2, [bitinstr.val]
9816  //      (for SWAP, substitute:  mov t5, t6 <- [bitinstr.val])
9817  //     mov ECX, EBX <- t5, t6
9818  //     mov EAX, EDX <- t1, t2
9819  //     cmpxchg8b [bitinstr.addr]  [EAX, EDX, EBX, ECX implicit]
9820  //     mov t3, t4 <- EAX, EDX
9821  //     bz  newMBB
9822  //     result in out1, out2
9823  //     fallthrough -->nextMBB
9824
9825  const TargetRegisterClass *RC = X86::GR32RegisterClass;
9826  const unsigned LoadOpc = X86::MOV32rm;
9827  const unsigned NotOpc = X86::NOT32r;
9828  const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
9829  const BasicBlock *LLVM_BB = MBB->getBasicBlock();
9830  MachineFunction::iterator MBBIter = MBB;
9831  ++MBBIter;
9832
9833  /// First build the CFG
9834  MachineFunction *F = MBB->getParent();
9835  MachineBasicBlock *thisMBB = MBB;
9836  MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
9837  MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
9838  F->insert(MBBIter, newMBB);
9839  F->insert(MBBIter, nextMBB);
9840
9841  // Transfer the remainder of thisMBB and its successor edges to nextMBB.
9842  nextMBB->splice(nextMBB->begin(), thisMBB,
9843                  llvm::next(MachineBasicBlock::iterator(bInstr)),
9844                  thisMBB->end());
9845  nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
9846
9847  // Update thisMBB to fall through to newMBB
9848  thisMBB->addSuccessor(newMBB);
9849
9850  // newMBB jumps to itself and fall through to nextMBB
9851  newMBB->addSuccessor(nextMBB);
9852  newMBB->addSuccessor(newMBB);
9853
9854  DebugLoc dl = bInstr->getDebugLoc();
9855  // Insert instructions into newMBB based on incoming instruction
9856  // There are 8 "real" operands plus 9 implicit def/uses, ignored here.
9857  assert(bInstr->getNumOperands() < X86::AddrNumOperands + 14 &&
9858         "unexpected number of operands");
9859  MachineOperand& dest1Oper = bInstr->getOperand(0);
9860  MachineOperand& dest2Oper = bInstr->getOperand(1);
9861  MachineOperand* argOpers[2 + X86::AddrNumOperands];
9862  for (int i=0; i < 2 + X86::AddrNumOperands; ++i) {
9863    argOpers[i] = &bInstr->getOperand(i+2);
9864
9865    // We use some of the operands multiple times, so conservatively just
9866    // clear any kill flags that might be present.
9867    if (argOpers[i]->isReg() && argOpers[i]->isUse())
9868      argOpers[i]->setIsKill(false);
9869  }
9870
9871  // x86 address has 5 operands: base, index, scale, displacement, and segment.
9872  int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
9873
9874  unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
9875  MachineInstrBuilder MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t1);
9876  for (int i=0; i <= lastAddrIndx; ++i)
9877    (*MIB).addOperand(*argOpers[i]);
9878  unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
9879  MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t2);
9880  // add 4 to displacement.
9881  for (int i=0; i <= lastAddrIndx-2; ++i)
9882    (*MIB).addOperand(*argOpers[i]);
9883  MachineOperand newOp3 = *(argOpers[3]);
9884  if (newOp3.isImm())
9885    newOp3.setImm(newOp3.getImm()+4);
9886  else
9887    newOp3.setOffset(newOp3.getOffset()+4);
9888  (*MIB).addOperand(newOp3);
9889  (*MIB).addOperand(*argOpers[lastAddrIndx]);
9890
9891  // t3/4 are defined later, at the bottom of the loop
9892  unsigned t3 = F->getRegInfo().createVirtualRegister(RC);
9893  unsigned t4 = F->getRegInfo().createVirtualRegister(RC);
9894  BuildMI(newMBB, dl, TII->get(X86::PHI), dest1Oper.getReg())
9895    .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(newMBB);
9896  BuildMI(newMBB, dl, TII->get(X86::PHI), dest2Oper.getReg())
9897    .addReg(t2).addMBB(thisMBB).addReg(t4).addMBB(newMBB);
9898
9899  // The subsequent operations should be using the destination registers of
9900  //the PHI instructions.
9901  if (invSrc) {
9902    t1 = F->getRegInfo().createVirtualRegister(RC);
9903    t2 = F->getRegInfo().createVirtualRegister(RC);
9904    MIB = BuildMI(newMBB, dl, TII->get(NotOpc), t1).addReg(dest1Oper.getReg());
9905    MIB = BuildMI(newMBB, dl, TII->get(NotOpc), t2).addReg(dest2Oper.getReg());
9906  } else {
9907    t1 = dest1Oper.getReg();
9908    t2 = dest2Oper.getReg();
9909  }
9910
9911  int valArgIndx = lastAddrIndx + 1;
9912  assert((argOpers[valArgIndx]->isReg() ||
9913          argOpers[valArgIndx]->isImm()) &&
9914         "invalid operand");
9915  unsigned t5 = F->getRegInfo().createVirtualRegister(RC);
9916  unsigned t6 = F->getRegInfo().createVirtualRegister(RC);
9917  if (argOpers[valArgIndx]->isReg())
9918    MIB = BuildMI(newMBB, dl, TII->get(regOpcL), t5);
9919  else
9920    MIB = BuildMI(newMBB, dl, TII->get(immOpcL), t5);
9921  if (regOpcL != X86::MOV32rr)
9922    MIB.addReg(t1);
9923  (*MIB).addOperand(*argOpers[valArgIndx]);
9924  assert(argOpers[valArgIndx + 1]->isReg() ==
9925         argOpers[valArgIndx]->isReg());
9926  assert(argOpers[valArgIndx + 1]->isImm() ==
9927         argOpers[valArgIndx]->isImm());
9928  if (argOpers[valArgIndx + 1]->isReg())
9929    MIB = BuildMI(newMBB, dl, TII->get(regOpcH), t6);
9930  else
9931    MIB = BuildMI(newMBB, dl, TII->get(immOpcH), t6);
9932  if (regOpcH != X86::MOV32rr)
9933    MIB.addReg(t2);
9934  (*MIB).addOperand(*argOpers[valArgIndx + 1]);
9935
9936  MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EAX);
9937  MIB.addReg(t1);
9938  MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EDX);
9939  MIB.addReg(t2);
9940
9941  MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EBX);
9942  MIB.addReg(t5);
9943  MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::ECX);
9944  MIB.addReg(t6);
9945
9946  MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG8B));
9947  for (int i=0; i <= lastAddrIndx; ++i)
9948    (*MIB).addOperand(*argOpers[i]);
9949
9950  assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
9951  (*MIB).setMemRefs(bInstr->memoperands_begin(),
9952                    bInstr->memoperands_end());
9953
9954  MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t3);
9955  MIB.addReg(X86::EAX);
9956  MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t4);
9957  MIB.addReg(X86::EDX);
9958
9959  // insert branch
9960  BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
9961
9962  bInstr->eraseFromParent();   // The pseudo instruction is gone now.
9963  return nextMBB;
9964}
9965
9966// private utility function
9967MachineBasicBlock *
9968X86TargetLowering::EmitAtomicMinMaxWithCustomInserter(MachineInstr *mInstr,
9969                                                      MachineBasicBlock *MBB,
9970                                                      unsigned cmovOpc) const {
9971  // For the atomic min/max operator, we generate
9972  //   thisMBB:
9973  //   newMBB:
9974  //     ld t1 = [min/max.addr]
9975  //     mov t2 = [min/max.val]
9976  //     cmp  t1, t2
9977  //     cmov[cond] t2 = t1
9978  //     mov EAX = t1
9979  //     lcs dest = [bitinstr.addr], t2  [EAX is implicit]
9980  //     bz   newMBB
9981  //     fallthrough -->nextMBB
9982  //
9983  const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
9984  const BasicBlock *LLVM_BB = MBB->getBasicBlock();
9985  MachineFunction::iterator MBBIter = MBB;
9986  ++MBBIter;
9987
9988  /// First build the CFG
9989  MachineFunction *F = MBB->getParent();
9990  MachineBasicBlock *thisMBB = MBB;
9991  MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
9992  MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
9993  F->insert(MBBIter, newMBB);
9994  F->insert(MBBIter, nextMBB);
9995
9996  // Transfer the remainder of thisMBB and its successor edges to nextMBB.
9997  nextMBB->splice(nextMBB->begin(), thisMBB,
9998                  llvm::next(MachineBasicBlock::iterator(mInstr)),
9999                  thisMBB->end());
10000  nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
10001
10002  // Update thisMBB to fall through to newMBB
10003  thisMBB->addSuccessor(newMBB);
10004
10005  // newMBB jumps to newMBB and fall through to nextMBB
10006  newMBB->addSuccessor(nextMBB);
10007  newMBB->addSuccessor(newMBB);
10008
10009  DebugLoc dl = mInstr->getDebugLoc();
10010  // Insert instructions into newMBB based on incoming instruction
10011  assert(mInstr->getNumOperands() < X86::AddrNumOperands + 4 &&
10012         "unexpected number of operands");
10013  MachineOperand& destOper = mInstr->getOperand(0);
10014  MachineOperand* argOpers[2 + X86::AddrNumOperands];
10015  int numArgs = mInstr->getNumOperands() - 1;
10016  for (int i=0; i < numArgs; ++i)
10017    argOpers[i] = &mInstr->getOperand(i+1);
10018
10019  // x86 address has 4 operands: base, index, scale, and displacement
10020  int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
10021  int valArgIndx = lastAddrIndx + 1;
10022
10023  unsigned t1 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
10024  MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rm), t1);
10025  for (int i=0; i <= lastAddrIndx; ++i)
10026    (*MIB).addOperand(*argOpers[i]);
10027
10028  // We only support register and immediate values
10029  assert((argOpers[valArgIndx]->isReg() ||
10030          argOpers[valArgIndx]->isImm()) &&
10031         "invalid operand");
10032
10033  unsigned t2 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
10034  if (argOpers[valArgIndx]->isReg())
10035    MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t2);
10036  else
10037    MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rr), t2);
10038  (*MIB).addOperand(*argOpers[valArgIndx]);
10039
10040  MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EAX);
10041  MIB.addReg(t1);
10042
10043  MIB = BuildMI(newMBB, dl, TII->get(X86::CMP32rr));
10044  MIB.addReg(t1);
10045  MIB.addReg(t2);
10046
10047  // Generate movc
10048  unsigned t3 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
10049  MIB = BuildMI(newMBB, dl, TII->get(cmovOpc),t3);
10050  MIB.addReg(t2);
10051  MIB.addReg(t1);
10052
10053  // Cmp and exchange if none has modified the memory location
10054  MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG32));
10055  for (int i=0; i <= lastAddrIndx; ++i)
10056    (*MIB).addOperand(*argOpers[i]);
10057  MIB.addReg(t3);
10058  assert(mInstr->hasOneMemOperand() && "Unexpected number of memoperand");
10059  (*MIB).setMemRefs(mInstr->memoperands_begin(),
10060                    mInstr->memoperands_end());
10061
10062  MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), destOper.getReg());
10063  MIB.addReg(X86::EAX);
10064
10065  // insert branch
10066  BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
10067
10068  mInstr->eraseFromParent();   // The pseudo instruction is gone now.
10069  return nextMBB;
10070}
10071
10072// FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
10073// or XMM0_V32I8 in AVX all of this code can be replaced with that
10074// in the .td file.
10075MachineBasicBlock *
10076X86TargetLowering::EmitPCMP(MachineInstr *MI, MachineBasicBlock *BB,
10077                            unsigned numArgs, bool memArg) const {
10078  assert((Subtarget->hasSSE42() || Subtarget->hasAVX()) &&
10079         "Target must have SSE4.2 or AVX features enabled");
10080
10081  DebugLoc dl = MI->getDebugLoc();
10082  const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
10083  unsigned Opc;
10084  if (!Subtarget->hasAVX()) {
10085    if (memArg)
10086      Opc = numArgs == 3 ? X86::PCMPISTRM128rm : X86::PCMPESTRM128rm;
10087    else
10088      Opc = numArgs == 3 ? X86::PCMPISTRM128rr : X86::PCMPESTRM128rr;
10089  } else {
10090    if (memArg)
10091      Opc = numArgs == 3 ? X86::VPCMPISTRM128rm : X86::VPCMPESTRM128rm;
10092    else
10093      Opc = numArgs == 3 ? X86::VPCMPISTRM128rr : X86::VPCMPESTRM128rr;
10094  }
10095
10096  MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
10097  for (unsigned i = 0; i < numArgs; ++i) {
10098    MachineOperand &Op = MI->getOperand(i+1);
10099    if (!(Op.isReg() && Op.isImplicit()))
10100      MIB.addOperand(Op);
10101  }
10102  BuildMI(*BB, MI, dl, TII->get(X86::MOVAPSrr), MI->getOperand(0).getReg())
10103    .addReg(X86::XMM0);
10104
10105  MI->eraseFromParent();
10106  return BB;
10107}
10108
10109MachineBasicBlock *
10110X86TargetLowering::EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB) const {
10111  DebugLoc dl = MI->getDebugLoc();
10112  const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
10113
10114  // Address into RAX/EAX, other two args into ECX, EDX.
10115  unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
10116  unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
10117  MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
10118  for (int i = 0; i < X86::AddrNumOperands; ++i)
10119    MIB.addOperand(MI->getOperand(i));
10120
10121  unsigned ValOps = X86::AddrNumOperands;
10122  BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
10123    .addReg(MI->getOperand(ValOps).getReg());
10124  BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
10125    .addReg(MI->getOperand(ValOps+1).getReg());
10126
10127  // The instruction doesn't actually take any operands though.
10128  BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
10129
10130  MI->eraseFromParent(); // The pseudo is gone now.
10131  return BB;
10132}
10133
10134MachineBasicBlock *
10135X86TargetLowering::EmitMwait(MachineInstr *MI, MachineBasicBlock *BB) const {
10136  DebugLoc dl = MI->getDebugLoc();
10137  const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
10138
10139  // First arg in ECX, the second in EAX.
10140  BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
10141    .addReg(MI->getOperand(0).getReg());
10142  BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EAX)
10143    .addReg(MI->getOperand(1).getReg());
10144
10145  // The instruction doesn't actually take any operands though.
10146  BuildMI(*BB, MI, dl, TII->get(X86::MWAITrr));
10147
10148  MI->eraseFromParent(); // The pseudo is gone now.
10149  return BB;
10150}
10151
10152MachineBasicBlock *
10153X86TargetLowering::EmitVAARG64WithCustomInserter(
10154                   MachineInstr *MI,
10155                   MachineBasicBlock *MBB) const {
10156  // Emit va_arg instruction on X86-64.
10157
10158  // Operands to this pseudo-instruction:
10159  // 0  ) Output        : destination address (reg)
10160  // 1-5) Input         : va_list address (addr, i64mem)
10161  // 6  ) ArgSize       : Size (in bytes) of vararg type
10162  // 7  ) ArgMode       : 0=overflow only, 1=use gp_offset, 2=use fp_offset
10163  // 8  ) Align         : Alignment of type
10164  // 9  ) EFLAGS (implicit-def)
10165
10166  assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
10167  assert(X86::AddrNumOperands == 5 && "VAARG_64 assumes 5 address operands");
10168
10169  unsigned DestReg = MI->getOperand(0).getReg();
10170  MachineOperand &Base = MI->getOperand(1);
10171  MachineOperand &Scale = MI->getOperand(2);
10172  MachineOperand &Index = MI->getOperand(3);
10173  MachineOperand &Disp = MI->getOperand(4);
10174  MachineOperand &Segment = MI->getOperand(5);
10175  unsigned ArgSize = MI->getOperand(6).getImm();
10176  unsigned ArgMode = MI->getOperand(7).getImm();
10177  unsigned Align = MI->getOperand(8).getImm();
10178
10179  // Memory Reference
10180  assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
10181  MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
10182  MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
10183
10184  // Machine Information
10185  const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
10186  MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
10187  const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
10188  const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
10189  DebugLoc DL = MI->getDebugLoc();
10190
10191  // struct va_list {
10192  //   i32   gp_offset
10193  //   i32   fp_offset
10194  //   i64   overflow_area (address)
10195  //   i64   reg_save_area (address)
10196  // }
10197  // sizeof(va_list) = 24
10198  // alignment(va_list) = 8
10199
10200  unsigned TotalNumIntRegs = 6;
10201  unsigned TotalNumXMMRegs = 8;
10202  bool UseGPOffset = (ArgMode == 1);
10203  bool UseFPOffset = (ArgMode == 2);
10204  unsigned MaxOffset = TotalNumIntRegs * 8 +
10205                       (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
10206
10207  /* Align ArgSize to a multiple of 8 */
10208  unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
10209  bool NeedsAlign = (Align > 8);
10210
10211  MachineBasicBlock *thisMBB = MBB;
10212  MachineBasicBlock *overflowMBB;
10213  MachineBasicBlock *offsetMBB;
10214  MachineBasicBlock *endMBB;
10215
10216  unsigned OffsetDestReg = 0;    // Argument address computed by offsetMBB
10217  unsigned OverflowDestReg = 0;  // Argument address computed by overflowMBB
10218  unsigned OffsetReg = 0;
10219
10220  if (!UseGPOffset && !UseFPOffset) {
10221    // If we only pull from the overflow region, we don't create a branch.
10222    // We don't need to alter control flow.
10223    OffsetDestReg = 0; // unused
10224    OverflowDestReg = DestReg;
10225
10226    offsetMBB = NULL;
10227    overflowMBB = thisMBB;
10228    endMBB = thisMBB;
10229  } else {
10230    // First emit code to check if gp_offset (or fp_offset) is below the bound.
10231    // If so, pull the argument from reg_save_area. (branch to offsetMBB)
10232    // If not, pull from overflow_area. (branch to overflowMBB)
10233    //
10234    //       thisMBB
10235    //         |     .
10236    //         |        .
10237    //     offsetMBB   overflowMBB
10238    //         |        .
10239    //         |     .
10240    //        endMBB
10241
10242    // Registers for the PHI in endMBB
10243    OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
10244    OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
10245
10246    const BasicBlock *LLVM_BB = MBB->getBasicBlock();
10247    MachineFunction *MF = MBB->getParent();
10248    overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
10249    offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
10250    endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
10251
10252    MachineFunction::iterator MBBIter = MBB;
10253    ++MBBIter;
10254
10255    // Insert the new basic blocks
10256    MF->insert(MBBIter, offsetMBB);
10257    MF->insert(MBBIter, overflowMBB);
10258    MF->insert(MBBIter, endMBB);
10259
10260    // Transfer the remainder of MBB and its successor edges to endMBB.
10261    endMBB->splice(endMBB->begin(), thisMBB,
10262                    llvm::next(MachineBasicBlock::iterator(MI)),
10263                    thisMBB->end());
10264    endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
10265
10266    // Make offsetMBB and overflowMBB successors of thisMBB
10267    thisMBB->addSuccessor(offsetMBB);
10268    thisMBB->addSuccessor(overflowMBB);
10269
10270    // endMBB is a successor of both offsetMBB and overflowMBB
10271    offsetMBB->addSuccessor(endMBB);
10272    overflowMBB->addSuccessor(endMBB);
10273
10274    // Load the offset value into a register
10275    OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
10276    BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
10277      .addOperand(Base)
10278      .addOperand(Scale)
10279      .addOperand(Index)
10280      .addDisp(Disp, UseFPOffset ? 4 : 0)
10281      .addOperand(Segment)
10282      .setMemRefs(MMOBegin, MMOEnd);
10283
10284    // Check if there is enough room left to pull this argument.
10285    BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
10286      .addReg(OffsetReg)
10287      .addImm(MaxOffset + 8 - ArgSizeA8);
10288
10289    // Branch to "overflowMBB" if offset >= max
10290    // Fall through to "offsetMBB" otherwise
10291    BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
10292      .addMBB(overflowMBB);
10293  }
10294
10295  // In offsetMBB, emit code to use the reg_save_area.
10296  if (offsetMBB) {
10297    assert(OffsetReg != 0);
10298
10299    // Read the reg_save_area address.
10300    unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
10301    BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
10302      .addOperand(Base)
10303      .addOperand(Scale)
10304      .addOperand(Index)
10305      .addDisp(Disp, 16)
10306      .addOperand(Segment)
10307      .setMemRefs(MMOBegin, MMOEnd);
10308
10309    // Zero-extend the offset
10310    unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
10311      BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
10312        .addImm(0)
10313        .addReg(OffsetReg)
10314        .addImm(X86::sub_32bit);
10315
10316    // Add the offset to the reg_save_area to get the final address.
10317    BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
10318      .addReg(OffsetReg64)
10319      .addReg(RegSaveReg);
10320
10321    // Compute the offset for the next argument
10322    unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
10323    BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
10324      .addReg(OffsetReg)
10325      .addImm(UseFPOffset ? 16 : 8);
10326
10327    // Store it back into the va_list.
10328    BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
10329      .addOperand(Base)
10330      .addOperand(Scale)
10331      .addOperand(Index)
10332      .addDisp(Disp, UseFPOffset ? 4 : 0)
10333      .addOperand(Segment)
10334      .addReg(NextOffsetReg)
10335      .setMemRefs(MMOBegin, MMOEnd);
10336
10337    // Jump to endMBB
10338    BuildMI(offsetMBB, DL, TII->get(X86::JMP_4))
10339      .addMBB(endMBB);
10340  }
10341
10342  //
10343  // Emit code to use overflow area
10344  //
10345
10346  // Load the overflow_area address into a register.
10347  unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
10348  BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
10349    .addOperand(Base)
10350    .addOperand(Scale)
10351    .addOperand(Index)
10352    .addDisp(Disp, 8)
10353    .addOperand(Segment)
10354    .setMemRefs(MMOBegin, MMOEnd);
10355
10356  // If we need to align it, do so. Otherwise, just copy the address
10357  // to OverflowDestReg.
10358  if (NeedsAlign) {
10359    // Align the overflow address
10360    assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
10361    unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
10362
10363    // aligned_addr = (addr + (align-1)) & ~(align-1)
10364    BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
10365      .addReg(OverflowAddrReg)
10366      .addImm(Align-1);
10367
10368    BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
10369      .addReg(TmpReg)
10370      .addImm(~(uint64_t)(Align-1));
10371  } else {
10372    BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
10373      .addReg(OverflowAddrReg);
10374  }
10375
10376  // Compute the next overflow address after this argument.
10377  // (the overflow address should be kept 8-byte aligned)
10378  unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
10379  BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
10380    .addReg(OverflowDestReg)
10381    .addImm(ArgSizeA8);
10382
10383  // Store the new overflow address.
10384  BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
10385    .addOperand(Base)
10386    .addOperand(Scale)
10387    .addOperand(Index)
10388    .addDisp(Disp, 8)
10389    .addOperand(Segment)
10390    .addReg(NextAddrReg)
10391    .setMemRefs(MMOBegin, MMOEnd);
10392
10393  // If we branched, emit the PHI to the front of endMBB.
10394  if (offsetMBB) {
10395    BuildMI(*endMBB, endMBB->begin(), DL,
10396            TII->get(X86::PHI), DestReg)
10397      .addReg(OffsetDestReg).addMBB(offsetMBB)
10398      .addReg(OverflowDestReg).addMBB(overflowMBB);
10399  }
10400
10401  // Erase the pseudo instruction
10402  MI->eraseFromParent();
10403
10404  return endMBB;
10405}
10406
10407MachineBasicBlock *
10408X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
10409                                                 MachineInstr *MI,
10410                                                 MachineBasicBlock *MBB) const {
10411  // Emit code to save XMM registers to the stack. The ABI says that the
10412  // number of registers to save is given in %al, so it's theoretically
10413  // possible to do an indirect jump trick to avoid saving all of them,
10414  // however this code takes a simpler approach and just executes all
10415  // of the stores if %al is non-zero. It's less code, and it's probably
10416  // easier on the hardware branch predictor, and stores aren't all that
10417  // expensive anyway.
10418
10419  // Create the new basic blocks. One block contains all the XMM stores,
10420  // and one block is the final destination regardless of whether any
10421  // stores were performed.
10422  const BasicBlock *LLVM_BB = MBB->getBasicBlock();
10423  MachineFunction *F = MBB->getParent();
10424  MachineFunction::iterator MBBIter = MBB;
10425  ++MBBIter;
10426  MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
10427  MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
10428  F->insert(MBBIter, XMMSaveMBB);
10429  F->insert(MBBIter, EndMBB);
10430
10431  // Transfer the remainder of MBB and its successor edges to EndMBB.
10432  EndMBB->splice(EndMBB->begin(), MBB,
10433                 llvm::next(MachineBasicBlock::iterator(MI)),
10434                 MBB->end());
10435  EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
10436
10437  // The original block will now fall through to the XMM save block.
10438  MBB->addSuccessor(XMMSaveMBB);
10439  // The XMMSaveMBB will fall through to the end block.
10440  XMMSaveMBB->addSuccessor(EndMBB);
10441
10442  // Now add the instructions.
10443  const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
10444  DebugLoc DL = MI->getDebugLoc();
10445
10446  unsigned CountReg = MI->getOperand(0).getReg();
10447  int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
10448  int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
10449
10450  if (!Subtarget->isTargetWin64()) {
10451    // If %al is 0, branch around the XMM save block.
10452    BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
10453    BuildMI(MBB, DL, TII->get(X86::JE_4)).addMBB(EndMBB);
10454    MBB->addSuccessor(EndMBB);
10455  }
10456
10457  // In the XMM save block, save all the XMM argument registers.
10458  for (int i = 3, e = MI->getNumOperands(); i != e; ++i) {
10459    int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
10460    MachineMemOperand *MMO =
10461      F->getMachineMemOperand(
10462          MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
10463        MachineMemOperand::MOStore,
10464        /*Size=*/16, /*Align=*/16);
10465    BuildMI(XMMSaveMBB, DL, TII->get(X86::MOVAPSmr))
10466      .addFrameIndex(RegSaveFrameIndex)
10467      .addImm(/*Scale=*/1)
10468      .addReg(/*IndexReg=*/0)
10469      .addImm(/*Disp=*/Offset)
10470      .addReg(/*Segment=*/0)
10471      .addReg(MI->getOperand(i).getReg())
10472      .addMemOperand(MMO);
10473  }
10474
10475  MI->eraseFromParent();   // The pseudo instruction is gone now.
10476
10477  return EndMBB;
10478}
10479
10480MachineBasicBlock *
10481X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
10482                                     MachineBasicBlock *BB) const {
10483  const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
10484  DebugLoc DL = MI->getDebugLoc();
10485
10486  // To "insert" a SELECT_CC instruction, we actually have to insert the
10487  // diamond control-flow pattern.  The incoming instruction knows the
10488  // destination vreg to set, the condition code register to branch on, the
10489  // true/false values to select between, and a branch opcode to use.
10490  const BasicBlock *LLVM_BB = BB->getBasicBlock();
10491  MachineFunction::iterator It = BB;
10492  ++It;
10493
10494  //  thisMBB:
10495  //  ...
10496  //   TrueVal = ...
10497  //   cmpTY ccX, r1, r2
10498  //   bCC copy1MBB
10499  //   fallthrough --> copy0MBB
10500  MachineBasicBlock *thisMBB = BB;
10501  MachineFunction *F = BB->getParent();
10502  MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
10503  MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
10504  F->insert(It, copy0MBB);
10505  F->insert(It, sinkMBB);
10506
10507  // If the EFLAGS register isn't dead in the terminator, then claim that it's
10508  // live into the sink and copy blocks.
10509  const MachineFunction *MF = BB->getParent();
10510  const TargetRegisterInfo *TRI = MF->getTarget().getRegisterInfo();
10511  BitVector ReservedRegs = TRI->getReservedRegs(*MF);
10512
10513  for (unsigned I = 0, E = MI->getNumOperands(); I != E; ++I) {
10514    const MachineOperand &MO = MI->getOperand(I);
10515    if (!MO.isReg() || !MO.isUse() || MO.isKill()) continue;
10516    unsigned Reg = MO.getReg();
10517    if (Reg != X86::EFLAGS) continue;
10518    copy0MBB->addLiveIn(Reg);
10519    sinkMBB->addLiveIn(Reg);
10520  }
10521
10522  // Transfer the remainder of BB and its successor edges to sinkMBB.
10523  sinkMBB->splice(sinkMBB->begin(), BB,
10524                  llvm::next(MachineBasicBlock::iterator(MI)),
10525                  BB->end());
10526  sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
10527
10528  // Add the true and fallthrough blocks as its successors.
10529  BB->addSuccessor(copy0MBB);
10530  BB->addSuccessor(sinkMBB);
10531
10532  // Create the conditional branch instruction.
10533  unsigned Opc =
10534    X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
10535  BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
10536
10537  //  copy0MBB:
10538  //   %FalseValue = ...
10539  //   # fallthrough to sinkMBB
10540  copy0MBB->addSuccessor(sinkMBB);
10541
10542  //  sinkMBB:
10543  //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
10544  //  ...
10545  BuildMI(*sinkMBB, sinkMBB->begin(), DL,
10546          TII->get(X86::PHI), MI->getOperand(0).getReg())
10547    .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
10548    .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
10549
10550  MI->eraseFromParent();   // The pseudo instruction is gone now.
10551  return sinkMBB;
10552}
10553
10554MachineBasicBlock *
10555X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
10556                                          MachineBasicBlock *BB) const {
10557  const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
10558  DebugLoc DL = MI->getDebugLoc();
10559
10560  assert(!Subtarget->isTargetEnvMacho());
10561
10562  // The lowering is pretty easy: we're just emitting the call to _alloca.  The
10563  // non-trivial part is impdef of ESP.
10564
10565  if (Subtarget->isTargetWin64()) {
10566    if (Subtarget->isTargetCygMing()) {
10567      // ___chkstk(Mingw64):
10568      // Clobbers R10, R11, RAX and EFLAGS.
10569      // Updates RSP.
10570      BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
10571        .addExternalSymbol("___chkstk")
10572        .addReg(X86::RAX, RegState::Implicit)
10573        .addReg(X86::RSP, RegState::Implicit)
10574        .addReg(X86::RAX, RegState::Define | RegState::Implicit)
10575        .addReg(X86::RSP, RegState::Define | RegState::Implicit)
10576        .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
10577    } else {
10578      // __chkstk(MSVCRT): does not update stack pointer.
10579      // Clobbers R10, R11 and EFLAGS.
10580      // FIXME: RAX(allocated size) might be reused and not killed.
10581      BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
10582        .addExternalSymbol("__chkstk")
10583        .addReg(X86::RAX, RegState::Implicit)
10584        .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
10585      // RAX has the offset to subtracted from RSP.
10586      BuildMI(*BB, MI, DL, TII->get(X86::SUB64rr), X86::RSP)
10587        .addReg(X86::RSP)
10588        .addReg(X86::RAX);
10589    }
10590  } else {
10591    const char *StackProbeSymbol =
10592      Subtarget->isTargetWindows() ? "_chkstk" : "_alloca";
10593
10594    BuildMI(*BB, MI, DL, TII->get(X86::CALLpcrel32))
10595      .addExternalSymbol(StackProbeSymbol)
10596      .addReg(X86::EAX, RegState::Implicit)
10597      .addReg(X86::ESP, RegState::Implicit)
10598      .addReg(X86::EAX, RegState::Define | RegState::Implicit)
10599      .addReg(X86::ESP, RegState::Define | RegState::Implicit)
10600      .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
10601  }
10602
10603  MI->eraseFromParent();   // The pseudo instruction is gone now.
10604  return BB;
10605}
10606
10607MachineBasicBlock *
10608X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
10609                                      MachineBasicBlock *BB) const {
10610  // This is pretty easy.  We're taking the value that we received from
10611  // our load from the relocation, sticking it in either RDI (x86-64)
10612  // or EAX and doing an indirect call.  The return value will then
10613  // be in the normal return register.
10614  const X86InstrInfo *TII
10615    = static_cast<const X86InstrInfo*>(getTargetMachine().getInstrInfo());
10616  DebugLoc DL = MI->getDebugLoc();
10617  MachineFunction *F = BB->getParent();
10618
10619  assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
10620  assert(MI->getOperand(3).isGlobal() && "This should be a global");
10621
10622  if (Subtarget->is64Bit()) {
10623    MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
10624                                      TII->get(X86::MOV64rm), X86::RDI)
10625    .addReg(X86::RIP)
10626    .addImm(0).addReg(0)
10627    .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
10628                      MI->getOperand(3).getTargetFlags())
10629    .addReg(0);
10630    MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
10631    addDirectMem(MIB, X86::RDI);
10632  } else if (getTargetMachine().getRelocationModel() != Reloc::PIC_) {
10633    MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
10634                                      TII->get(X86::MOV32rm), X86::EAX)
10635    .addReg(0)
10636    .addImm(0).addReg(0)
10637    .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
10638                      MI->getOperand(3).getTargetFlags())
10639    .addReg(0);
10640    MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
10641    addDirectMem(MIB, X86::EAX);
10642  } else {
10643    MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
10644                                      TII->get(X86::MOV32rm), X86::EAX)
10645    .addReg(TII->getGlobalBaseReg(F))
10646    .addImm(0).addReg(0)
10647    .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
10648                      MI->getOperand(3).getTargetFlags())
10649    .addReg(0);
10650    MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
10651    addDirectMem(MIB, X86::EAX);
10652  }
10653
10654  MI->eraseFromParent(); // The pseudo instruction is gone now.
10655  return BB;
10656}
10657
10658MachineBasicBlock *
10659X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
10660                                               MachineBasicBlock *BB) const {
10661  switch (MI->getOpcode()) {
10662  default: assert(false && "Unexpected instr type to insert");
10663  case X86::TAILJMPd64:
10664  case X86::TAILJMPr64:
10665  case X86::TAILJMPm64:
10666    assert(!"TAILJMP64 would not be touched here.");
10667  case X86::TCRETURNdi64:
10668  case X86::TCRETURNri64:
10669  case X86::TCRETURNmi64:
10670    // Defs of TCRETURNxx64 has Win64's callee-saved registers, as subset.
10671    // On AMD64, additional defs should be added before register allocation.
10672    if (!Subtarget->isTargetWin64()) {
10673      MI->addRegisterDefined(X86::RSI);
10674      MI->addRegisterDefined(X86::RDI);
10675      MI->addRegisterDefined(X86::XMM6);
10676      MI->addRegisterDefined(X86::XMM7);
10677      MI->addRegisterDefined(X86::XMM8);
10678      MI->addRegisterDefined(X86::XMM9);
10679      MI->addRegisterDefined(X86::XMM10);
10680      MI->addRegisterDefined(X86::XMM11);
10681      MI->addRegisterDefined(X86::XMM12);
10682      MI->addRegisterDefined(X86::XMM13);
10683      MI->addRegisterDefined(X86::XMM14);
10684      MI->addRegisterDefined(X86::XMM15);
10685    }
10686    return BB;
10687  case X86::WIN_ALLOCA:
10688    return EmitLoweredWinAlloca(MI, BB);
10689  case X86::TLSCall_32:
10690  case X86::TLSCall_64:
10691    return EmitLoweredTLSCall(MI, BB);
10692  case X86::CMOV_GR8:
10693  case X86::CMOV_FR32:
10694  case X86::CMOV_FR64:
10695  case X86::CMOV_V4F32:
10696  case X86::CMOV_V2F64:
10697  case X86::CMOV_V2I64:
10698  case X86::CMOV_GR16:
10699  case X86::CMOV_GR32:
10700  case X86::CMOV_RFP32:
10701  case X86::CMOV_RFP64:
10702  case X86::CMOV_RFP80:
10703    return EmitLoweredSelect(MI, BB);
10704
10705  case X86::FP32_TO_INT16_IN_MEM:
10706  case X86::FP32_TO_INT32_IN_MEM:
10707  case X86::FP32_TO_INT64_IN_MEM:
10708  case X86::FP64_TO_INT16_IN_MEM:
10709  case X86::FP64_TO_INT32_IN_MEM:
10710  case X86::FP64_TO_INT64_IN_MEM:
10711  case X86::FP80_TO_INT16_IN_MEM:
10712  case X86::FP80_TO_INT32_IN_MEM:
10713  case X86::FP80_TO_INT64_IN_MEM: {
10714    const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
10715    DebugLoc DL = MI->getDebugLoc();
10716
10717    // Change the floating point control register to use "round towards zero"
10718    // mode when truncating to an integer value.
10719    MachineFunction *F = BB->getParent();
10720    int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
10721    addFrameReference(BuildMI(*BB, MI, DL,
10722                              TII->get(X86::FNSTCW16m)), CWFrameIdx);
10723
10724    // Load the old value of the high byte of the control word...
10725    unsigned OldCW =
10726      F->getRegInfo().createVirtualRegister(X86::GR16RegisterClass);
10727    addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
10728                      CWFrameIdx);
10729
10730    // Set the high part to be round to zero...
10731    addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
10732      .addImm(0xC7F);
10733
10734    // Reload the modified control word now...
10735    addFrameReference(BuildMI(*BB, MI, DL,
10736                              TII->get(X86::FLDCW16m)), CWFrameIdx);
10737
10738    // Restore the memory image of control word to original value
10739    addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
10740      .addReg(OldCW);
10741
10742    // Get the X86 opcode to use.
10743    unsigned Opc;
10744    switch (MI->getOpcode()) {
10745    default: llvm_unreachable("illegal opcode!");
10746    case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
10747    case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
10748    case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
10749    case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
10750    case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
10751    case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
10752    case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
10753    case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
10754    case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
10755    }
10756
10757    X86AddressMode AM;
10758    MachineOperand &Op = MI->getOperand(0);
10759    if (Op.isReg()) {
10760      AM.BaseType = X86AddressMode::RegBase;
10761      AM.Base.Reg = Op.getReg();
10762    } else {
10763      AM.BaseType = X86AddressMode::FrameIndexBase;
10764      AM.Base.FrameIndex = Op.getIndex();
10765    }
10766    Op = MI->getOperand(1);
10767    if (Op.isImm())
10768      AM.Scale = Op.getImm();
10769    Op = MI->getOperand(2);
10770    if (Op.isImm())
10771      AM.IndexReg = Op.getImm();
10772    Op = MI->getOperand(3);
10773    if (Op.isGlobal()) {
10774      AM.GV = Op.getGlobal();
10775    } else {
10776      AM.Disp = Op.getImm();
10777    }
10778    addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
10779                      .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
10780
10781    // Reload the original control word now.
10782    addFrameReference(BuildMI(*BB, MI, DL,
10783                              TII->get(X86::FLDCW16m)), CWFrameIdx);
10784
10785    MI->eraseFromParent();   // The pseudo instruction is gone now.
10786    return BB;
10787  }
10788    // String/text processing lowering.
10789  case X86::PCMPISTRM128REG:
10790  case X86::VPCMPISTRM128REG:
10791    return EmitPCMP(MI, BB, 3, false /* in-mem */);
10792  case X86::PCMPISTRM128MEM:
10793  case X86::VPCMPISTRM128MEM:
10794    return EmitPCMP(MI, BB, 3, true /* in-mem */);
10795  case X86::PCMPESTRM128REG:
10796  case X86::VPCMPESTRM128REG:
10797    return EmitPCMP(MI, BB, 5, false /* in mem */);
10798  case X86::PCMPESTRM128MEM:
10799  case X86::VPCMPESTRM128MEM:
10800    return EmitPCMP(MI, BB, 5, true /* in mem */);
10801
10802    // Thread synchronization.
10803  case X86::MONITOR:
10804    return EmitMonitor(MI, BB);
10805  case X86::MWAIT:
10806    return EmitMwait(MI, BB);
10807
10808    // Atomic Lowering.
10809  case X86::ATOMAND32:
10810    return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
10811                                               X86::AND32ri, X86::MOV32rm,
10812                                               X86::LCMPXCHG32,
10813                                               X86::NOT32r, X86::EAX,
10814                                               X86::GR32RegisterClass);
10815  case X86::ATOMOR32:
10816    return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR32rr,
10817                                               X86::OR32ri, X86::MOV32rm,
10818                                               X86::LCMPXCHG32,
10819                                               X86::NOT32r, X86::EAX,
10820                                               X86::GR32RegisterClass);
10821  case X86::ATOMXOR32:
10822    return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR32rr,
10823                                               X86::XOR32ri, X86::MOV32rm,
10824                                               X86::LCMPXCHG32,
10825                                               X86::NOT32r, X86::EAX,
10826                                               X86::GR32RegisterClass);
10827  case X86::ATOMNAND32:
10828    return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
10829                                               X86::AND32ri, X86::MOV32rm,
10830                                               X86::LCMPXCHG32,
10831                                               X86::NOT32r, X86::EAX,
10832                                               X86::GR32RegisterClass, true);
10833  case X86::ATOMMIN32:
10834    return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL32rr);
10835  case X86::ATOMMAX32:
10836    return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG32rr);
10837  case X86::ATOMUMIN32:
10838    return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB32rr);
10839  case X86::ATOMUMAX32:
10840    return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA32rr);
10841
10842  case X86::ATOMAND16:
10843    return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
10844                                               X86::AND16ri, X86::MOV16rm,
10845                                               X86::LCMPXCHG16,
10846                                               X86::NOT16r, X86::AX,
10847                                               X86::GR16RegisterClass);
10848  case X86::ATOMOR16:
10849    return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR16rr,
10850                                               X86::OR16ri, X86::MOV16rm,
10851                                               X86::LCMPXCHG16,
10852                                               X86::NOT16r, X86::AX,
10853                                               X86::GR16RegisterClass);
10854  case X86::ATOMXOR16:
10855    return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR16rr,
10856                                               X86::XOR16ri, X86::MOV16rm,
10857                                               X86::LCMPXCHG16,
10858                                               X86::NOT16r, X86::AX,
10859                                               X86::GR16RegisterClass);
10860  case X86::ATOMNAND16:
10861    return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
10862                                               X86::AND16ri, X86::MOV16rm,
10863                                               X86::LCMPXCHG16,
10864                                               X86::NOT16r, X86::AX,
10865                                               X86::GR16RegisterClass, true);
10866  case X86::ATOMMIN16:
10867    return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL16rr);
10868  case X86::ATOMMAX16:
10869    return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG16rr);
10870  case X86::ATOMUMIN16:
10871    return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB16rr);
10872  case X86::ATOMUMAX16:
10873    return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA16rr);
10874
10875  case X86::ATOMAND8:
10876    return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
10877                                               X86::AND8ri, X86::MOV8rm,
10878                                               X86::LCMPXCHG8,
10879                                               X86::NOT8r, X86::AL,
10880                                               X86::GR8RegisterClass);
10881  case X86::ATOMOR8:
10882    return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR8rr,
10883                                               X86::OR8ri, X86::MOV8rm,
10884                                               X86::LCMPXCHG8,
10885                                               X86::NOT8r, X86::AL,
10886                                               X86::GR8RegisterClass);
10887  case X86::ATOMXOR8:
10888    return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR8rr,
10889                                               X86::XOR8ri, X86::MOV8rm,
10890                                               X86::LCMPXCHG8,
10891                                               X86::NOT8r, X86::AL,
10892                                               X86::GR8RegisterClass);
10893  case X86::ATOMNAND8:
10894    return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
10895                                               X86::AND8ri, X86::MOV8rm,
10896                                               X86::LCMPXCHG8,
10897                                               X86::NOT8r, X86::AL,
10898                                               X86::GR8RegisterClass, true);
10899  // FIXME: There are no CMOV8 instructions; MIN/MAX need some other way.
10900  // This group is for 64-bit host.
10901  case X86::ATOMAND64:
10902    return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
10903                                               X86::AND64ri32, X86::MOV64rm,
10904                                               X86::LCMPXCHG64,
10905                                               X86::NOT64r, X86::RAX,
10906                                               X86::GR64RegisterClass);
10907  case X86::ATOMOR64:
10908    return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR64rr,
10909                                               X86::OR64ri32, X86::MOV64rm,
10910                                               X86::LCMPXCHG64,
10911                                               X86::NOT64r, X86::RAX,
10912                                               X86::GR64RegisterClass);
10913  case X86::ATOMXOR64:
10914    return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR64rr,
10915                                               X86::XOR64ri32, X86::MOV64rm,
10916                                               X86::LCMPXCHG64,
10917                                               X86::NOT64r, X86::RAX,
10918                                               X86::GR64RegisterClass);
10919  case X86::ATOMNAND64:
10920    return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
10921                                               X86::AND64ri32, X86::MOV64rm,
10922                                               X86::LCMPXCHG64,
10923                                               X86::NOT64r, X86::RAX,
10924                                               X86::GR64RegisterClass, true);
10925  case X86::ATOMMIN64:
10926    return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL64rr);
10927  case X86::ATOMMAX64:
10928    return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG64rr);
10929  case X86::ATOMUMIN64:
10930    return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB64rr);
10931  case X86::ATOMUMAX64:
10932    return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA64rr);
10933
10934  // This group does 64-bit operations on a 32-bit host.
10935  case X86::ATOMAND6432:
10936    return EmitAtomicBit6432WithCustomInserter(MI, BB,
10937                                               X86::AND32rr, X86::AND32rr,
10938                                               X86::AND32ri, X86::AND32ri,
10939                                               false);
10940  case X86::ATOMOR6432:
10941    return EmitAtomicBit6432WithCustomInserter(MI, BB,
10942                                               X86::OR32rr, X86::OR32rr,
10943                                               X86::OR32ri, X86::OR32ri,
10944                                               false);
10945  case X86::ATOMXOR6432:
10946    return EmitAtomicBit6432WithCustomInserter(MI, BB,
10947                                               X86::XOR32rr, X86::XOR32rr,
10948                                               X86::XOR32ri, X86::XOR32ri,
10949                                               false);
10950  case X86::ATOMNAND6432:
10951    return EmitAtomicBit6432WithCustomInserter(MI, BB,
10952                                               X86::AND32rr, X86::AND32rr,
10953                                               X86::AND32ri, X86::AND32ri,
10954                                               true);
10955  case X86::ATOMADD6432:
10956    return EmitAtomicBit6432WithCustomInserter(MI, BB,
10957                                               X86::ADD32rr, X86::ADC32rr,
10958                                               X86::ADD32ri, X86::ADC32ri,
10959                                               false);
10960  case X86::ATOMSUB6432:
10961    return EmitAtomicBit6432WithCustomInserter(MI, BB,
10962                                               X86::SUB32rr, X86::SBB32rr,
10963                                               X86::SUB32ri, X86::SBB32ri,
10964                                               false);
10965  case X86::ATOMSWAP6432:
10966    return EmitAtomicBit6432WithCustomInserter(MI, BB,
10967                                               X86::MOV32rr, X86::MOV32rr,
10968                                               X86::MOV32ri, X86::MOV32ri,
10969                                               false);
10970  case X86::VASTART_SAVE_XMM_REGS:
10971    return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
10972
10973  case X86::VAARG_64:
10974    return EmitVAARG64WithCustomInserter(MI, BB);
10975  }
10976}
10977
10978//===----------------------------------------------------------------------===//
10979//                           X86 Optimization Hooks
10980//===----------------------------------------------------------------------===//
10981
10982void X86TargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
10983                                                       const APInt &Mask,
10984                                                       APInt &KnownZero,
10985                                                       APInt &KnownOne,
10986                                                       const SelectionDAG &DAG,
10987                                                       unsigned Depth) const {
10988  unsigned Opc = Op.getOpcode();
10989  assert((Opc >= ISD::BUILTIN_OP_END ||
10990          Opc == ISD::INTRINSIC_WO_CHAIN ||
10991          Opc == ISD::INTRINSIC_W_CHAIN ||
10992          Opc == ISD::INTRINSIC_VOID) &&
10993         "Should use MaskedValueIsZero if you don't know whether Op"
10994         " is a target node!");
10995
10996  KnownZero = KnownOne = APInt(Mask.getBitWidth(), 0);   // Don't know anything.
10997  switch (Opc) {
10998  default: break;
10999  case X86ISD::ADD:
11000  case X86ISD::SUB:
11001  case X86ISD::ADC:
11002  case X86ISD::SBB:
11003  case X86ISD::SMUL:
11004  case X86ISD::UMUL:
11005  case X86ISD::INC:
11006  case X86ISD::DEC:
11007  case X86ISD::OR:
11008  case X86ISD::XOR:
11009  case X86ISD::AND:
11010    // These nodes' second result is a boolean.
11011    if (Op.getResNo() == 0)
11012      break;
11013    // Fallthrough
11014  case X86ISD::SETCC:
11015    KnownZero |= APInt::getHighBitsSet(Mask.getBitWidth(),
11016                                       Mask.getBitWidth() - 1);
11017    break;
11018  }
11019}
11020
11021unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(SDValue Op,
11022                                                         unsigned Depth) const {
11023  // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
11024  if (Op.getOpcode() == X86ISD::SETCC_CARRY)
11025    return Op.getValueType().getScalarType().getSizeInBits();
11026
11027  // Fallback case.
11028  return 1;
11029}
11030
11031/// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
11032/// node is a GlobalAddress + offset.
11033bool X86TargetLowering::isGAPlusOffset(SDNode *N,
11034                                       const GlobalValue* &GA,
11035                                       int64_t &Offset) const {
11036  if (N->getOpcode() == X86ISD::Wrapper) {
11037    if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
11038      GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
11039      Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
11040      return true;
11041    }
11042  }
11043  return TargetLowering::isGAPlusOffset(N, GA, Offset);
11044}
11045
11046/// PerformShuffleCombine - Combine a vector_shuffle that is equal to
11047/// build_vector load1, load2, load3, load4, <0, 1, 2, 3> into a 128-bit load
11048/// if the load addresses are consecutive, non-overlapping, and in the right
11049/// order.
11050static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
11051                                     TargetLowering::DAGCombinerInfo &DCI) {
11052  DebugLoc dl = N->getDebugLoc();
11053  EVT VT = N->getValueType(0);
11054
11055  if (VT.getSizeInBits() != 128)
11056    return SDValue();
11057
11058  // Don't create instructions with illegal types after legalize types has run.
11059  const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11060  if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
11061    return SDValue();
11062
11063  SmallVector<SDValue, 16> Elts;
11064  for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
11065    Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
11066
11067  return EltsFromConsecutiveLoads(VT, Elts, dl, DAG);
11068}
11069
11070/// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
11071/// generation and convert it from being a bunch of shuffles and extracts
11072/// to a simple store and scalar loads to extract the elements.
11073static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
11074                                                const TargetLowering &TLI) {
11075  SDValue InputVector = N->getOperand(0);
11076
11077  // Only operate on vectors of 4 elements, where the alternative shuffling
11078  // gets to be more expensive.
11079  if (InputVector.getValueType() != MVT::v4i32)
11080    return SDValue();
11081
11082  // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
11083  // single use which is a sign-extend or zero-extend, and all elements are
11084  // used.
11085  SmallVector<SDNode *, 4> Uses;
11086  unsigned ExtractedElements = 0;
11087  for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
11088       UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
11089    if (UI.getUse().getResNo() != InputVector.getResNo())
11090      return SDValue();
11091
11092    SDNode *Extract = *UI;
11093    if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
11094      return SDValue();
11095
11096    if (Extract->getValueType(0) != MVT::i32)
11097      return SDValue();
11098    if (!Extract->hasOneUse())
11099      return SDValue();
11100    if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
11101        Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
11102      return SDValue();
11103    if (!isa<ConstantSDNode>(Extract->getOperand(1)))
11104      return SDValue();
11105
11106    // Record which element was extracted.
11107    ExtractedElements |=
11108      1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
11109
11110    Uses.push_back(Extract);
11111  }
11112
11113  // If not all the elements were used, this may not be worthwhile.
11114  if (ExtractedElements != 15)
11115    return SDValue();
11116
11117  // Ok, we've now decided to do the transformation.
11118  DebugLoc dl = InputVector.getDebugLoc();
11119
11120  // Store the value to a temporary stack slot.
11121  SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
11122  SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
11123                            MachinePointerInfo(), false, false, 0);
11124
11125  // Replace each use (extract) with a load of the appropriate element.
11126  for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
11127       UE = Uses.end(); UI != UE; ++UI) {
11128    SDNode *Extract = *UI;
11129
11130    // cOMpute the element's address.
11131    SDValue Idx = Extract->getOperand(1);
11132    unsigned EltSize =
11133        InputVector.getValueType().getVectorElementType().getSizeInBits()/8;
11134    uint64_t Offset = EltSize * cast<ConstantSDNode>(Idx)->getZExtValue();
11135    SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy());
11136
11137    SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(),
11138                                     StackPtr, OffsetVal);
11139
11140    // Load the scalar.
11141    SDValue LoadScalar = DAG.getLoad(Extract->getValueType(0), dl, Ch,
11142                                     ScalarAddr, MachinePointerInfo(),
11143                                     false, false, 0);
11144
11145    // Replace the exact with the load.
11146    DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), LoadScalar);
11147  }
11148
11149  // The replacement was made in place; don't return anything.
11150  return SDValue();
11151}
11152
11153/// PerformSELECTCombine - Do target-specific dag combines on SELECT nodes.
11154static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
11155                                    const X86Subtarget *Subtarget) {
11156  DebugLoc DL = N->getDebugLoc();
11157  SDValue Cond = N->getOperand(0);
11158  // Get the LHS/RHS of the select.
11159  SDValue LHS = N->getOperand(1);
11160  SDValue RHS = N->getOperand(2);
11161
11162  // If we have SSE[12] support, try to form min/max nodes. SSE min/max
11163  // instructions match the semantics of the common C idiom x<y?x:y but not
11164  // x<=y?x:y, because of how they handle negative zero (which can be
11165  // ignored in unsafe-math mode).
11166  if (Subtarget->hasSSE2() &&
11167      (LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64) &&
11168      Cond.getOpcode() == ISD::SETCC) {
11169    ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
11170
11171    unsigned Opcode = 0;
11172    // Check for x CC y ? x : y.
11173    if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
11174        DAG.isEqualTo(RHS, Cond.getOperand(1))) {
11175      switch (CC) {
11176      default: break;
11177      case ISD::SETULT:
11178        // Converting this to a min would handle NaNs incorrectly, and swapping
11179        // the operands would cause it to handle comparisons between positive
11180        // and negative zero incorrectly.
11181        if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
11182          if (!UnsafeFPMath &&
11183              !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
11184            break;
11185          std::swap(LHS, RHS);
11186        }
11187        Opcode = X86ISD::FMIN;
11188        break;
11189      case ISD::SETOLE:
11190        // Converting this to a min would handle comparisons between positive
11191        // and negative zero incorrectly.
11192        if (!UnsafeFPMath &&
11193            !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
11194          break;
11195        Opcode = X86ISD::FMIN;
11196        break;
11197      case ISD::SETULE:
11198        // Converting this to a min would handle both negative zeros and NaNs
11199        // incorrectly, but we can swap the operands to fix both.
11200        std::swap(LHS, RHS);
11201      case ISD::SETOLT:
11202      case ISD::SETLT:
11203      case ISD::SETLE:
11204        Opcode = X86ISD::FMIN;
11205        break;
11206
11207      case ISD::SETOGE:
11208        // Converting this to a max would handle comparisons between positive
11209        // and negative zero incorrectly.
11210        if (!UnsafeFPMath &&
11211            !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(LHS))
11212          break;
11213        Opcode = X86ISD::FMAX;
11214        break;
11215      case ISD::SETUGT:
11216        // Converting this to a max would handle NaNs incorrectly, and swapping
11217        // the operands would cause it to handle comparisons between positive
11218        // and negative zero incorrectly.
11219        if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
11220          if (!UnsafeFPMath &&
11221              !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
11222            break;
11223          std::swap(LHS, RHS);
11224        }
11225        Opcode = X86ISD::FMAX;
11226        break;
11227      case ISD::SETUGE:
11228        // Converting this to a max would handle both negative zeros and NaNs
11229        // incorrectly, but we can swap the operands to fix both.
11230        std::swap(LHS, RHS);
11231      case ISD::SETOGT:
11232      case ISD::SETGT:
11233      case ISD::SETGE:
11234        Opcode = X86ISD::FMAX;
11235        break;
11236      }
11237    // Check for x CC y ? y : x -- a min/max with reversed arms.
11238    } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
11239               DAG.isEqualTo(RHS, Cond.getOperand(0))) {
11240      switch (CC) {
11241      default: break;
11242      case ISD::SETOGE:
11243        // Converting this to a min would handle comparisons between positive
11244        // and negative zero incorrectly, and swapping the operands would
11245        // cause it to handle NaNs incorrectly.
11246        if (!UnsafeFPMath &&
11247            !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
11248          if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
11249            break;
11250          std::swap(LHS, RHS);
11251        }
11252        Opcode = X86ISD::FMIN;
11253        break;
11254      case ISD::SETUGT:
11255        // Converting this to a min would handle NaNs incorrectly.
11256        if (!UnsafeFPMath &&
11257            (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
11258          break;
11259        Opcode = X86ISD::FMIN;
11260        break;
11261      case ISD::SETUGE:
11262        // Converting this to a min would handle both negative zeros and NaNs
11263        // incorrectly, but we can swap the operands to fix both.
11264        std::swap(LHS, RHS);
11265      case ISD::SETOGT:
11266      case ISD::SETGT:
11267      case ISD::SETGE:
11268        Opcode = X86ISD::FMIN;
11269        break;
11270
11271      case ISD::SETULT:
11272        // Converting this to a max would handle NaNs incorrectly.
11273        if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
11274          break;
11275        Opcode = X86ISD::FMAX;
11276        break;
11277      case ISD::SETOLE:
11278        // Converting this to a max would handle comparisons between positive
11279        // and negative zero incorrectly, and swapping the operands would
11280        // cause it to handle NaNs incorrectly.
11281        if (!UnsafeFPMath &&
11282            !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
11283          if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
11284            break;
11285          std::swap(LHS, RHS);
11286        }
11287        Opcode = X86ISD::FMAX;
11288        break;
11289      case ISD::SETULE:
11290        // Converting this to a max would handle both negative zeros and NaNs
11291        // incorrectly, but we can swap the operands to fix both.
11292        std::swap(LHS, RHS);
11293      case ISD::SETOLT:
11294      case ISD::SETLT:
11295      case ISD::SETLE:
11296        Opcode = X86ISD::FMAX;
11297        break;
11298      }
11299    }
11300
11301    if (Opcode)
11302      return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
11303  }
11304
11305  // If this is a select between two integer constants, try to do some
11306  // optimizations.
11307  if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
11308    if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
11309      // Don't do this for crazy integer types.
11310      if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
11311        // If this is efficiently invertible, canonicalize the LHSC/RHSC values
11312        // so that TrueC (the true value) is larger than FalseC.
11313        bool NeedsCondInvert = false;
11314
11315        if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
11316            // Efficiently invertible.
11317            (Cond.getOpcode() == ISD::SETCC ||  // setcc -> invertible.
11318             (Cond.getOpcode() == ISD::XOR &&   // xor(X, C) -> invertible.
11319              isa<ConstantSDNode>(Cond.getOperand(1))))) {
11320          NeedsCondInvert = true;
11321          std::swap(TrueC, FalseC);
11322        }
11323
11324        // Optimize C ? 8 : 0 -> zext(C) << 3.  Likewise for any pow2/0.
11325        if (FalseC->getAPIntValue() == 0 &&
11326            TrueC->getAPIntValue().isPowerOf2()) {
11327          if (NeedsCondInvert) // Invert the condition if needed.
11328            Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
11329                               DAG.getConstant(1, Cond.getValueType()));
11330
11331          // Zero extend the condition if needed.
11332          Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
11333
11334          unsigned ShAmt = TrueC->getAPIntValue().logBase2();
11335          return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
11336                             DAG.getConstant(ShAmt, MVT::i8));
11337        }
11338
11339        // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
11340        if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
11341          if (NeedsCondInvert) // Invert the condition if needed.
11342            Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
11343                               DAG.getConstant(1, Cond.getValueType()));
11344
11345          // Zero extend the condition if needed.
11346          Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
11347                             FalseC->getValueType(0), Cond);
11348          return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
11349                             SDValue(FalseC, 0));
11350        }
11351
11352        // Optimize cases that will turn into an LEA instruction.  This requires
11353        // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
11354        if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
11355          uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
11356          if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
11357
11358          bool isFastMultiplier = false;
11359          if (Diff < 10) {
11360            switch ((unsigned char)Diff) {
11361              default: break;
11362              case 1:  // result = add base, cond
11363              case 2:  // result = lea base(    , cond*2)
11364              case 3:  // result = lea base(cond, cond*2)
11365              case 4:  // result = lea base(    , cond*4)
11366              case 5:  // result = lea base(cond, cond*4)
11367              case 8:  // result = lea base(    , cond*8)
11368              case 9:  // result = lea base(cond, cond*8)
11369                isFastMultiplier = true;
11370                break;
11371            }
11372          }
11373
11374          if (isFastMultiplier) {
11375            APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
11376            if (NeedsCondInvert) // Invert the condition if needed.
11377              Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
11378                                 DAG.getConstant(1, Cond.getValueType()));
11379
11380            // Zero extend the condition if needed.
11381            Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
11382                               Cond);
11383            // Scale the condition by the difference.
11384            if (Diff != 1)
11385              Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
11386                                 DAG.getConstant(Diff, Cond.getValueType()));
11387
11388            // Add the base if non-zero.
11389            if (FalseC->getAPIntValue() != 0)
11390              Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
11391                                 SDValue(FalseC, 0));
11392            return Cond;
11393          }
11394        }
11395      }
11396  }
11397
11398  return SDValue();
11399}
11400
11401/// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
11402static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
11403                                  TargetLowering::DAGCombinerInfo &DCI) {
11404  DebugLoc DL = N->getDebugLoc();
11405
11406  // If the flag operand isn't dead, don't touch this CMOV.
11407  if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
11408    return SDValue();
11409
11410  SDValue FalseOp = N->getOperand(0);
11411  SDValue TrueOp = N->getOperand(1);
11412  X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
11413  SDValue Cond = N->getOperand(3);
11414  if (CC == X86::COND_E || CC == X86::COND_NE) {
11415    switch (Cond.getOpcode()) {
11416    default: break;
11417    case X86ISD::BSR:
11418    case X86ISD::BSF:
11419      // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
11420      if (DAG.isKnownNeverZero(Cond.getOperand(0)))
11421        return (CC == X86::COND_E) ? FalseOp : TrueOp;
11422    }
11423  }
11424
11425  // If this is a select between two integer constants, try to do some
11426  // optimizations.  Note that the operands are ordered the opposite of SELECT
11427  // operands.
11428  if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
11429    if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
11430      // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
11431      // larger than FalseC (the false value).
11432      if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
11433        CC = X86::GetOppositeBranchCondition(CC);
11434        std::swap(TrueC, FalseC);
11435      }
11436
11437      // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3.  Likewise for any pow2/0.
11438      // This is efficient for any integer data type (including i8/i16) and
11439      // shift amount.
11440      if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
11441        Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
11442                           DAG.getConstant(CC, MVT::i8), Cond);
11443
11444        // Zero extend the condition if needed.
11445        Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
11446
11447        unsigned ShAmt = TrueC->getAPIntValue().logBase2();
11448        Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
11449                           DAG.getConstant(ShAmt, MVT::i8));
11450        if (N->getNumValues() == 2)  // Dead flag value?
11451          return DCI.CombineTo(N, Cond, SDValue());
11452        return Cond;
11453      }
11454
11455      // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.  This is efficient
11456      // for any integer data type, including i8/i16.
11457      if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
11458        Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
11459                           DAG.getConstant(CC, MVT::i8), Cond);
11460
11461        // Zero extend the condition if needed.
11462        Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
11463                           FalseC->getValueType(0), Cond);
11464        Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
11465                           SDValue(FalseC, 0));
11466
11467        if (N->getNumValues() == 2)  // Dead flag value?
11468          return DCI.CombineTo(N, Cond, SDValue());
11469        return Cond;
11470      }
11471
11472      // Optimize cases that will turn into an LEA instruction.  This requires
11473      // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
11474      if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
11475        uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
11476        if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
11477
11478        bool isFastMultiplier = false;
11479        if (Diff < 10) {
11480          switch ((unsigned char)Diff) {
11481          default: break;
11482          case 1:  // result = add base, cond
11483          case 2:  // result = lea base(    , cond*2)
11484          case 3:  // result = lea base(cond, cond*2)
11485          case 4:  // result = lea base(    , cond*4)
11486          case 5:  // result = lea base(cond, cond*4)
11487          case 8:  // result = lea base(    , cond*8)
11488          case 9:  // result = lea base(cond, cond*8)
11489            isFastMultiplier = true;
11490            break;
11491          }
11492        }
11493
11494        if (isFastMultiplier) {
11495          APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
11496          Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
11497                             DAG.getConstant(CC, MVT::i8), Cond);
11498          // Zero extend the condition if needed.
11499          Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
11500                             Cond);
11501          // Scale the condition by the difference.
11502          if (Diff != 1)
11503            Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
11504                               DAG.getConstant(Diff, Cond.getValueType()));
11505
11506          // Add the base if non-zero.
11507          if (FalseC->getAPIntValue() != 0)
11508            Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
11509                               SDValue(FalseC, 0));
11510          if (N->getNumValues() == 2)  // Dead flag value?
11511            return DCI.CombineTo(N, Cond, SDValue());
11512          return Cond;
11513        }
11514      }
11515    }
11516  }
11517  return SDValue();
11518}
11519
11520
11521/// PerformMulCombine - Optimize a single multiply with constant into two
11522/// in order to implement it with two cheaper instructions, e.g.
11523/// LEA + SHL, LEA + LEA.
11524static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
11525                                 TargetLowering::DAGCombinerInfo &DCI) {
11526  if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
11527    return SDValue();
11528
11529  EVT VT = N->getValueType(0);
11530  if (VT != MVT::i64)
11531    return SDValue();
11532
11533  ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
11534  if (!C)
11535    return SDValue();
11536  uint64_t MulAmt = C->getZExtValue();
11537  if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
11538    return SDValue();
11539
11540  uint64_t MulAmt1 = 0;
11541  uint64_t MulAmt2 = 0;
11542  if ((MulAmt % 9) == 0) {
11543    MulAmt1 = 9;
11544    MulAmt2 = MulAmt / 9;
11545  } else if ((MulAmt % 5) == 0) {
11546    MulAmt1 = 5;
11547    MulAmt2 = MulAmt / 5;
11548  } else if ((MulAmt % 3) == 0) {
11549    MulAmt1 = 3;
11550    MulAmt2 = MulAmt / 3;
11551  }
11552  if (MulAmt2 &&
11553      (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
11554    DebugLoc DL = N->getDebugLoc();
11555
11556    if (isPowerOf2_64(MulAmt2) &&
11557        !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
11558      // If second multiplifer is pow2, issue it first. We want the multiply by
11559      // 3, 5, or 9 to be folded into the addressing mode unless the lone use
11560      // is an add.
11561      std::swap(MulAmt1, MulAmt2);
11562
11563    SDValue NewMul;
11564    if (isPowerOf2_64(MulAmt1))
11565      NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
11566                           DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
11567    else
11568      NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
11569                           DAG.getConstant(MulAmt1, VT));
11570
11571    if (isPowerOf2_64(MulAmt2))
11572      NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
11573                           DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
11574    else
11575      NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
11576                           DAG.getConstant(MulAmt2, VT));
11577
11578    // Do not add new nodes to DAG combiner worklist.
11579    DCI.CombineTo(N, NewMul, false);
11580  }
11581  return SDValue();
11582}
11583
11584static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
11585  SDValue N0 = N->getOperand(0);
11586  SDValue N1 = N->getOperand(1);
11587  ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
11588  EVT VT = N0.getValueType();
11589
11590  // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
11591  // since the result of setcc_c is all zero's or all ones.
11592  if (N1C && N0.getOpcode() == ISD::AND &&
11593      N0.getOperand(1).getOpcode() == ISD::Constant) {
11594    SDValue N00 = N0.getOperand(0);
11595    if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
11596        ((N00.getOpcode() == ISD::ANY_EXTEND ||
11597          N00.getOpcode() == ISD::ZERO_EXTEND) &&
11598         N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
11599      APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
11600      APInt ShAmt = N1C->getAPIntValue();
11601      Mask = Mask.shl(ShAmt);
11602      if (Mask != 0)
11603        return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
11604                           N00, DAG.getConstant(Mask, VT));
11605    }
11606  }
11607
11608  return SDValue();
11609}
11610
11611/// PerformShiftCombine - Transforms vector shift nodes to use vector shifts
11612///                       when possible.
11613static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
11614                                   const X86Subtarget *Subtarget) {
11615  EVT VT = N->getValueType(0);
11616  if (!VT.isVector() && VT.isInteger() &&
11617      N->getOpcode() == ISD::SHL)
11618    return PerformSHLCombine(N, DAG);
11619
11620  // On X86 with SSE2 support, we can transform this to a vector shift if
11621  // all elements are shifted by the same amount.  We can't do this in legalize
11622  // because the a constant vector is typically transformed to a constant pool
11623  // so we have no knowledge of the shift amount.
11624  if (!Subtarget->hasSSE2())
11625    return SDValue();
11626
11627  if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16)
11628    return SDValue();
11629
11630  SDValue ShAmtOp = N->getOperand(1);
11631  EVT EltVT = VT.getVectorElementType();
11632  DebugLoc DL = N->getDebugLoc();
11633  SDValue BaseShAmt = SDValue();
11634  if (ShAmtOp.getOpcode() == ISD::BUILD_VECTOR) {
11635    unsigned NumElts = VT.getVectorNumElements();
11636    unsigned i = 0;
11637    for (; i != NumElts; ++i) {
11638      SDValue Arg = ShAmtOp.getOperand(i);
11639      if (Arg.getOpcode() == ISD::UNDEF) continue;
11640      BaseShAmt = Arg;
11641      break;
11642    }
11643    for (; i != NumElts; ++i) {
11644      SDValue Arg = ShAmtOp.getOperand(i);
11645      if (Arg.getOpcode() == ISD::UNDEF) continue;
11646      if (Arg != BaseShAmt) {
11647        return SDValue();
11648      }
11649    }
11650  } else if (ShAmtOp.getOpcode() == ISD::VECTOR_SHUFFLE &&
11651             cast<ShuffleVectorSDNode>(ShAmtOp)->isSplat()) {
11652    SDValue InVec = ShAmtOp.getOperand(0);
11653    if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
11654      unsigned NumElts = InVec.getValueType().getVectorNumElements();
11655      unsigned i = 0;
11656      for (; i != NumElts; ++i) {
11657        SDValue Arg = InVec.getOperand(i);
11658        if (Arg.getOpcode() == ISD::UNDEF) continue;
11659        BaseShAmt = Arg;
11660        break;
11661      }
11662    } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
11663       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
11664         unsigned SplatIdx= cast<ShuffleVectorSDNode>(ShAmtOp)->getSplatIndex();
11665         if (C->getZExtValue() == SplatIdx)
11666           BaseShAmt = InVec.getOperand(1);
11667       }
11668    }
11669    if (BaseShAmt.getNode() == 0)
11670      BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, ShAmtOp,
11671                              DAG.getIntPtrConstant(0));
11672  } else
11673    return SDValue();
11674
11675  // The shift amount is an i32.
11676  if (EltVT.bitsGT(MVT::i32))
11677    BaseShAmt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, BaseShAmt);
11678  else if (EltVT.bitsLT(MVT::i32))
11679    BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, BaseShAmt);
11680
11681  // The shift amount is identical so we can do a vector shift.
11682  SDValue  ValOp = N->getOperand(0);
11683  switch (N->getOpcode()) {
11684  default:
11685    llvm_unreachable("Unknown shift opcode!");
11686    break;
11687  case ISD::SHL:
11688    if (VT == MVT::v2i64)
11689      return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11690                         DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
11691                         ValOp, BaseShAmt);
11692    if (VT == MVT::v4i32)
11693      return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11694                         DAG.getConstant(Intrinsic::x86_sse2_pslli_d, MVT::i32),
11695                         ValOp, BaseShAmt);
11696    if (VT == MVT::v8i16)
11697      return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11698                         DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32),
11699                         ValOp, BaseShAmt);
11700    break;
11701  case ISD::SRA:
11702    if (VT == MVT::v4i32)
11703      return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11704                         DAG.getConstant(Intrinsic::x86_sse2_psrai_d, MVT::i32),
11705                         ValOp, BaseShAmt);
11706    if (VT == MVT::v8i16)
11707      return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11708                         DAG.getConstant(Intrinsic::x86_sse2_psrai_w, MVT::i32),
11709                         ValOp, BaseShAmt);
11710    break;
11711  case ISD::SRL:
11712    if (VT == MVT::v2i64)
11713      return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11714                         DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
11715                         ValOp, BaseShAmt);
11716    if (VT == MVT::v4i32)
11717      return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11718                         DAG.getConstant(Intrinsic::x86_sse2_psrli_d, MVT::i32),
11719                         ValOp, BaseShAmt);
11720    if (VT ==  MVT::v8i16)
11721      return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11722                         DAG.getConstant(Intrinsic::x86_sse2_psrli_w, MVT::i32),
11723                         ValOp, BaseShAmt);
11724    break;
11725  }
11726  return SDValue();
11727}
11728
11729
11730// CMPEQCombine - Recognize the distinctive  (AND (setcc ...) (setcc ..))
11731// where both setccs reference the same FP CMP, and rewrite for CMPEQSS
11732// and friends.  Likewise for OR -> CMPNEQSS.
11733static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
11734                            TargetLowering::DAGCombinerInfo &DCI,
11735                            const X86Subtarget *Subtarget) {
11736  unsigned opcode;
11737
11738  // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
11739  // we're requiring SSE2 for both.
11740  if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
11741    SDValue N0 = N->getOperand(0);
11742    SDValue N1 = N->getOperand(1);
11743    SDValue CMP0 = N0->getOperand(1);
11744    SDValue CMP1 = N1->getOperand(1);
11745    DebugLoc DL = N->getDebugLoc();
11746
11747    // The SETCCs should both refer to the same CMP.
11748    if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
11749      return SDValue();
11750
11751    SDValue CMP00 = CMP0->getOperand(0);
11752    SDValue CMP01 = CMP0->getOperand(1);
11753    EVT     VT    = CMP00.getValueType();
11754
11755    if (VT == MVT::f32 || VT == MVT::f64) {
11756      bool ExpectingFlags = false;
11757      // Check for any users that want flags:
11758      for (SDNode::use_iterator UI = N->use_begin(),
11759             UE = N->use_end();
11760           !ExpectingFlags && UI != UE; ++UI)
11761        switch (UI->getOpcode()) {
11762        default:
11763        case ISD::BR_CC:
11764        case ISD::BRCOND:
11765        case ISD::SELECT:
11766          ExpectingFlags = true;
11767          break;
11768        case ISD::CopyToReg:
11769        case ISD::SIGN_EXTEND:
11770        case ISD::ZERO_EXTEND:
11771        case ISD::ANY_EXTEND:
11772          break;
11773        }
11774
11775      if (!ExpectingFlags) {
11776        enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
11777        enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
11778
11779        if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
11780          X86::CondCode tmp = cc0;
11781          cc0 = cc1;
11782          cc1 = tmp;
11783        }
11784
11785        if ((cc0 == X86::COND_E  && cc1 == X86::COND_NP) ||
11786            (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
11787          bool is64BitFP = (CMP00.getValueType() == MVT::f64);
11788          X86ISD::NodeType NTOperator = is64BitFP ?
11789            X86ISD::FSETCCsd : X86ISD::FSETCCss;
11790          // FIXME: need symbolic constants for these magic numbers.
11791          // See X86ATTInstPrinter.cpp:printSSECC().
11792          unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
11793          SDValue OnesOrZeroesF = DAG.getNode(NTOperator, DL, MVT::f32, CMP00, CMP01,
11794                                              DAG.getConstant(x86cc, MVT::i8));
11795          SDValue OnesOrZeroesI = DAG.getNode(ISD::BITCAST, DL, MVT::i32,
11796                                              OnesOrZeroesF);
11797          SDValue ANDed = DAG.getNode(ISD::AND, DL, MVT::i32, OnesOrZeroesI,
11798                                      DAG.getConstant(1, MVT::i32));
11799          SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8, ANDed);
11800          return OneBitOfTruth;
11801        }
11802      }
11803    }
11804  }
11805  return SDValue();
11806}
11807
11808static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
11809                                 TargetLowering::DAGCombinerInfo &DCI,
11810                                 const X86Subtarget *Subtarget) {
11811  if (DCI.isBeforeLegalizeOps())
11812    return SDValue();
11813
11814  SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
11815  if (R.getNode())
11816    return R;
11817
11818  // Want to form PANDN nodes, in the hopes of then easily combining them with
11819  // OR and AND nodes to form PBLEND/PSIGN.
11820  EVT VT = N->getValueType(0);
11821  if (VT != MVT::v2i64)
11822    return SDValue();
11823
11824  SDValue N0 = N->getOperand(0);
11825  SDValue N1 = N->getOperand(1);
11826  DebugLoc DL = N->getDebugLoc();
11827
11828  // Check LHS for vnot
11829  if (N0.getOpcode() == ISD::XOR &&
11830      ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
11831    return DAG.getNode(X86ISD::PANDN, DL, VT, N0.getOperand(0), N1);
11832
11833  // Check RHS for vnot
11834  if (N1.getOpcode() == ISD::XOR &&
11835      ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
11836    return DAG.getNode(X86ISD::PANDN, DL, VT, N1.getOperand(0), N0);
11837
11838  return SDValue();
11839}
11840
11841static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
11842                                TargetLowering::DAGCombinerInfo &DCI,
11843                                const X86Subtarget *Subtarget) {
11844  if (DCI.isBeforeLegalizeOps())
11845    return SDValue();
11846
11847  SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
11848  if (R.getNode())
11849    return R;
11850
11851  EVT VT = N->getValueType(0);
11852  if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64 && VT != MVT::v2i64)
11853    return SDValue();
11854
11855  SDValue N0 = N->getOperand(0);
11856  SDValue N1 = N->getOperand(1);
11857
11858  // look for psign/blend
11859  if (Subtarget->hasSSSE3()) {
11860    if (VT == MVT::v2i64) {
11861      // Canonicalize pandn to RHS
11862      if (N0.getOpcode() == X86ISD::PANDN)
11863        std::swap(N0, N1);
11864      // or (and (m, x), (pandn m, y))
11865      if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::PANDN) {
11866        SDValue Mask = N1.getOperand(0);
11867        SDValue X    = N1.getOperand(1);
11868        SDValue Y;
11869        if (N0.getOperand(0) == Mask)
11870          Y = N0.getOperand(1);
11871        if (N0.getOperand(1) == Mask)
11872          Y = N0.getOperand(0);
11873
11874        // Check to see if the mask appeared in both the AND and PANDN and
11875        if (!Y.getNode())
11876          return SDValue();
11877
11878        // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
11879        if (Mask.getOpcode() != ISD::BITCAST ||
11880            X.getOpcode() != ISD::BITCAST ||
11881            Y.getOpcode() != ISD::BITCAST)
11882          return SDValue();
11883
11884        // Look through mask bitcast.
11885        Mask = Mask.getOperand(0);
11886        EVT MaskVT = Mask.getValueType();
11887
11888        // Validate that the Mask operand is a vector sra node.  The sra node
11889        // will be an intrinsic.
11890        if (Mask.getOpcode() != ISD::INTRINSIC_WO_CHAIN)
11891          return SDValue();
11892
11893        // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
11894        // there is no psrai.b
11895        switch (cast<ConstantSDNode>(Mask.getOperand(0))->getZExtValue()) {
11896        case Intrinsic::x86_sse2_psrai_w:
11897        case Intrinsic::x86_sse2_psrai_d:
11898          break;
11899        default: return SDValue();
11900        }
11901
11902        // Check that the SRA is all signbits.
11903        SDValue SraC = Mask.getOperand(2);
11904        unsigned SraAmt  = cast<ConstantSDNode>(SraC)->getZExtValue();
11905        unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
11906        if ((SraAmt + 1) != EltBits)
11907          return SDValue();
11908
11909        DebugLoc DL = N->getDebugLoc();
11910
11911        // Now we know we at least have a plendvb with the mask val.  See if
11912        // we can form a psignb/w/d.
11913        // psign = x.type == y.type == mask.type && y = sub(0, x);
11914        X = X.getOperand(0);
11915        Y = Y.getOperand(0);
11916        if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
11917            ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
11918            X.getValueType() == MaskVT && X.getValueType() == Y.getValueType()){
11919          unsigned Opc = 0;
11920          switch (EltBits) {
11921          case 8: Opc = X86ISD::PSIGNB; break;
11922          case 16: Opc = X86ISD::PSIGNW; break;
11923          case 32: Opc = X86ISD::PSIGND; break;
11924          default: break;
11925          }
11926          if (Opc) {
11927            SDValue Sign = DAG.getNode(Opc, DL, MaskVT, X, Mask.getOperand(1));
11928            return DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, Sign);
11929          }
11930        }
11931        // PBLENDVB only available on SSE 4.1
11932        if (!Subtarget->hasSSE41())
11933          return SDValue();
11934
11935        X = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, X);
11936        Y = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, Y);
11937        Mask = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, Mask);
11938        Mask = DAG.getNode(X86ISD::PBLENDVB, DL, MVT::v16i8, X, Y, Mask);
11939        return DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, Mask);
11940      }
11941    }
11942  }
11943
11944  // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
11945  if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
11946    std::swap(N0, N1);
11947  if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
11948    return SDValue();
11949  if (!N0.hasOneUse() || !N1.hasOneUse())
11950    return SDValue();
11951
11952  SDValue ShAmt0 = N0.getOperand(1);
11953  if (ShAmt0.getValueType() != MVT::i8)
11954    return SDValue();
11955  SDValue ShAmt1 = N1.getOperand(1);
11956  if (ShAmt1.getValueType() != MVT::i8)
11957    return SDValue();
11958  if (ShAmt0.getOpcode() == ISD::TRUNCATE)
11959    ShAmt0 = ShAmt0.getOperand(0);
11960  if (ShAmt1.getOpcode() == ISD::TRUNCATE)
11961    ShAmt1 = ShAmt1.getOperand(0);
11962
11963  DebugLoc DL = N->getDebugLoc();
11964  unsigned Opc = X86ISD::SHLD;
11965  SDValue Op0 = N0.getOperand(0);
11966  SDValue Op1 = N1.getOperand(0);
11967  if (ShAmt0.getOpcode() == ISD::SUB) {
11968    Opc = X86ISD::SHRD;
11969    std::swap(Op0, Op1);
11970    std::swap(ShAmt0, ShAmt1);
11971  }
11972
11973  unsigned Bits = VT.getSizeInBits();
11974  if (ShAmt1.getOpcode() == ISD::SUB) {
11975    SDValue Sum = ShAmt1.getOperand(0);
11976    if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
11977      SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
11978      if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
11979        ShAmt1Op1 = ShAmt1Op1.getOperand(0);
11980      if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
11981        return DAG.getNode(Opc, DL, VT,
11982                           Op0, Op1,
11983                           DAG.getNode(ISD::TRUNCATE, DL,
11984                                       MVT::i8, ShAmt0));
11985    }
11986  } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
11987    ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
11988    if (ShAmt0C &&
11989        ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
11990      return DAG.getNode(Opc, DL, VT,
11991                         N0.getOperand(0), N1.getOperand(0),
11992                         DAG.getNode(ISD::TRUNCATE, DL,
11993                                       MVT::i8, ShAmt0));
11994  }
11995
11996  return SDValue();
11997}
11998
11999/// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
12000static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
12001                                   const X86Subtarget *Subtarget) {
12002  // Turn load->store of MMX types into GPR load/stores.  This avoids clobbering
12003  // the FP state in cases where an emms may be missing.
12004  // A preferable solution to the general problem is to figure out the right
12005  // places to insert EMMS.  This qualifies as a quick hack.
12006
12007  // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
12008  StoreSDNode *St = cast<StoreSDNode>(N);
12009  EVT VT = St->getValue().getValueType();
12010  if (VT.getSizeInBits() != 64)
12011    return SDValue();
12012
12013  const Function *F = DAG.getMachineFunction().getFunction();
12014  bool NoImplicitFloatOps = F->hasFnAttr(Attribute::NoImplicitFloat);
12015  bool F64IsLegal = !UseSoftFloat && !NoImplicitFloatOps
12016    && Subtarget->hasSSE2();
12017  if ((VT.isVector() ||
12018       (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
12019      isa<LoadSDNode>(St->getValue()) &&
12020      !cast<LoadSDNode>(St->getValue())->isVolatile() &&
12021      St->getChain().hasOneUse() && !St->isVolatile()) {
12022    SDNode* LdVal = St->getValue().getNode();
12023    LoadSDNode *Ld = 0;
12024    int TokenFactorIndex = -1;
12025    SmallVector<SDValue, 8> Ops;
12026    SDNode* ChainVal = St->getChain().getNode();
12027    // Must be a store of a load.  We currently handle two cases:  the load
12028    // is a direct child, and it's under an intervening TokenFactor.  It is
12029    // possible to dig deeper under nested TokenFactors.
12030    if (ChainVal == LdVal)
12031      Ld = cast<LoadSDNode>(St->getChain());
12032    else if (St->getValue().hasOneUse() &&
12033             ChainVal->getOpcode() == ISD::TokenFactor) {
12034      for (unsigned i=0, e = ChainVal->getNumOperands(); i != e; ++i) {
12035        if (ChainVal->getOperand(i).getNode() == LdVal) {
12036          TokenFactorIndex = i;
12037          Ld = cast<LoadSDNode>(St->getValue());
12038        } else
12039          Ops.push_back(ChainVal->getOperand(i));
12040      }
12041    }
12042
12043    if (!Ld || !ISD::isNormalLoad(Ld))
12044      return SDValue();
12045
12046    // If this is not the MMX case, i.e. we are just turning i64 load/store
12047    // into f64 load/store, avoid the transformation if there are multiple
12048    // uses of the loaded value.
12049    if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
12050      return SDValue();
12051
12052    DebugLoc LdDL = Ld->getDebugLoc();
12053    DebugLoc StDL = N->getDebugLoc();
12054    // If we are a 64-bit capable x86, lower to a single movq load/store pair.
12055    // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
12056    // pair instead.
12057    if (Subtarget->is64Bit() || F64IsLegal) {
12058      EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
12059      SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
12060                                  Ld->getPointerInfo(), Ld->isVolatile(),
12061                                  Ld->isNonTemporal(), Ld->getAlignment());
12062      SDValue NewChain = NewLd.getValue(1);
12063      if (TokenFactorIndex != -1) {
12064        Ops.push_back(NewChain);
12065        NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
12066                               Ops.size());
12067      }
12068      return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
12069                          St->getPointerInfo(),
12070                          St->isVolatile(), St->isNonTemporal(),
12071                          St->getAlignment());
12072    }
12073
12074    // Otherwise, lower to two pairs of 32-bit loads / stores.
12075    SDValue LoAddr = Ld->getBasePtr();
12076    SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
12077                                 DAG.getConstant(4, MVT::i32));
12078
12079    SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
12080                               Ld->getPointerInfo(),
12081                               Ld->isVolatile(), Ld->isNonTemporal(),
12082                               Ld->getAlignment());
12083    SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
12084                               Ld->getPointerInfo().getWithOffset(4),
12085                               Ld->isVolatile(), Ld->isNonTemporal(),
12086                               MinAlign(Ld->getAlignment(), 4));
12087
12088    SDValue NewChain = LoLd.getValue(1);
12089    if (TokenFactorIndex != -1) {
12090      Ops.push_back(LoLd);
12091      Ops.push_back(HiLd);
12092      NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
12093                             Ops.size());
12094    }
12095
12096    LoAddr = St->getBasePtr();
12097    HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
12098                         DAG.getConstant(4, MVT::i32));
12099
12100    SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
12101                                St->getPointerInfo(),
12102                                St->isVolatile(), St->isNonTemporal(),
12103                                St->getAlignment());
12104    SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
12105                                St->getPointerInfo().getWithOffset(4),
12106                                St->isVolatile(),
12107                                St->isNonTemporal(),
12108                                MinAlign(St->getAlignment(), 4));
12109    return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
12110  }
12111  return SDValue();
12112}
12113
12114/// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
12115/// X86ISD::FXOR nodes.
12116static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
12117  assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
12118  // F[X]OR(0.0, x) -> x
12119  // F[X]OR(x, 0.0) -> x
12120  if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
12121    if (C->getValueAPF().isPosZero())
12122      return N->getOperand(1);
12123  if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
12124    if (C->getValueAPF().isPosZero())
12125      return N->getOperand(0);
12126  return SDValue();
12127}
12128
12129/// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
12130static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
12131  // FAND(0.0, x) -> 0.0
12132  // FAND(x, 0.0) -> 0.0
12133  if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
12134    if (C->getValueAPF().isPosZero())
12135      return N->getOperand(0);
12136  if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
12137    if (C->getValueAPF().isPosZero())
12138      return N->getOperand(1);
12139  return SDValue();
12140}
12141
12142static SDValue PerformBTCombine(SDNode *N,
12143                                SelectionDAG &DAG,
12144                                TargetLowering::DAGCombinerInfo &DCI) {
12145  // BT ignores high bits in the bit index operand.
12146  SDValue Op1 = N->getOperand(1);
12147  if (Op1.hasOneUse()) {
12148    unsigned BitWidth = Op1.getValueSizeInBits();
12149    APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
12150    APInt KnownZero, KnownOne;
12151    TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
12152                                          !DCI.isBeforeLegalizeOps());
12153    const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12154    if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
12155        TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
12156      DCI.CommitTargetLoweringOpt(TLO);
12157  }
12158  return SDValue();
12159}
12160
12161static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
12162  SDValue Op = N->getOperand(0);
12163  if (Op.getOpcode() == ISD::BITCAST)
12164    Op = Op.getOperand(0);
12165  EVT VT = N->getValueType(0), OpVT = Op.getValueType();
12166  if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
12167      VT.getVectorElementType().getSizeInBits() ==
12168      OpVT.getVectorElementType().getSizeInBits()) {
12169    return DAG.getNode(ISD::BITCAST, N->getDebugLoc(), VT, Op);
12170  }
12171  return SDValue();
12172}
12173
12174static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG) {
12175  // (i32 zext (and (i8  x86isd::setcc_carry), 1)) ->
12176  //           (and (i32 x86isd::setcc_carry), 1)
12177  // This eliminates the zext. This transformation is necessary because
12178  // ISD::SETCC is always legalized to i8.
12179  DebugLoc dl = N->getDebugLoc();
12180  SDValue N0 = N->getOperand(0);
12181  EVT VT = N->getValueType(0);
12182  if (N0.getOpcode() == ISD::AND &&
12183      N0.hasOneUse() &&
12184      N0.getOperand(0).hasOneUse()) {
12185    SDValue N00 = N0.getOperand(0);
12186    if (N00.getOpcode() != X86ISD::SETCC_CARRY)
12187      return SDValue();
12188    ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
12189    if (!C || C->getZExtValue() != 1)
12190      return SDValue();
12191    return DAG.getNode(ISD::AND, dl, VT,
12192                       DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
12193                                   N00.getOperand(0), N00.getOperand(1)),
12194                       DAG.getConstant(1, VT));
12195  }
12196
12197  return SDValue();
12198}
12199
12200// Optimize  RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
12201static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG) {
12202  unsigned X86CC = N->getConstantOperandVal(0);
12203  SDValue EFLAG = N->getOperand(1);
12204  DebugLoc DL = N->getDebugLoc();
12205
12206  // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
12207  // a zext and produces an all-ones bit which is more useful than 0/1 in some
12208  // cases.
12209  if (X86CC == X86::COND_B)
12210    return DAG.getNode(ISD::AND, DL, MVT::i8,
12211                       DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
12212                                   DAG.getConstant(X86CC, MVT::i8), EFLAG),
12213                       DAG.getConstant(1, MVT::i8));
12214
12215  return SDValue();
12216}
12217
12218static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
12219                                        const X86TargetLowering *XTLI) {
12220  SDValue Op0 = N->getOperand(0);
12221  // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
12222  // a 32-bit target where SSE doesn't support i64->FP operations.
12223  if (Op0.getOpcode() == ISD::LOAD) {
12224    LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
12225    EVT VT = Ld->getValueType(0);
12226    if (!Ld->isVolatile() && !N->getValueType(0).isVector() &&
12227        ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
12228        !XTLI->getSubtarget()->is64Bit() &&
12229        !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
12230      SDValue FILDChain = XTLI->BuildFILD(SDValue(N, 0), Ld->getValueType(0),
12231                                          Ld->getChain(), Op0, DAG);
12232      DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
12233      return FILDChain;
12234    }
12235  }
12236  return SDValue();
12237}
12238
12239// Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
12240static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
12241                                 X86TargetLowering::DAGCombinerInfo &DCI) {
12242  // If the LHS and RHS of the ADC node are zero, then it can't overflow and
12243  // the result is either zero or one (depending on the input carry bit).
12244  // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
12245  if (X86::isZeroNode(N->getOperand(0)) &&
12246      X86::isZeroNode(N->getOperand(1)) &&
12247      // We don't have a good way to replace an EFLAGS use, so only do this when
12248      // dead right now.
12249      SDValue(N, 1).use_empty()) {
12250    DebugLoc DL = N->getDebugLoc();
12251    EVT VT = N->getValueType(0);
12252    SDValue CarryOut = DAG.getConstant(0, N->getValueType(1));
12253    SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
12254                               DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
12255                                           DAG.getConstant(X86::COND_B,MVT::i8),
12256                                           N->getOperand(2)),
12257                               DAG.getConstant(1, VT));
12258    return DCI.CombineTo(N, Res1, CarryOut);
12259  }
12260
12261  return SDValue();
12262}
12263
12264// fold (add Y, (sete  X, 0)) -> adc  0, Y
12265//      (add Y, (setne X, 0)) -> sbb -1, Y
12266//      (sub (sete  X, 0), Y) -> sbb  0, Y
12267//      (sub (setne X, 0), Y) -> adc -1, Y
12268static SDValue OptimizeConditonalInDecrement(SDNode *N, SelectionDAG &DAG) {
12269  DebugLoc DL = N->getDebugLoc();
12270
12271  // Look through ZExts.
12272  SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
12273  if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
12274    return SDValue();
12275
12276  SDValue SetCC = Ext.getOperand(0);
12277  if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
12278    return SDValue();
12279
12280  X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
12281  if (CC != X86::COND_E && CC != X86::COND_NE)
12282    return SDValue();
12283
12284  SDValue Cmp = SetCC.getOperand(1);
12285  if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
12286      !X86::isZeroNode(Cmp.getOperand(1)) ||
12287      !Cmp.getOperand(0).getValueType().isInteger())
12288    return SDValue();
12289
12290  SDValue CmpOp0 = Cmp.getOperand(0);
12291  SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
12292                               DAG.getConstant(1, CmpOp0.getValueType()));
12293
12294  SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
12295  if (CC == X86::COND_NE)
12296    return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
12297                       DL, OtherVal.getValueType(), OtherVal,
12298                       DAG.getConstant(-1ULL, OtherVal.getValueType()), NewCmp);
12299  return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
12300                     DL, OtherVal.getValueType(), OtherVal,
12301                     DAG.getConstant(0, OtherVal.getValueType()), NewCmp);
12302}
12303
12304SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
12305                                             DAGCombinerInfo &DCI) const {
12306  SelectionDAG &DAG = DCI.DAG;
12307  switch (N->getOpcode()) {
12308  default: break;
12309  case ISD::EXTRACT_VECTOR_ELT:
12310    return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, *this);
12311  case ISD::SELECT:         return PerformSELECTCombine(N, DAG, Subtarget);
12312  case X86ISD::CMOV:        return PerformCMOVCombine(N, DAG, DCI);
12313  case ISD::ADD:
12314  case ISD::SUB:            return OptimizeConditonalInDecrement(N, DAG);
12315  case X86ISD::ADC:         return PerformADCCombine(N, DAG, DCI);
12316  case ISD::MUL:            return PerformMulCombine(N, DAG, DCI);
12317  case ISD::SHL:
12318  case ISD::SRA:
12319  case ISD::SRL:            return PerformShiftCombine(N, DAG, Subtarget);
12320  case ISD::AND:            return PerformAndCombine(N, DAG, DCI, Subtarget);
12321  case ISD::OR:             return PerformOrCombine(N, DAG, DCI, Subtarget);
12322  case ISD::STORE:          return PerformSTORECombine(N, DAG, Subtarget);
12323  case ISD::SINT_TO_FP:     return PerformSINT_TO_FPCombine(N, DAG, this);
12324  case X86ISD::FXOR:
12325  case X86ISD::FOR:         return PerformFORCombine(N, DAG);
12326  case X86ISD::FAND:        return PerformFANDCombine(N, DAG);
12327  case X86ISD::BT:          return PerformBTCombine(N, DAG, DCI);
12328  case X86ISD::VZEXT_MOVL:  return PerformVZEXT_MOVLCombine(N, DAG);
12329  case ISD::ZERO_EXTEND:    return PerformZExtCombine(N, DAG);
12330  case X86ISD::SETCC:       return PerformSETCCCombine(N, DAG);
12331  case X86ISD::SHUFPS:      // Handle all target specific shuffles
12332  case X86ISD::SHUFPD:
12333  case X86ISD::PALIGN:
12334  case X86ISD::PUNPCKHBW:
12335  case X86ISD::PUNPCKHWD:
12336  case X86ISD::PUNPCKHDQ:
12337  case X86ISD::PUNPCKHQDQ:
12338  case X86ISD::UNPCKHPS:
12339  case X86ISD::UNPCKHPD:
12340  case X86ISD::PUNPCKLBW:
12341  case X86ISD::PUNPCKLWD:
12342  case X86ISD::PUNPCKLDQ:
12343  case X86ISD::PUNPCKLQDQ:
12344  case X86ISD::UNPCKLPS:
12345  case X86ISD::UNPCKLPD:
12346  case X86ISD::VUNPCKLPS:
12347  case X86ISD::VUNPCKLPD:
12348  case X86ISD::VUNPCKLPSY:
12349  case X86ISD::VUNPCKLPDY:
12350  case X86ISD::MOVHLPS:
12351  case X86ISD::MOVLHPS:
12352  case X86ISD::PSHUFD:
12353  case X86ISD::PSHUFHW:
12354  case X86ISD::PSHUFLW:
12355  case X86ISD::MOVSS:
12356  case X86ISD::MOVSD:
12357  case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI);
12358  }
12359
12360  return SDValue();
12361}
12362
12363/// isTypeDesirableForOp - Return true if the target has native support for
12364/// the specified value type and it is 'desirable' to use the type for the
12365/// given node type. e.g. On x86 i16 is legal, but undesirable since i16
12366/// instruction encodings are longer and some i16 instructions are slow.
12367bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
12368  if (!isTypeLegal(VT))
12369    return false;
12370  if (VT != MVT::i16)
12371    return true;
12372
12373  switch (Opc) {
12374  default:
12375    return true;
12376  case ISD::LOAD:
12377  case ISD::SIGN_EXTEND:
12378  case ISD::ZERO_EXTEND:
12379  case ISD::ANY_EXTEND:
12380  case ISD::SHL:
12381  case ISD::SRL:
12382  case ISD::SUB:
12383  case ISD::ADD:
12384  case ISD::MUL:
12385  case ISD::AND:
12386  case ISD::OR:
12387  case ISD::XOR:
12388    return false;
12389  }
12390}
12391
12392/// IsDesirableToPromoteOp - This method query the target whether it is
12393/// beneficial for dag combiner to promote the specified node. If true, it
12394/// should return the desired promotion type by reference.
12395bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
12396  EVT VT = Op.getValueType();
12397  if (VT != MVT::i16)
12398    return false;
12399
12400  bool Promote = false;
12401  bool Commute = false;
12402  switch (Op.getOpcode()) {
12403  default: break;
12404  case ISD::LOAD: {
12405    LoadSDNode *LD = cast<LoadSDNode>(Op);
12406    // If the non-extending load has a single use and it's not live out, then it
12407    // might be folded.
12408    if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
12409                                                     Op.hasOneUse()*/) {
12410      for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
12411             UE = Op.getNode()->use_end(); UI != UE; ++UI) {
12412        // The only case where we'd want to promote LOAD (rather then it being
12413        // promoted as an operand is when it's only use is liveout.
12414        if (UI->getOpcode() != ISD::CopyToReg)
12415          return false;
12416      }
12417    }
12418    Promote = true;
12419    break;
12420  }
12421  case ISD::SIGN_EXTEND:
12422  case ISD::ZERO_EXTEND:
12423  case ISD::ANY_EXTEND:
12424    Promote = true;
12425    break;
12426  case ISD::SHL:
12427  case ISD::SRL: {
12428    SDValue N0 = Op.getOperand(0);
12429    // Look out for (store (shl (load), x)).
12430    if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
12431      return false;
12432    Promote = true;
12433    break;
12434  }
12435  case ISD::ADD:
12436  case ISD::MUL:
12437  case ISD::AND:
12438  case ISD::OR:
12439  case ISD::XOR:
12440    Commute = true;
12441    // fallthrough
12442  case ISD::SUB: {
12443    SDValue N0 = Op.getOperand(0);
12444    SDValue N1 = Op.getOperand(1);
12445    if (!Commute && MayFoldLoad(N1))
12446      return false;
12447    // Avoid disabling potential load folding opportunities.
12448    if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
12449      return false;
12450    if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
12451      return false;
12452    Promote = true;
12453  }
12454  }
12455
12456  PVT = MVT::i32;
12457  return Promote;
12458}
12459
12460//===----------------------------------------------------------------------===//
12461//                           X86 Inline Assembly Support
12462//===----------------------------------------------------------------------===//
12463
12464bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
12465  InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
12466
12467  std::string AsmStr = IA->getAsmString();
12468
12469  // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
12470  SmallVector<StringRef, 4> AsmPieces;
12471  SplitString(AsmStr, AsmPieces, ";\n");
12472
12473  switch (AsmPieces.size()) {
12474  default: return false;
12475  case 1:
12476    AsmStr = AsmPieces[0];
12477    AsmPieces.clear();
12478    SplitString(AsmStr, AsmPieces, " \t");  // Split with whitespace.
12479
12480    // FIXME: this should verify that we are targeting a 486 or better.  If not,
12481    // we will turn this bswap into something that will be lowered to logical ops
12482    // instead of emitting the bswap asm.  For now, we don't support 486 or lower
12483    // so don't worry about this.
12484    // bswap $0
12485    if (AsmPieces.size() == 2 &&
12486        (AsmPieces[0] == "bswap" ||
12487         AsmPieces[0] == "bswapq" ||
12488         AsmPieces[0] == "bswapl") &&
12489        (AsmPieces[1] == "$0" ||
12490         AsmPieces[1] == "${0:q}")) {
12491      // No need to check constraints, nothing other than the equivalent of
12492      // "=r,0" would be valid here.
12493      const IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
12494      if (!Ty || Ty->getBitWidth() % 16 != 0)
12495        return false;
12496      return IntrinsicLowering::LowerToByteSwap(CI);
12497    }
12498    // rorw $$8, ${0:w}  -->  llvm.bswap.i16
12499    if (CI->getType()->isIntegerTy(16) &&
12500        AsmPieces.size() == 3 &&
12501        (AsmPieces[0] == "rorw" || AsmPieces[0] == "rolw") &&
12502        AsmPieces[1] == "$$8," &&
12503        AsmPieces[2] == "${0:w}" &&
12504        IA->getConstraintString().compare(0, 5, "=r,0,") == 0) {
12505      AsmPieces.clear();
12506      const std::string &ConstraintsStr = IA->getConstraintString();
12507      SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
12508      std::sort(AsmPieces.begin(), AsmPieces.end());
12509      if (AsmPieces.size() == 4 &&
12510          AsmPieces[0] == "~{cc}" &&
12511          AsmPieces[1] == "~{dirflag}" &&
12512          AsmPieces[2] == "~{flags}" &&
12513          AsmPieces[3] == "~{fpsr}") {
12514        const IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
12515        if (!Ty || Ty->getBitWidth() % 16 != 0)
12516          return false;
12517        return IntrinsicLowering::LowerToByteSwap(CI);
12518      }
12519    }
12520    break;
12521  case 3:
12522    if (CI->getType()->isIntegerTy(32) &&
12523        IA->getConstraintString().compare(0, 5, "=r,0,") == 0) {
12524      SmallVector<StringRef, 4> Words;
12525      SplitString(AsmPieces[0], Words, " \t,");
12526      if (Words.size() == 3 && Words[0] == "rorw" && Words[1] == "$$8" &&
12527          Words[2] == "${0:w}") {
12528        Words.clear();
12529        SplitString(AsmPieces[1], Words, " \t,");
12530        if (Words.size() == 3 && Words[0] == "rorl" && Words[1] == "$$16" &&
12531            Words[2] == "$0") {
12532          Words.clear();
12533          SplitString(AsmPieces[2], Words, " \t,");
12534          if (Words.size() == 3 && Words[0] == "rorw" && Words[1] == "$$8" &&
12535              Words[2] == "${0:w}") {
12536            AsmPieces.clear();
12537            const std::string &ConstraintsStr = IA->getConstraintString();
12538            SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
12539            std::sort(AsmPieces.begin(), AsmPieces.end());
12540            if (AsmPieces.size() == 4 &&
12541                AsmPieces[0] == "~{cc}" &&
12542                AsmPieces[1] == "~{dirflag}" &&
12543                AsmPieces[2] == "~{flags}" &&
12544                AsmPieces[3] == "~{fpsr}") {
12545              const IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
12546              if (!Ty || Ty->getBitWidth() % 16 != 0)
12547                return false;
12548              return IntrinsicLowering::LowerToByteSwap(CI);
12549            }
12550          }
12551        }
12552      }
12553    }
12554
12555    if (CI->getType()->isIntegerTy(64)) {
12556      InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
12557      if (Constraints.size() >= 2 &&
12558          Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
12559          Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
12560        // bswap %eax / bswap %edx / xchgl %eax, %edx  -> llvm.bswap.i64
12561        SmallVector<StringRef, 4> Words;
12562        SplitString(AsmPieces[0], Words, " \t");
12563        if (Words.size() == 2 && Words[0] == "bswap" && Words[1] == "%eax") {
12564          Words.clear();
12565          SplitString(AsmPieces[1], Words, " \t");
12566          if (Words.size() == 2 && Words[0] == "bswap" && Words[1] == "%edx") {
12567            Words.clear();
12568            SplitString(AsmPieces[2], Words, " \t,");
12569            if (Words.size() == 3 && Words[0] == "xchgl" && Words[1] == "%eax" &&
12570                Words[2] == "%edx") {
12571              const IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
12572              if (!Ty || Ty->getBitWidth() % 16 != 0)
12573                return false;
12574              return IntrinsicLowering::LowerToByteSwap(CI);
12575            }
12576          }
12577        }
12578      }
12579    }
12580    break;
12581  }
12582  return false;
12583}
12584
12585
12586
12587/// getConstraintType - Given a constraint letter, return the type of
12588/// constraint it is for this target.
12589X86TargetLowering::ConstraintType
12590X86TargetLowering::getConstraintType(const std::string &Constraint) const {
12591  if (Constraint.size() == 1) {
12592    switch (Constraint[0]) {
12593    case 'R':
12594    case 'q':
12595    case 'Q':
12596    case 'f':
12597    case 't':
12598    case 'u':
12599    case 'y':
12600    case 'x':
12601    case 'Y':
12602    case 'l':
12603      return C_RegisterClass;
12604    case 'a':
12605    case 'b':
12606    case 'c':
12607    case 'd':
12608    case 'S':
12609    case 'D':
12610    case 'A':
12611      return C_Register;
12612    case 'I':
12613    case 'J':
12614    case 'K':
12615    case 'L':
12616    case 'M':
12617    case 'N':
12618    case 'G':
12619    case 'C':
12620    case 'e':
12621    case 'Z':
12622      return C_Other;
12623    default:
12624      break;
12625    }
12626  }
12627  return TargetLowering::getConstraintType(Constraint);
12628}
12629
12630/// Examine constraint type and operand type and determine a weight value.
12631/// This object must already have been set up with the operand type
12632/// and the current alternative constraint selected.
12633TargetLowering::ConstraintWeight
12634  X86TargetLowering::getSingleConstraintMatchWeight(
12635    AsmOperandInfo &info, const char *constraint) const {
12636  ConstraintWeight weight = CW_Invalid;
12637  Value *CallOperandVal = info.CallOperandVal;
12638    // If we don't have a value, we can't do a match,
12639    // but allow it at the lowest weight.
12640  if (CallOperandVal == NULL)
12641    return CW_Default;
12642  const Type *type = CallOperandVal->getType();
12643  // Look at the constraint type.
12644  switch (*constraint) {
12645  default:
12646    weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
12647  case 'R':
12648  case 'q':
12649  case 'Q':
12650  case 'a':
12651  case 'b':
12652  case 'c':
12653  case 'd':
12654  case 'S':
12655  case 'D':
12656  case 'A':
12657    if (CallOperandVal->getType()->isIntegerTy())
12658      weight = CW_SpecificReg;
12659    break;
12660  case 'f':
12661  case 't':
12662  case 'u':
12663      if (type->isFloatingPointTy())
12664        weight = CW_SpecificReg;
12665      break;
12666  case 'y':
12667      if (type->isX86_MMXTy() && Subtarget->hasMMX())
12668        weight = CW_SpecificReg;
12669      break;
12670  case 'x':
12671  case 'Y':
12672    if ((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasXMM())
12673      weight = CW_Register;
12674    break;
12675  case 'I':
12676    if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
12677      if (C->getZExtValue() <= 31)
12678        weight = CW_Constant;
12679    }
12680    break;
12681  case 'J':
12682    if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
12683      if (C->getZExtValue() <= 63)
12684        weight = CW_Constant;
12685    }
12686    break;
12687  case 'K':
12688    if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
12689      if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
12690        weight = CW_Constant;
12691    }
12692    break;
12693  case 'L':
12694    if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
12695      if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
12696        weight = CW_Constant;
12697    }
12698    break;
12699  case 'M':
12700    if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
12701      if (C->getZExtValue() <= 3)
12702        weight = CW_Constant;
12703    }
12704    break;
12705  case 'N':
12706    if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
12707      if (C->getZExtValue() <= 0xff)
12708        weight = CW_Constant;
12709    }
12710    break;
12711  case 'G':
12712  case 'C':
12713    if (dyn_cast<ConstantFP>(CallOperandVal)) {
12714      weight = CW_Constant;
12715    }
12716    break;
12717  case 'e':
12718    if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
12719      if ((C->getSExtValue() >= -0x80000000LL) &&
12720          (C->getSExtValue() <= 0x7fffffffLL))
12721        weight = CW_Constant;
12722    }
12723    break;
12724  case 'Z':
12725    if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
12726      if (C->getZExtValue() <= 0xffffffff)
12727        weight = CW_Constant;
12728    }
12729    break;
12730  }
12731  return weight;
12732}
12733
12734/// LowerXConstraint - try to replace an X constraint, which matches anything,
12735/// with another that has more specific requirements based on the type of the
12736/// corresponding operand.
12737const char *X86TargetLowering::
12738LowerXConstraint(EVT ConstraintVT) const {
12739  // FP X constraints get lowered to SSE1/2 registers if available, otherwise
12740  // 'f' like normal targets.
12741  if (ConstraintVT.isFloatingPoint()) {
12742    if (Subtarget->hasXMMInt())
12743      return "Y";
12744    if (Subtarget->hasXMM())
12745      return "x";
12746  }
12747
12748  return TargetLowering::LowerXConstraint(ConstraintVT);
12749}
12750
12751/// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
12752/// vector.  If it is invalid, don't add anything to Ops.
12753void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
12754                                                     std::string &Constraint,
12755                                                     std::vector<SDValue>&Ops,
12756                                                     SelectionDAG &DAG) const {
12757  SDValue Result(0, 0);
12758
12759  // Only support length 1 constraints for now.
12760  if (Constraint.length() > 1) return;
12761
12762  char ConstraintLetter = Constraint[0];
12763  switch (ConstraintLetter) {
12764  default: break;
12765  case 'I':
12766    if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
12767      if (C->getZExtValue() <= 31) {
12768        Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
12769        break;
12770      }
12771    }
12772    return;
12773  case 'J':
12774    if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
12775      if (C->getZExtValue() <= 63) {
12776        Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
12777        break;
12778      }
12779    }
12780    return;
12781  case 'K':
12782    if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
12783      if ((int8_t)C->getSExtValue() == C->getSExtValue()) {
12784        Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
12785        break;
12786      }
12787    }
12788    return;
12789  case 'N':
12790    if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
12791      if (C->getZExtValue() <= 255) {
12792        Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
12793        break;
12794      }
12795    }
12796    return;
12797  case 'e': {
12798    // 32-bit signed value
12799    if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
12800      if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
12801                                           C->getSExtValue())) {
12802        // Widen to 64 bits here to get it sign extended.
12803        Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
12804        break;
12805      }
12806    // FIXME gcc accepts some relocatable values here too, but only in certain
12807    // memory models; it's complicated.
12808    }
12809    return;
12810  }
12811  case 'Z': {
12812    // 32-bit unsigned value
12813    if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
12814      if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
12815                                           C->getZExtValue())) {
12816        Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
12817        break;
12818      }
12819    }
12820    // FIXME gcc accepts some relocatable values here too, but only in certain
12821    // memory models; it's complicated.
12822    return;
12823  }
12824  case 'i': {
12825    // Literal immediates are always ok.
12826    if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
12827      // Widen to 64 bits here to get it sign extended.
12828      Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
12829      break;
12830    }
12831
12832    // In any sort of PIC mode addresses need to be computed at runtime by
12833    // adding in a register or some sort of table lookup.  These can't
12834    // be used as immediates.
12835    if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
12836      return;
12837
12838    // If we are in non-pic codegen mode, we allow the address of a global (with
12839    // an optional displacement) to be used with 'i'.
12840    GlobalAddressSDNode *GA = 0;
12841    int64_t Offset = 0;
12842
12843    // Match either (GA), (GA+C), (GA+C1+C2), etc.
12844    while (1) {
12845      if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
12846        Offset += GA->getOffset();
12847        break;
12848      } else if (Op.getOpcode() == ISD::ADD) {
12849        if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
12850          Offset += C->getZExtValue();
12851          Op = Op.getOperand(0);
12852          continue;
12853        }
12854      } else if (Op.getOpcode() == ISD::SUB) {
12855        if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
12856          Offset += -C->getZExtValue();
12857          Op = Op.getOperand(0);
12858          continue;
12859        }
12860      }
12861
12862      // Otherwise, this isn't something we can handle, reject it.
12863      return;
12864    }
12865
12866    const GlobalValue *GV = GA->getGlobal();
12867    // If we require an extra load to get this address, as in PIC mode, we
12868    // can't accept it.
12869    if (isGlobalStubReference(Subtarget->ClassifyGlobalReference(GV,
12870                                                        getTargetMachine())))
12871      return;
12872
12873    Result = DAG.getTargetGlobalAddress(GV, Op.getDebugLoc(),
12874                                        GA->getValueType(0), Offset);
12875    break;
12876  }
12877  }
12878
12879  if (Result.getNode()) {
12880    Ops.push_back(Result);
12881    return;
12882  }
12883  return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
12884}
12885
12886std::pair<unsigned, const TargetRegisterClass*>
12887X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
12888                                                EVT VT) const {
12889  // First, see if this is a constraint that directly corresponds to an LLVM
12890  // register class.
12891  if (Constraint.size() == 1) {
12892    // GCC Constraint Letters
12893    switch (Constraint[0]) {
12894    default: break;
12895      // TODO: Slight differences here in allocation order and leaving
12896      // RIP in the class. Do they matter any more here than they do
12897      // in the normal allocation?
12898    case 'q':   // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
12899      if (Subtarget->is64Bit()) {
12900	if (VT == MVT::i32 || VT == MVT::f32)
12901	  return std::make_pair(0U, X86::GR32RegisterClass);
12902	else if (VT == MVT::i16)
12903	  return std::make_pair(0U, X86::GR16RegisterClass);
12904	else if (VT == MVT::i8)
12905	  return std::make_pair(0U, X86::GR8RegisterClass);
12906	else if (VT == MVT::i64 || VT == MVT::f64)
12907	  return std::make_pair(0U, X86::GR64RegisterClass);
12908	break;
12909      }
12910      // 32-bit fallthrough
12911    case 'Q':   // Q_REGS
12912      if (VT == MVT::i32 || VT == MVT::f32)
12913	return std::make_pair(0U, X86::GR32_ABCDRegisterClass);
12914      else if (VT == MVT::i16)
12915	return std::make_pair(0U, X86::GR16_ABCDRegisterClass);
12916      else if (VT == MVT::i8)
12917	return std::make_pair(0U, X86::GR8_ABCD_LRegisterClass);
12918      else if (VT == MVT::i64)
12919	return std::make_pair(0U, X86::GR64_ABCDRegisterClass);
12920      break;
12921    case 'r':   // GENERAL_REGS
12922    case 'l':   // INDEX_REGS
12923      if (VT == MVT::i8)
12924        return std::make_pair(0U, X86::GR8RegisterClass);
12925      if (VT == MVT::i16)
12926        return std::make_pair(0U, X86::GR16RegisterClass);
12927      if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
12928        return std::make_pair(0U, X86::GR32RegisterClass);
12929      return std::make_pair(0U, X86::GR64RegisterClass);
12930    case 'R':   // LEGACY_REGS
12931      if (VT == MVT::i8)
12932        return std::make_pair(0U, X86::GR8_NOREXRegisterClass);
12933      if (VT == MVT::i16)
12934        return std::make_pair(0U, X86::GR16_NOREXRegisterClass);
12935      if (VT == MVT::i32 || !Subtarget->is64Bit())
12936        return std::make_pair(0U, X86::GR32_NOREXRegisterClass);
12937      return std::make_pair(0U, X86::GR64_NOREXRegisterClass);
12938    case 'f':  // FP Stack registers.
12939      // If SSE is enabled for this VT, use f80 to ensure the isel moves the
12940      // value to the correct fpstack register class.
12941      if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
12942        return std::make_pair(0U, X86::RFP32RegisterClass);
12943      if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
12944        return std::make_pair(0U, X86::RFP64RegisterClass);
12945      return std::make_pair(0U, X86::RFP80RegisterClass);
12946    case 'y':   // MMX_REGS if MMX allowed.
12947      if (!Subtarget->hasMMX()) break;
12948      return std::make_pair(0U, X86::VR64RegisterClass);
12949    case 'Y':   // SSE_REGS if SSE2 allowed
12950      if (!Subtarget->hasXMMInt()) break;
12951      // FALL THROUGH.
12952    case 'x':   // SSE_REGS if SSE1 allowed
12953      if (!Subtarget->hasXMM()) break;
12954
12955      switch (VT.getSimpleVT().SimpleTy) {
12956      default: break;
12957      // Scalar SSE types.
12958      case MVT::f32:
12959      case MVT::i32:
12960        return std::make_pair(0U, X86::FR32RegisterClass);
12961      case MVT::f64:
12962      case MVT::i64:
12963        return std::make_pair(0U, X86::FR64RegisterClass);
12964      // Vector types.
12965      case MVT::v16i8:
12966      case MVT::v8i16:
12967      case MVT::v4i32:
12968      case MVT::v2i64:
12969      case MVT::v4f32:
12970      case MVT::v2f64:
12971        return std::make_pair(0U, X86::VR128RegisterClass);
12972      }
12973      break;
12974    }
12975  }
12976
12977  // Use the default implementation in TargetLowering to convert the register
12978  // constraint into a member of a register class.
12979  std::pair<unsigned, const TargetRegisterClass*> Res;
12980  Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
12981
12982  // Not found as a standard register?
12983  if (Res.second == 0) {
12984    // Map st(0) -> st(7) -> ST0
12985    if (Constraint.size() == 7 && Constraint[0] == '{' &&
12986        tolower(Constraint[1]) == 's' &&
12987        tolower(Constraint[2]) == 't' &&
12988        Constraint[3] == '(' &&
12989        (Constraint[4] >= '0' && Constraint[4] <= '7') &&
12990        Constraint[5] == ')' &&
12991        Constraint[6] == '}') {
12992
12993      Res.first = X86::ST0+Constraint[4]-'0';
12994      Res.second = X86::RFP80RegisterClass;
12995      return Res;
12996    }
12997
12998    // GCC allows "st(0)" to be called just plain "st".
12999    if (StringRef("{st}").equals_lower(Constraint)) {
13000      Res.first = X86::ST0;
13001      Res.second = X86::RFP80RegisterClass;
13002      return Res;
13003    }
13004
13005    // flags -> EFLAGS
13006    if (StringRef("{flags}").equals_lower(Constraint)) {
13007      Res.first = X86::EFLAGS;
13008      Res.second = X86::CCRRegisterClass;
13009      return Res;
13010    }
13011
13012    // 'A' means EAX + EDX.
13013    if (Constraint == "A") {
13014      Res.first = X86::EAX;
13015      Res.second = X86::GR32_ADRegisterClass;
13016      return Res;
13017    }
13018    return Res;
13019  }
13020
13021  // Otherwise, check to see if this is a register class of the wrong value
13022  // type.  For example, we want to map "{ax},i32" -> {eax}, we don't want it to
13023  // turn into {ax},{dx}.
13024  if (Res.second->hasType(VT))
13025    return Res;   // Correct type already, nothing to do.
13026
13027  // All of the single-register GCC register classes map their values onto
13028  // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp".  If we
13029  // really want an 8-bit or 32-bit register, map to the appropriate register
13030  // class and return the appropriate register.
13031  if (Res.second == X86::GR16RegisterClass) {
13032    if (VT == MVT::i8) {
13033      unsigned DestReg = 0;
13034      switch (Res.first) {
13035      default: break;
13036      case X86::AX: DestReg = X86::AL; break;
13037      case X86::DX: DestReg = X86::DL; break;
13038      case X86::CX: DestReg = X86::CL; break;
13039      case X86::BX: DestReg = X86::BL; break;
13040      }
13041      if (DestReg) {
13042        Res.first = DestReg;
13043        Res.second = X86::GR8RegisterClass;
13044      }
13045    } else if (VT == MVT::i32) {
13046      unsigned DestReg = 0;
13047      switch (Res.first) {
13048      default: break;
13049      case X86::AX: DestReg = X86::EAX; break;
13050      case X86::DX: DestReg = X86::EDX; break;
13051      case X86::CX: DestReg = X86::ECX; break;
13052      case X86::BX: DestReg = X86::EBX; break;
13053      case X86::SI: DestReg = X86::ESI; break;
13054      case X86::DI: DestReg = X86::EDI; break;
13055      case X86::BP: DestReg = X86::EBP; break;
13056      case X86::SP: DestReg = X86::ESP; break;
13057      }
13058      if (DestReg) {
13059        Res.first = DestReg;
13060        Res.second = X86::GR32RegisterClass;
13061      }
13062    } else if (VT == MVT::i64) {
13063      unsigned DestReg = 0;
13064      switch (Res.first) {
13065      default: break;
13066      case X86::AX: DestReg = X86::RAX; break;
13067      case X86::DX: DestReg = X86::RDX; break;
13068      case X86::CX: DestReg = X86::RCX; break;
13069      case X86::BX: DestReg = X86::RBX; break;
13070      case X86::SI: DestReg = X86::RSI; break;
13071      case X86::DI: DestReg = X86::RDI; break;
13072      case X86::BP: DestReg = X86::RBP; break;
13073      case X86::SP: DestReg = X86::RSP; break;
13074      }
13075      if (DestReg) {
13076        Res.first = DestReg;
13077        Res.second = X86::GR64RegisterClass;
13078      }
13079    }
13080  } else if (Res.second == X86::FR32RegisterClass ||
13081             Res.second == X86::FR64RegisterClass ||
13082             Res.second == X86::VR128RegisterClass) {
13083    // Handle references to XMM physical registers that got mapped into the
13084    // wrong class.  This can happen with constraints like {xmm0} where the
13085    // target independent register mapper will just pick the first match it can
13086    // find, ignoring the required type.
13087    if (VT == MVT::f32)
13088      Res.second = X86::FR32RegisterClass;
13089    else if (VT == MVT::f64)
13090      Res.second = X86::FR64RegisterClass;
13091    else if (X86::VR128RegisterClass->hasType(VT))
13092      Res.second = X86::VR128RegisterClass;
13093  }
13094
13095  return Res;
13096}
13097