X86ISelLowering.cpp revision ab7c09b6b6f4516a631fd6788918c237c83939af
1f11879ae94e7598cb6ae59fdc13104947b66e3e6Alan Viverette//===-- X86ISelLowering.cpp - X86 DAG Lowering Implementation -------------===//
2f11879ae94e7598cb6ae59fdc13104947b66e3e6Alan Viverette//
3f11879ae94e7598cb6ae59fdc13104947b66e3e6Alan Viverette//                     The LLVM Compiler Infrastructure
4f11879ae94e7598cb6ae59fdc13104947b66e3e6Alan Viverette//
5f11879ae94e7598cb6ae59fdc13104947b66e3e6Alan Viverette// This file is distributed under the University of Illinois Open Source
6f11879ae94e7598cb6ae59fdc13104947b66e3e6Alan Viverette// License. See LICENSE.TXT for details.
7f11879ae94e7598cb6ae59fdc13104947b66e3e6Alan Viverette//
8f11879ae94e7598cb6ae59fdc13104947b66e3e6Alan Viverette//===----------------------------------------------------------------------===//
9f11879ae94e7598cb6ae59fdc13104947b66e3e6Alan Viverette//
10f11879ae94e7598cb6ae59fdc13104947b66e3e6Alan Viverette// This file defines the interfaces that X86 uses to lower LLVM code into a
11f11879ae94e7598cb6ae59fdc13104947b66e3e6Alan Viverette// selection DAG.
12f11879ae94e7598cb6ae59fdc13104947b66e3e6Alan Viverette//
13f11879ae94e7598cb6ae59fdc13104947b66e3e6Alan Viverette//===----------------------------------------------------------------------===//
14f11879ae94e7598cb6ae59fdc13104947b66e3e6Alan Viverette
15f11879ae94e7598cb6ae59fdc13104947b66e3e6Alan Viverette#include "X86.h"
16f11879ae94e7598cb6ae59fdc13104947b66e3e6Alan Viverette#include "X86InstrBuilder.h"
17f11879ae94e7598cb6ae59fdc13104947b66e3e6Alan Viverette#include "X86ISelLowering.h"
18f11879ae94e7598cb6ae59fdc13104947b66e3e6Alan Viverette#include "X86TargetMachine.h"
19f11879ae94e7598cb6ae59fdc13104947b66e3e6Alan Viverette#include "llvm/CallingConv.h"
20f11879ae94e7598cb6ae59fdc13104947b66e3e6Alan Viverette#include "llvm/Constants.h"
21f11879ae94e7598cb6ae59fdc13104947b66e3e6Alan Viverette#include "llvm/DerivedTypes.h"
22f11879ae94e7598cb6ae59fdc13104947b66e3e6Alan Viverette#include "llvm/GlobalAlias.h"
23f11879ae94e7598cb6ae59fdc13104947b66e3e6Alan Viverette#include "llvm/GlobalVariable.h"
24f11879ae94e7598cb6ae59fdc13104947b66e3e6Alan Viverette#include "llvm/Function.h"
25f11879ae94e7598cb6ae59fdc13104947b66e3e6Alan Viverette#include "llvm/Intrinsics.h"
26f11879ae94e7598cb6ae59fdc13104947b66e3e6Alan Viverette#include "llvm/ADT/BitVector.h"
27f11879ae94e7598cb6ae59fdc13104947b66e3e6Alan Viverette#include "llvm/ADT/VectorExtras.h"
28f11879ae94e7598cb6ae59fdc13104947b66e3e6Alan Viverette#include "llvm/CodeGen/MachineFrameInfo.h"
29f11879ae94e7598cb6ae59fdc13104947b66e3e6Alan Viverette#include "llvm/CodeGen/MachineFunction.h"
30f11879ae94e7598cb6ae59fdc13104947b66e3e6Alan Viverette#include "llvm/CodeGen/MachineInstrBuilder.h"
31f11879ae94e7598cb6ae59fdc13104947b66e3e6Alan Viverette#include "llvm/CodeGen/MachineModuleInfo.h"
32f11879ae94e7598cb6ae59fdc13104947b66e3e6Alan Viverette#include "llvm/CodeGen/MachineRegisterInfo.h"
33f11879ae94e7598cb6ae59fdc13104947b66e3e6Alan Viverette#include "llvm/CodeGen/PseudoSourceValue.h"
34f11879ae94e7598cb6ae59fdc13104947b66e3e6Alan Viverette#include "llvm/Support/MathExtras.h"
35f11879ae94e7598cb6ae59fdc13104947b66e3e6Alan Viverette#include "llvm/Support/Debug.h"
36f11879ae94e7598cb6ae59fdc13104947b66e3e6Alan Viverette#include "llvm/Support/ErrorHandling.h"
37f11879ae94e7598cb6ae59fdc13104947b66e3e6Alan Viverette#include "llvm/Target/TargetOptions.h"
38f11879ae94e7598cb6ae59fdc13104947b66e3e6Alan Viverette#include "llvm/ADT/SmallSet.h"
39f11879ae94e7598cb6ae59fdc13104947b66e3e6Alan Viverette#include "llvm/ADT/StringExtras.h"
40f11879ae94e7598cb6ae59fdc13104947b66e3e6Alan Viverette#include "llvm/Support/CommandLine.h"
41f11879ae94e7598cb6ae59fdc13104947b66e3e6Alan Viveretteusing namespace llvm;
42f11879ae94e7598cb6ae59fdc13104947b66e3e6Alan Viverette
43f11879ae94e7598cb6ae59fdc13104947b66e3e6Alan Viverettestatic cl::opt<bool>
44f11879ae94e7598cb6ae59fdc13104947b66e3e6Alan ViveretteDisableMMX("disable-mmx", cl::Hidden, cl::desc("Disable use of MMX"));
45f11879ae94e7598cb6ae59fdc13104947b66e3e6Alan Viverette
46f11879ae94e7598cb6ae59fdc13104947b66e3e6Alan Viverette// Forward declarations.
47f11879ae94e7598cb6ae59fdc13104947b66e3e6Alan Viverettestatic SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, MVT VT, SDValue V1,
48f11879ae94e7598cb6ae59fdc13104947b66e3e6Alan Viverette                       SDValue V2);
49f11879ae94e7598cb6ae59fdc13104947b66e3e6Alan Viverette
50f11879ae94e7598cb6ae59fdc13104947b66e3e6Alan ViveretteX86TargetLowering::X86TargetLowering(X86TargetMachine &TM)
51f11879ae94e7598cb6ae59fdc13104947b66e3e6Alan Viverette  : TargetLowering(TM) {
52f11879ae94e7598cb6ae59fdc13104947b66e3e6Alan Viverette  Subtarget = &TM.getSubtarget<X86Subtarget>();
53f11879ae94e7598cb6ae59fdc13104947b66e3e6Alan Viverette  X86ScalarSSEf64 = Subtarget->hasSSE2();
54f11879ae94e7598cb6ae59fdc13104947b66e3e6Alan Viverette  X86ScalarSSEf32 = Subtarget->hasSSE1();
55f11879ae94e7598cb6ae59fdc13104947b66e3e6Alan Viverette  X86StackPtr = Subtarget->is64Bit() ? X86::RSP : X86::ESP;
56f11879ae94e7598cb6ae59fdc13104947b66e3e6Alan Viverette
57f11879ae94e7598cb6ae59fdc13104947b66e3e6Alan Viverette  RegInfo = TM.getRegisterInfo();
58f11879ae94e7598cb6ae59fdc13104947b66e3e6Alan Viverette  TD = getTargetData();
59f11879ae94e7598cb6ae59fdc13104947b66e3e6Alan Viverette
60f11879ae94e7598cb6ae59fdc13104947b66e3e6Alan Viverette  // Set up the TargetLowering object.
61f11879ae94e7598cb6ae59fdc13104947b66e3e6Alan Viverette
62f11879ae94e7598cb6ae59fdc13104947b66e3e6Alan Viverette  // X86 is weird, it always uses i8 for shift amounts and setcc results.
63f11879ae94e7598cb6ae59fdc13104947b66e3e6Alan Viverette  setShiftAmountType(MVT::i8);
64f11879ae94e7598cb6ae59fdc13104947b66e3e6Alan Viverette  setBooleanContents(ZeroOrOneBooleanContent);
65f11879ae94e7598cb6ae59fdc13104947b66e3e6Alan Viverette  setSchedulingPreference(SchedulingForRegPressure);
66f11879ae94e7598cb6ae59fdc13104947b66e3e6Alan Viverette  setShiftAmountFlavor(Mask);   // shl X, 32 == shl X, 0
67f11879ae94e7598cb6ae59fdc13104947b66e3e6Alan Viverette  setStackPointerRegisterToSaveRestore(X86StackPtr);
68f11879ae94e7598cb6ae59fdc13104947b66e3e6Alan Viverette
69f11879ae94e7598cb6ae59fdc13104947b66e3e6Alan Viverette  if (Subtarget->isTargetDarwin()) {
70f11879ae94e7598cb6ae59fdc13104947b66e3e6Alan Viverette    // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
71f11879ae94e7598cb6ae59fdc13104947b66e3e6Alan Viverette    setUseUnderscoreSetJmp(false);
72f11879ae94e7598cb6ae59fdc13104947b66e3e6Alan Viverette    setUseUnderscoreLongJmp(false);
73f11879ae94e7598cb6ae59fdc13104947b66e3e6Alan Viverette  } else if (Subtarget->isTargetMingw()) {
74f11879ae94e7598cb6ae59fdc13104947b66e3e6Alan Viverette    // MS runtime is weird: it exports _setjmp, but longjmp!
75f11879ae94e7598cb6ae59fdc13104947b66e3e6Alan Viverette    setUseUnderscoreSetJmp(true);
76f11879ae94e7598cb6ae59fdc13104947b66e3e6Alan Viverette    setUseUnderscoreLongJmp(false);
77f11879ae94e7598cb6ae59fdc13104947b66e3e6Alan Viverette  } else {
78f11879ae94e7598cb6ae59fdc13104947b66e3e6Alan Viverette    setUseUnderscoreSetJmp(true);
79f11879ae94e7598cb6ae59fdc13104947b66e3e6Alan Viverette    setUseUnderscoreLongJmp(true);
80f11879ae94e7598cb6ae59fdc13104947b66e3e6Alan Viverette  }
81f11879ae94e7598cb6ae59fdc13104947b66e3e6Alan Viverette
82f11879ae94e7598cb6ae59fdc13104947b66e3e6Alan Viverette  // Set up the register classes.
83f11879ae94e7598cb6ae59fdc13104947b66e3e6Alan Viverette  addRegisterClass(MVT::i8, X86::GR8RegisterClass);
84f11879ae94e7598cb6ae59fdc13104947b66e3e6Alan Viverette  addRegisterClass(MVT::i16, X86::GR16RegisterClass);
85f11879ae94e7598cb6ae59fdc13104947b66e3e6Alan Viverette  addRegisterClass(MVT::i32, X86::GR32RegisterClass);
86f11879ae94e7598cb6ae59fdc13104947b66e3e6Alan Viverette  if (Subtarget->is64Bit())
87f11879ae94e7598cb6ae59fdc13104947b66e3e6Alan Viverette    addRegisterClass(MVT::i64, X86::GR64RegisterClass);
88f11879ae94e7598cb6ae59fdc13104947b66e3e6Alan Viverette
89f11879ae94e7598cb6ae59fdc13104947b66e3e6Alan Viverette  setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
90f11879ae94e7598cb6ae59fdc13104947b66e3e6Alan Viverette
91f11879ae94e7598cb6ae59fdc13104947b66e3e6Alan Viverette  // We don't accept any truncstore of integer registers.
92f11879ae94e7598cb6ae59fdc13104947b66e3e6Alan Viverette  setTruncStoreAction(MVT::i64, MVT::i32, Expand);
93f11879ae94e7598cb6ae59fdc13104947b66e3e6Alan Viverette  setTruncStoreAction(MVT::i64, MVT::i16, Expand);
94f11879ae94e7598cb6ae59fdc13104947b66e3e6Alan Viverette  setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
95f11879ae94e7598cb6ae59fdc13104947b66e3e6Alan Viverette  setTruncStoreAction(MVT::i32, MVT::i16, Expand);
96f11879ae94e7598cb6ae59fdc13104947b66e3e6Alan Viverette  setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
97f11879ae94e7598cb6ae59fdc13104947b66e3e6Alan Viverette  setTruncStoreAction(MVT::i16, MVT::i8,  Expand);
98f11879ae94e7598cb6ae59fdc13104947b66e3e6Alan Viverette
99f11879ae94e7598cb6ae59fdc13104947b66e3e6Alan Viverette  // SETOEQ and SETUNE require checking two conditions.
100f11879ae94e7598cb6ae59fdc13104947b66e3e6Alan Viverette  setCondCodeAction(ISD::SETOEQ, MVT::f32, Expand);
101f11879ae94e7598cb6ae59fdc13104947b66e3e6Alan Viverette  setCondCodeAction(ISD::SETOEQ, MVT::f64, Expand);
102f11879ae94e7598cb6ae59fdc13104947b66e3e6Alan Viverette  setCondCodeAction(ISD::SETOEQ, MVT::f80, Expand);
103f11879ae94e7598cb6ae59fdc13104947b66e3e6Alan Viverette  setCondCodeAction(ISD::SETUNE, MVT::f32, Expand);
104f11879ae94e7598cb6ae59fdc13104947b66e3e6Alan Viverette  setCondCodeAction(ISD::SETUNE, MVT::f64, Expand);
105f11879ae94e7598cb6ae59fdc13104947b66e3e6Alan Viverette  setCondCodeAction(ISD::SETUNE, MVT::f80, Expand);
106f11879ae94e7598cb6ae59fdc13104947b66e3e6Alan Viverette
107f11879ae94e7598cb6ae59fdc13104947b66e3e6Alan Viverette  // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
108f11879ae94e7598cb6ae59fdc13104947b66e3e6Alan Viverette  // operation.
109f11879ae94e7598cb6ae59fdc13104947b66e3e6Alan Viverette  setOperationAction(ISD::UINT_TO_FP       , MVT::i1   , Promote);
110f11879ae94e7598cb6ae59fdc13104947b66e3e6Alan Viverette  setOperationAction(ISD::UINT_TO_FP       , MVT::i8   , Promote);
111f11879ae94e7598cb6ae59fdc13104947b66e3e6Alan Viverette  setOperationAction(ISD::UINT_TO_FP       , MVT::i16  , Promote);
112f11879ae94e7598cb6ae59fdc13104947b66e3e6Alan Viverette
113f11879ae94e7598cb6ae59fdc13104947b66e3e6Alan Viverette  if (Subtarget->is64Bit()) {
114f11879ae94e7598cb6ae59fdc13104947b66e3e6Alan Viverette    setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Promote);
115f11879ae94e7598cb6ae59fdc13104947b66e3e6Alan Viverette    setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Expand);
116f11879ae94e7598cb6ae59fdc13104947b66e3e6Alan Viverette  } else if (!UseSoftFloat) {
117f11879ae94e7598cb6ae59fdc13104947b66e3e6Alan Viverette    if (X86ScalarSSEf64) {
118f11879ae94e7598cb6ae59fdc13104947b66e3e6Alan Viverette      // We have an impenetrably clever algorithm for ui64->double only.
119f11879ae94e7598cb6ae59fdc13104947b66e3e6Alan Viverette      setOperationAction(ISD::UINT_TO_FP   , MVT::i64  , Custom);
120f11879ae94e7598cb6ae59fdc13104947b66e3e6Alan Viverette    }
121f11879ae94e7598cb6ae59fdc13104947b66e3e6Alan Viverette    // We have an algorithm for SSE2, and we turn this into a 64-bit
122f11879ae94e7598cb6ae59fdc13104947b66e3e6Alan Viverette    // FILD for other targets.
123f11879ae94e7598cb6ae59fdc13104947b66e3e6Alan Viverette    setOperationAction(ISD::UINT_TO_FP   , MVT::i32  , Custom);
124f11879ae94e7598cb6ae59fdc13104947b66e3e6Alan Viverette  }
125f11879ae94e7598cb6ae59fdc13104947b66e3e6Alan Viverette
126f11879ae94e7598cb6ae59fdc13104947b66e3e6Alan Viverette  // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
127f11879ae94e7598cb6ae59fdc13104947b66e3e6Alan Viverette  // this operation.
128f11879ae94e7598cb6ae59fdc13104947b66e3e6Alan Viverette  setOperationAction(ISD::SINT_TO_FP       , MVT::i1   , Promote);
129f11879ae94e7598cb6ae59fdc13104947b66e3e6Alan Viverette  setOperationAction(ISD::SINT_TO_FP       , MVT::i8   , Promote);
130f11879ae94e7598cb6ae59fdc13104947b66e3e6Alan Viverette
131f11879ae94e7598cb6ae59fdc13104947b66e3e6Alan Viverette  if (!UseSoftFloat) {
132f11879ae94e7598cb6ae59fdc13104947b66e3e6Alan Viverette    // SSE has no i16 to fp conversion, only i32
133f11879ae94e7598cb6ae59fdc13104947b66e3e6Alan Viverette    if (X86ScalarSSEf32) {
134f11879ae94e7598cb6ae59fdc13104947b66e3e6Alan Viverette      setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
135f11879ae94e7598cb6ae59fdc13104947b66e3e6Alan Viverette      // f32 and f64 cases are Legal, f80 case is not
136      setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
137    } else {
138      setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Custom);
139      setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
140    }
141  } else {
142    setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
143    setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Promote);
144  }
145
146  // In 32-bit mode these are custom lowered.  In 64-bit mode F32 and F64
147  // are Legal, f80 is custom lowered.
148  setOperationAction(ISD::FP_TO_SINT     , MVT::i64  , Custom);
149  setOperationAction(ISD::SINT_TO_FP     , MVT::i64  , Custom);
150
151  // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
152  // this operation.
153  setOperationAction(ISD::FP_TO_SINT       , MVT::i1   , Promote);
154  setOperationAction(ISD::FP_TO_SINT       , MVT::i8   , Promote);
155
156  if (X86ScalarSSEf32) {
157    setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Promote);
158    // f32 and f64 cases are Legal, f80 case is not
159    setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
160  } else {
161    setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Custom);
162    setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
163  }
164
165  // Handle FP_TO_UINT by promoting the destination to a larger signed
166  // conversion.
167  setOperationAction(ISD::FP_TO_UINT       , MVT::i1   , Promote);
168  setOperationAction(ISD::FP_TO_UINT       , MVT::i8   , Promote);
169  setOperationAction(ISD::FP_TO_UINT       , MVT::i16  , Promote);
170
171  if (Subtarget->is64Bit()) {
172    setOperationAction(ISD::FP_TO_UINT     , MVT::i64  , Expand);
173    setOperationAction(ISD::FP_TO_UINT     , MVT::i32  , Promote);
174  } else if (!UseSoftFloat) {
175    if (X86ScalarSSEf32 && !Subtarget->hasSSE3())
176      // Expand FP_TO_UINT into a select.
177      // FIXME: We would like to use a Custom expander here eventually to do
178      // the optimal thing for SSE vs. the default expansion in the legalizer.
179      setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Expand);
180    else
181      // With SSE3 we can use fisttpll to convert to a signed i64; without
182      // SSE, we're stuck with a fistpll.
183      setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Custom);
184  }
185
186  // TODO: when we have SSE, these could be more efficient, by using movd/movq.
187  if (!X86ScalarSSEf64) {
188    setOperationAction(ISD::BIT_CONVERT      , MVT::f32  , Expand);
189    setOperationAction(ISD::BIT_CONVERT      , MVT::i32  , Expand);
190  }
191
192  // Scalar integer divide and remainder are lowered to use operations that
193  // produce two results, to match the available instructions. This exposes
194  // the two-result form to trivial CSE, which is able to combine x/y and x%y
195  // into a single instruction.
196  //
197  // Scalar integer multiply-high is also lowered to use two-result
198  // operations, to match the available instructions. However, plain multiply
199  // (low) operations are left as Legal, as there are single-result
200  // instructions for this in x86. Using the two-result multiply instructions
201  // when both high and low results are needed must be arranged by dagcombine.
202  setOperationAction(ISD::MULHS           , MVT::i8    , Expand);
203  setOperationAction(ISD::MULHU           , MVT::i8    , Expand);
204  setOperationAction(ISD::SDIV            , MVT::i8    , Expand);
205  setOperationAction(ISD::UDIV            , MVT::i8    , Expand);
206  setOperationAction(ISD::SREM            , MVT::i8    , Expand);
207  setOperationAction(ISD::UREM            , MVT::i8    , Expand);
208  setOperationAction(ISD::MULHS           , MVT::i16   , Expand);
209  setOperationAction(ISD::MULHU           , MVT::i16   , Expand);
210  setOperationAction(ISD::SDIV            , MVT::i16   , Expand);
211  setOperationAction(ISD::UDIV            , MVT::i16   , Expand);
212  setOperationAction(ISD::SREM            , MVT::i16   , Expand);
213  setOperationAction(ISD::UREM            , MVT::i16   , Expand);
214  setOperationAction(ISD::MULHS           , MVT::i32   , Expand);
215  setOperationAction(ISD::MULHU           , MVT::i32   , Expand);
216  setOperationAction(ISD::SDIV            , MVT::i32   , Expand);
217  setOperationAction(ISD::UDIV            , MVT::i32   , Expand);
218  setOperationAction(ISD::SREM            , MVT::i32   , Expand);
219  setOperationAction(ISD::UREM            , MVT::i32   , Expand);
220  setOperationAction(ISD::MULHS           , MVT::i64   , Expand);
221  setOperationAction(ISD::MULHU           , MVT::i64   , Expand);
222  setOperationAction(ISD::SDIV            , MVT::i64   , Expand);
223  setOperationAction(ISD::UDIV            , MVT::i64   , Expand);
224  setOperationAction(ISD::SREM            , MVT::i64   , Expand);
225  setOperationAction(ISD::UREM            , MVT::i64   , Expand);
226
227  setOperationAction(ISD::BR_JT            , MVT::Other, Expand);
228  setOperationAction(ISD::BRCOND           , MVT::Other, Custom);
229  setOperationAction(ISD::BR_CC            , MVT::Other, Expand);
230  setOperationAction(ISD::SELECT_CC        , MVT::Other, Expand);
231  if (Subtarget->is64Bit())
232    setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
233  setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16  , Legal);
234  setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8   , Legal);
235  setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1   , Expand);
236  setOperationAction(ISD::FP_ROUND_INREG   , MVT::f32  , Expand);
237  setOperationAction(ISD::FREM             , MVT::f32  , Expand);
238  setOperationAction(ISD::FREM             , MVT::f64  , Expand);
239  setOperationAction(ISD::FREM             , MVT::f80  , Expand);
240  setOperationAction(ISD::FLT_ROUNDS_      , MVT::i32  , Custom);
241
242  setOperationAction(ISD::CTPOP            , MVT::i8   , Expand);
243  setOperationAction(ISD::CTTZ             , MVT::i8   , Custom);
244  setOperationAction(ISD::CTLZ             , MVT::i8   , Custom);
245  setOperationAction(ISD::CTPOP            , MVT::i16  , Expand);
246  setOperationAction(ISD::CTTZ             , MVT::i16  , Custom);
247  setOperationAction(ISD::CTLZ             , MVT::i16  , Custom);
248  setOperationAction(ISD::CTPOP            , MVT::i32  , Expand);
249  setOperationAction(ISD::CTTZ             , MVT::i32  , Custom);
250  setOperationAction(ISD::CTLZ             , MVT::i32  , Custom);
251  if (Subtarget->is64Bit()) {
252    setOperationAction(ISD::CTPOP          , MVT::i64  , Expand);
253    setOperationAction(ISD::CTTZ           , MVT::i64  , Custom);
254    setOperationAction(ISD::CTLZ           , MVT::i64  , Custom);
255  }
256
257  setOperationAction(ISD::READCYCLECOUNTER , MVT::i64  , Custom);
258  setOperationAction(ISD::BSWAP            , MVT::i16  , Expand);
259
260  // These should be promoted to a larger select which is supported.
261  setOperationAction(ISD::SELECT           , MVT::i1   , Promote);
262  setOperationAction(ISD::SELECT           , MVT::i8   , Promote);
263  // X86 wants to expand cmov itself.
264  setOperationAction(ISD::SELECT          , MVT::i16  , Custom);
265  setOperationAction(ISD::SELECT          , MVT::i32  , Custom);
266  setOperationAction(ISD::SELECT          , MVT::f32  , Custom);
267  setOperationAction(ISD::SELECT          , MVT::f64  , Custom);
268  setOperationAction(ISD::SELECT          , MVT::f80  , Custom);
269  setOperationAction(ISD::SETCC           , MVT::i8   , Custom);
270  setOperationAction(ISD::SETCC           , MVT::i16  , Custom);
271  setOperationAction(ISD::SETCC           , MVT::i32  , Custom);
272  setOperationAction(ISD::SETCC           , MVT::f32  , Custom);
273  setOperationAction(ISD::SETCC           , MVT::f64  , Custom);
274  setOperationAction(ISD::SETCC           , MVT::f80  , Custom);
275  if (Subtarget->is64Bit()) {
276    setOperationAction(ISD::SELECT        , MVT::i64  , Custom);
277    setOperationAction(ISD::SETCC         , MVT::i64  , Custom);
278  }
279  // X86 ret instruction may pop stack.
280  setOperationAction(ISD::RET             , MVT::Other, Custom);
281  setOperationAction(ISD::EH_RETURN       , MVT::Other, Custom);
282
283  // Darwin ABI issue.
284  setOperationAction(ISD::ConstantPool    , MVT::i32  , Custom);
285  setOperationAction(ISD::JumpTable       , MVT::i32  , Custom);
286  setOperationAction(ISD::GlobalAddress   , MVT::i32  , Custom);
287  setOperationAction(ISD::GlobalTLSAddress, MVT::i32  , Custom);
288  if (Subtarget->is64Bit())
289    setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
290  setOperationAction(ISD::ExternalSymbol  , MVT::i32  , Custom);
291  if (Subtarget->is64Bit()) {
292    setOperationAction(ISD::ConstantPool  , MVT::i64  , Custom);
293    setOperationAction(ISD::JumpTable     , MVT::i64  , Custom);
294    setOperationAction(ISD::GlobalAddress , MVT::i64  , Custom);
295    setOperationAction(ISD::ExternalSymbol, MVT::i64  , Custom);
296  }
297  // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
298  setOperationAction(ISD::SHL_PARTS       , MVT::i32  , Custom);
299  setOperationAction(ISD::SRA_PARTS       , MVT::i32  , Custom);
300  setOperationAction(ISD::SRL_PARTS       , MVT::i32  , Custom);
301  if (Subtarget->is64Bit()) {
302    setOperationAction(ISD::SHL_PARTS     , MVT::i64  , Custom);
303    setOperationAction(ISD::SRA_PARTS     , MVT::i64  , Custom);
304    setOperationAction(ISD::SRL_PARTS     , MVT::i64  , Custom);
305  }
306
307  if (Subtarget->hasSSE1())
308    setOperationAction(ISD::PREFETCH      , MVT::Other, Legal);
309
310  if (!Subtarget->hasSSE2())
311    setOperationAction(ISD::MEMBARRIER    , MVT::Other, Expand);
312
313  // Expand certain atomics
314  setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i8, Custom);
315  setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i16, Custom);
316  setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Custom);
317  setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i64, Custom);
318
319  setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i8, Custom);
320  setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i16, Custom);
321  setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i32, Custom);
322  setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
323
324  if (!Subtarget->is64Bit()) {
325    setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i64, Custom);
326    setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
327    setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i64, Custom);
328    setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i64, Custom);
329    setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i64, Custom);
330    setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i64, Custom);
331    setOperationAction(ISD::ATOMIC_SWAP, MVT::i64, Custom);
332  }
333
334  // Use the default ISD::DBG_STOPPOINT, ISD::DECLARE expansion.
335  setOperationAction(ISD::DBG_STOPPOINT, MVT::Other, Expand);
336  // FIXME - use subtarget debug flags
337  if (!Subtarget->isTargetDarwin() &&
338      !Subtarget->isTargetELF() &&
339      !Subtarget->isTargetCygMing()) {
340    setOperationAction(ISD::DBG_LABEL, MVT::Other, Expand);
341    setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
342  }
343
344  setOperationAction(ISD::EXCEPTIONADDR, MVT::i64, Expand);
345  setOperationAction(ISD::EHSELECTION,   MVT::i64, Expand);
346  setOperationAction(ISD::EXCEPTIONADDR, MVT::i32, Expand);
347  setOperationAction(ISD::EHSELECTION,   MVT::i32, Expand);
348  if (Subtarget->is64Bit()) {
349    setExceptionPointerRegister(X86::RAX);
350    setExceptionSelectorRegister(X86::RDX);
351  } else {
352    setExceptionPointerRegister(X86::EAX);
353    setExceptionSelectorRegister(X86::EDX);
354  }
355  setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
356  setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
357
358  setOperationAction(ISD::TRAMPOLINE, MVT::Other, Custom);
359
360  setOperationAction(ISD::TRAP, MVT::Other, Legal);
361
362  // VASTART needs to be custom lowered to use the VarArgsFrameIndex
363  setOperationAction(ISD::VASTART           , MVT::Other, Custom);
364  setOperationAction(ISD::VAEND             , MVT::Other, Expand);
365  if (Subtarget->is64Bit()) {
366    setOperationAction(ISD::VAARG           , MVT::Other, Custom);
367    setOperationAction(ISD::VACOPY          , MVT::Other, Custom);
368  } else {
369    setOperationAction(ISD::VAARG           , MVT::Other, Expand);
370    setOperationAction(ISD::VACOPY          , MVT::Other, Expand);
371  }
372
373  setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
374  setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
375  if (Subtarget->is64Bit())
376    setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64, Expand);
377  if (Subtarget->isTargetCygMing())
378    setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Custom);
379  else
380    setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
381
382  if (!UseSoftFloat && X86ScalarSSEf64) {
383    // f32 and f64 use SSE.
384    // Set up the FP register classes.
385    addRegisterClass(MVT::f32, X86::FR32RegisterClass);
386    addRegisterClass(MVT::f64, X86::FR64RegisterClass);
387
388    // Use ANDPD to simulate FABS.
389    setOperationAction(ISD::FABS , MVT::f64, Custom);
390    setOperationAction(ISD::FABS , MVT::f32, Custom);
391
392    // Use XORP to simulate FNEG.
393    setOperationAction(ISD::FNEG , MVT::f64, Custom);
394    setOperationAction(ISD::FNEG , MVT::f32, Custom);
395
396    // Use ANDPD and ORPD to simulate FCOPYSIGN.
397    setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
398    setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
399
400    // We don't support sin/cos/fmod
401    setOperationAction(ISD::FSIN , MVT::f64, Expand);
402    setOperationAction(ISD::FCOS , MVT::f64, Expand);
403    setOperationAction(ISD::FSIN , MVT::f32, Expand);
404    setOperationAction(ISD::FCOS , MVT::f32, Expand);
405
406    // Expand FP immediates into loads from the stack, except for the special
407    // cases we handle.
408    addLegalFPImmediate(APFloat(+0.0)); // xorpd
409    addLegalFPImmediate(APFloat(+0.0f)); // xorps
410  } else if (!UseSoftFloat && X86ScalarSSEf32) {
411    // Use SSE for f32, x87 for f64.
412    // Set up the FP register classes.
413    addRegisterClass(MVT::f32, X86::FR32RegisterClass);
414    addRegisterClass(MVT::f64, X86::RFP64RegisterClass);
415
416    // Use ANDPS to simulate FABS.
417    setOperationAction(ISD::FABS , MVT::f32, Custom);
418
419    // Use XORP to simulate FNEG.
420    setOperationAction(ISD::FNEG , MVT::f32, Custom);
421
422    setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
423
424    // Use ANDPS and ORPS to simulate FCOPYSIGN.
425    setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
426    setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
427
428    // We don't support sin/cos/fmod
429    setOperationAction(ISD::FSIN , MVT::f32, Expand);
430    setOperationAction(ISD::FCOS , MVT::f32, Expand);
431
432    // Special cases we handle for FP constants.
433    addLegalFPImmediate(APFloat(+0.0f)); // xorps
434    addLegalFPImmediate(APFloat(+0.0)); // FLD0
435    addLegalFPImmediate(APFloat(+1.0)); // FLD1
436    addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
437    addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
438
439    if (!UnsafeFPMath) {
440      setOperationAction(ISD::FSIN           , MVT::f64  , Expand);
441      setOperationAction(ISD::FCOS           , MVT::f64  , Expand);
442    }
443  } else if (!UseSoftFloat) {
444    // f32 and f64 in x87.
445    // Set up the FP register classes.
446    addRegisterClass(MVT::f64, X86::RFP64RegisterClass);
447    addRegisterClass(MVT::f32, X86::RFP32RegisterClass);
448
449    setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
450    setOperationAction(ISD::UNDEF,     MVT::f32, Expand);
451    setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
452    setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
453
454    if (!UnsafeFPMath) {
455      setOperationAction(ISD::FSIN           , MVT::f64  , Expand);
456      setOperationAction(ISD::FCOS           , MVT::f64  , Expand);
457    }
458    addLegalFPImmediate(APFloat(+0.0)); // FLD0
459    addLegalFPImmediate(APFloat(+1.0)); // FLD1
460    addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
461    addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
462    addLegalFPImmediate(APFloat(+0.0f)); // FLD0
463    addLegalFPImmediate(APFloat(+1.0f)); // FLD1
464    addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
465    addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
466  }
467
468  // Long double always uses X87.
469  if (!UseSoftFloat) {
470    addRegisterClass(MVT::f80, X86::RFP80RegisterClass);
471    setOperationAction(ISD::UNDEF,     MVT::f80, Expand);
472    setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
473    {
474      bool ignored;
475      APFloat TmpFlt(+0.0);
476      TmpFlt.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
477                     &ignored);
478      addLegalFPImmediate(TmpFlt);  // FLD0
479      TmpFlt.changeSign();
480      addLegalFPImmediate(TmpFlt);  // FLD0/FCHS
481      APFloat TmpFlt2(+1.0);
482      TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
483                      &ignored);
484      addLegalFPImmediate(TmpFlt2);  // FLD1
485      TmpFlt2.changeSign();
486      addLegalFPImmediate(TmpFlt2);  // FLD1/FCHS
487    }
488
489    if (!UnsafeFPMath) {
490      setOperationAction(ISD::FSIN           , MVT::f80  , Expand);
491      setOperationAction(ISD::FCOS           , MVT::f80  , Expand);
492    }
493  }
494
495  // Always use a library call for pow.
496  setOperationAction(ISD::FPOW             , MVT::f32  , Expand);
497  setOperationAction(ISD::FPOW             , MVT::f64  , Expand);
498  setOperationAction(ISD::FPOW             , MVT::f80  , Expand);
499
500  setOperationAction(ISD::FLOG, MVT::f80, Expand);
501  setOperationAction(ISD::FLOG2, MVT::f80, Expand);
502  setOperationAction(ISD::FLOG10, MVT::f80, Expand);
503  setOperationAction(ISD::FEXP, MVT::f80, Expand);
504  setOperationAction(ISD::FEXP2, MVT::f80, Expand);
505
506  // First set operation action for all vector types to either promote
507  // (for widening) or expand (for scalarization). Then we will selectively
508  // turn on ones that can be effectively codegen'd.
509  for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
510       VT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++VT) {
511    setOperationAction(ISD::ADD , (MVT::SimpleValueType)VT, Expand);
512    setOperationAction(ISD::SUB , (MVT::SimpleValueType)VT, Expand);
513    setOperationAction(ISD::FADD, (MVT::SimpleValueType)VT, Expand);
514    setOperationAction(ISD::FNEG, (MVT::SimpleValueType)VT, Expand);
515    setOperationAction(ISD::FSUB, (MVT::SimpleValueType)VT, Expand);
516    setOperationAction(ISD::MUL , (MVT::SimpleValueType)VT, Expand);
517    setOperationAction(ISD::FMUL, (MVT::SimpleValueType)VT, Expand);
518    setOperationAction(ISD::SDIV, (MVT::SimpleValueType)VT, Expand);
519    setOperationAction(ISD::UDIV, (MVT::SimpleValueType)VT, Expand);
520    setOperationAction(ISD::FDIV, (MVT::SimpleValueType)VT, Expand);
521    setOperationAction(ISD::SREM, (MVT::SimpleValueType)VT, Expand);
522    setOperationAction(ISD::UREM, (MVT::SimpleValueType)VT, Expand);
523    setOperationAction(ISD::LOAD, (MVT::SimpleValueType)VT, Expand);
524    setOperationAction(ISD::VECTOR_SHUFFLE, (MVT::SimpleValueType)VT, Expand);
525    setOperationAction(ISD::EXTRACT_VECTOR_ELT,(MVT::SimpleValueType)VT,Expand);
526    setOperationAction(ISD::EXTRACT_SUBVECTOR,(MVT::SimpleValueType)VT,Expand);
527    setOperationAction(ISD::INSERT_VECTOR_ELT,(MVT::SimpleValueType)VT, Expand);
528    setOperationAction(ISD::FABS, (MVT::SimpleValueType)VT, Expand);
529    setOperationAction(ISD::FSIN, (MVT::SimpleValueType)VT, Expand);
530    setOperationAction(ISD::FCOS, (MVT::SimpleValueType)VT, Expand);
531    setOperationAction(ISD::FREM, (MVT::SimpleValueType)VT, Expand);
532    setOperationAction(ISD::FPOWI, (MVT::SimpleValueType)VT, Expand);
533    setOperationAction(ISD::FSQRT, (MVT::SimpleValueType)VT, Expand);
534    setOperationAction(ISD::FCOPYSIGN, (MVT::SimpleValueType)VT, Expand);
535    setOperationAction(ISD::SMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
536    setOperationAction(ISD::UMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
537    setOperationAction(ISD::SDIVREM, (MVT::SimpleValueType)VT, Expand);
538    setOperationAction(ISD::UDIVREM, (MVT::SimpleValueType)VT, Expand);
539    setOperationAction(ISD::FPOW, (MVT::SimpleValueType)VT, Expand);
540    setOperationAction(ISD::CTPOP, (MVT::SimpleValueType)VT, Expand);
541    setOperationAction(ISD::CTTZ, (MVT::SimpleValueType)VT, Expand);
542    setOperationAction(ISD::CTLZ, (MVT::SimpleValueType)VT, Expand);
543    setOperationAction(ISD::SHL, (MVT::SimpleValueType)VT, Expand);
544    setOperationAction(ISD::SRA, (MVT::SimpleValueType)VT, Expand);
545    setOperationAction(ISD::SRL, (MVT::SimpleValueType)VT, Expand);
546    setOperationAction(ISD::ROTL, (MVT::SimpleValueType)VT, Expand);
547    setOperationAction(ISD::ROTR, (MVT::SimpleValueType)VT, Expand);
548    setOperationAction(ISD::BSWAP, (MVT::SimpleValueType)VT, Expand);
549    setOperationAction(ISD::VSETCC, (MVT::SimpleValueType)VT, Expand);
550    setOperationAction(ISD::FLOG, (MVT::SimpleValueType)VT, Expand);
551    setOperationAction(ISD::FLOG2, (MVT::SimpleValueType)VT, Expand);
552    setOperationAction(ISD::FLOG10, (MVT::SimpleValueType)VT, Expand);
553    setOperationAction(ISD::FEXP, (MVT::SimpleValueType)VT, Expand);
554    setOperationAction(ISD::FEXP2, (MVT::SimpleValueType)VT, Expand);
555    setOperationAction(ISD::FP_TO_UINT, (MVT::SimpleValueType)VT, Expand);
556    setOperationAction(ISD::FP_TO_SINT, (MVT::SimpleValueType)VT, Expand);
557    setOperationAction(ISD::UINT_TO_FP, (MVT::SimpleValueType)VT, Expand);
558    setOperationAction(ISD::SINT_TO_FP, (MVT::SimpleValueType)VT, Expand);
559  }
560
561  // FIXME: In order to prevent SSE instructions being expanded to MMX ones
562  // with -msoft-float, disable use of MMX as well.
563  if (!UseSoftFloat && !DisableMMX && Subtarget->hasMMX()) {
564    addRegisterClass(MVT::v8i8,  X86::VR64RegisterClass);
565    addRegisterClass(MVT::v4i16, X86::VR64RegisterClass);
566    addRegisterClass(MVT::v2i32, X86::VR64RegisterClass);
567    addRegisterClass(MVT::v2f32, X86::VR64RegisterClass);
568    addRegisterClass(MVT::v1i64, X86::VR64RegisterClass);
569
570    setOperationAction(ISD::ADD,                MVT::v8i8,  Legal);
571    setOperationAction(ISD::ADD,                MVT::v4i16, Legal);
572    setOperationAction(ISD::ADD,                MVT::v2i32, Legal);
573    setOperationAction(ISD::ADD,                MVT::v1i64, Legal);
574
575    setOperationAction(ISD::SUB,                MVT::v8i8,  Legal);
576    setOperationAction(ISD::SUB,                MVT::v4i16, Legal);
577    setOperationAction(ISD::SUB,                MVT::v2i32, Legal);
578    setOperationAction(ISD::SUB,                MVT::v1i64, Legal);
579
580    setOperationAction(ISD::MULHS,              MVT::v4i16, Legal);
581    setOperationAction(ISD::MUL,                MVT::v4i16, Legal);
582
583    setOperationAction(ISD::AND,                MVT::v8i8,  Promote);
584    AddPromotedToType (ISD::AND,                MVT::v8i8,  MVT::v1i64);
585    setOperationAction(ISD::AND,                MVT::v4i16, Promote);
586    AddPromotedToType (ISD::AND,                MVT::v4i16, MVT::v1i64);
587    setOperationAction(ISD::AND,                MVT::v2i32, Promote);
588    AddPromotedToType (ISD::AND,                MVT::v2i32, MVT::v1i64);
589    setOperationAction(ISD::AND,                MVT::v1i64, Legal);
590
591    setOperationAction(ISD::OR,                 MVT::v8i8,  Promote);
592    AddPromotedToType (ISD::OR,                 MVT::v8i8,  MVT::v1i64);
593    setOperationAction(ISD::OR,                 MVT::v4i16, Promote);
594    AddPromotedToType (ISD::OR,                 MVT::v4i16, MVT::v1i64);
595    setOperationAction(ISD::OR,                 MVT::v2i32, Promote);
596    AddPromotedToType (ISD::OR,                 MVT::v2i32, MVT::v1i64);
597    setOperationAction(ISD::OR,                 MVT::v1i64, Legal);
598
599    setOperationAction(ISD::XOR,                MVT::v8i8,  Promote);
600    AddPromotedToType (ISD::XOR,                MVT::v8i8,  MVT::v1i64);
601    setOperationAction(ISD::XOR,                MVT::v4i16, Promote);
602    AddPromotedToType (ISD::XOR,                MVT::v4i16, MVT::v1i64);
603    setOperationAction(ISD::XOR,                MVT::v2i32, Promote);
604    AddPromotedToType (ISD::XOR,                MVT::v2i32, MVT::v1i64);
605    setOperationAction(ISD::XOR,                MVT::v1i64, Legal);
606
607    setOperationAction(ISD::LOAD,               MVT::v8i8,  Promote);
608    AddPromotedToType (ISD::LOAD,               MVT::v8i8,  MVT::v1i64);
609    setOperationAction(ISD::LOAD,               MVT::v4i16, Promote);
610    AddPromotedToType (ISD::LOAD,               MVT::v4i16, MVT::v1i64);
611    setOperationAction(ISD::LOAD,               MVT::v2i32, Promote);
612    AddPromotedToType (ISD::LOAD,               MVT::v2i32, MVT::v1i64);
613    setOperationAction(ISD::LOAD,               MVT::v2f32, Promote);
614    AddPromotedToType (ISD::LOAD,               MVT::v2f32, MVT::v1i64);
615    setOperationAction(ISD::LOAD,               MVT::v1i64, Legal);
616
617    setOperationAction(ISD::BUILD_VECTOR,       MVT::v8i8,  Custom);
618    setOperationAction(ISD::BUILD_VECTOR,       MVT::v4i16, Custom);
619    setOperationAction(ISD::BUILD_VECTOR,       MVT::v2i32, Custom);
620    setOperationAction(ISD::BUILD_VECTOR,       MVT::v2f32, Custom);
621    setOperationAction(ISD::BUILD_VECTOR,       MVT::v1i64, Custom);
622
623    setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v8i8,  Custom);
624    setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4i16, Custom);
625    setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2i32, Custom);
626    setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v1i64, Custom);
627
628    setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v2f32, Custom);
629    setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i8,  Custom);
630    setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v4i16, Custom);
631    setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v1i64, Custom);
632
633    setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i16, Custom);
634
635    setTruncStoreAction(MVT::v8i16,             MVT::v8i8, Expand);
636    setOperationAction(ISD::TRUNCATE,           MVT::v8i8, Expand);
637    setOperationAction(ISD::SELECT,             MVT::v8i8, Promote);
638    setOperationAction(ISD::SELECT,             MVT::v4i16, Promote);
639    setOperationAction(ISD::SELECT,             MVT::v2i32, Promote);
640    setOperationAction(ISD::SELECT,             MVT::v1i64, Custom);
641  }
642
643  if (!UseSoftFloat && Subtarget->hasSSE1()) {
644    addRegisterClass(MVT::v4f32, X86::VR128RegisterClass);
645
646    setOperationAction(ISD::FADD,               MVT::v4f32, Legal);
647    setOperationAction(ISD::FSUB,               MVT::v4f32, Legal);
648    setOperationAction(ISD::FMUL,               MVT::v4f32, Legal);
649    setOperationAction(ISD::FDIV,               MVT::v4f32, Legal);
650    setOperationAction(ISD::FSQRT,              MVT::v4f32, Legal);
651    setOperationAction(ISD::FNEG,               MVT::v4f32, Custom);
652    setOperationAction(ISD::LOAD,               MVT::v4f32, Legal);
653    setOperationAction(ISD::BUILD_VECTOR,       MVT::v4f32, Custom);
654    setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4f32, Custom);
655    setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
656    setOperationAction(ISD::SELECT,             MVT::v4f32, Custom);
657    setOperationAction(ISD::VSETCC,             MVT::v4f32, Custom);
658  }
659
660  if (!UseSoftFloat && Subtarget->hasSSE2()) {
661    addRegisterClass(MVT::v2f64, X86::VR128RegisterClass);
662
663    // FIXME: Unfortunately -soft-float and -no-implicit-float means XMM
664    // registers cannot be used even for integer operations.
665    addRegisterClass(MVT::v16i8, X86::VR128RegisterClass);
666    addRegisterClass(MVT::v8i16, X86::VR128RegisterClass);
667    addRegisterClass(MVT::v4i32, X86::VR128RegisterClass);
668    addRegisterClass(MVT::v2i64, X86::VR128RegisterClass);
669
670    setOperationAction(ISD::ADD,                MVT::v16i8, Legal);
671    setOperationAction(ISD::ADD,                MVT::v8i16, Legal);
672    setOperationAction(ISD::ADD,                MVT::v4i32, Legal);
673    setOperationAction(ISD::ADD,                MVT::v2i64, Legal);
674    setOperationAction(ISD::MUL,                MVT::v2i64, Custom);
675    setOperationAction(ISD::SUB,                MVT::v16i8, Legal);
676    setOperationAction(ISD::SUB,                MVT::v8i16, Legal);
677    setOperationAction(ISD::SUB,                MVT::v4i32, Legal);
678    setOperationAction(ISD::SUB,                MVT::v2i64, Legal);
679    setOperationAction(ISD::MUL,                MVT::v8i16, Legal);
680    setOperationAction(ISD::FADD,               MVT::v2f64, Legal);
681    setOperationAction(ISD::FSUB,               MVT::v2f64, Legal);
682    setOperationAction(ISD::FMUL,               MVT::v2f64, Legal);
683    setOperationAction(ISD::FDIV,               MVT::v2f64, Legal);
684    setOperationAction(ISD::FSQRT,              MVT::v2f64, Legal);
685    setOperationAction(ISD::FNEG,               MVT::v2f64, Custom);
686
687    setOperationAction(ISD::VSETCC,             MVT::v2f64, Custom);
688    setOperationAction(ISD::VSETCC,             MVT::v16i8, Custom);
689    setOperationAction(ISD::VSETCC,             MVT::v8i16, Custom);
690    setOperationAction(ISD::VSETCC,             MVT::v4i32, Custom);
691
692    setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v16i8, Custom);
693    setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i16, Custom);
694    setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
695    setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
696    setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
697
698    // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
699    for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v2i64; ++i) {
700      MVT VT = (MVT::SimpleValueType)i;
701      // Do not attempt to custom lower non-power-of-2 vectors
702      if (!isPowerOf2_32(VT.getVectorNumElements()))
703        continue;
704      // Do not attempt to custom lower non-128-bit vectors
705      if (!VT.is128BitVector())
706        continue;
707      setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
708      setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
709      setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
710    }
711
712    setOperationAction(ISD::BUILD_VECTOR,       MVT::v2f64, Custom);
713    setOperationAction(ISD::BUILD_VECTOR,       MVT::v2i64, Custom);
714    setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2f64, Custom);
715    setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2i64, Custom);
716    setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2f64, Custom);
717    setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
718
719    if (Subtarget->is64Bit()) {
720      setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
721      setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
722    }
723
724    // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
725    for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v2i64; i++) {
726      MVT VT = (MVT::SimpleValueType)i;
727
728      // Do not attempt to promote non-128-bit vectors
729      if (!VT.is128BitVector()) {
730        continue;
731      }
732      setOperationAction(ISD::AND,    VT, Promote);
733      AddPromotedToType (ISD::AND,    VT, MVT::v2i64);
734      setOperationAction(ISD::OR,     VT, Promote);
735      AddPromotedToType (ISD::OR,     VT, MVT::v2i64);
736      setOperationAction(ISD::XOR,    VT, Promote);
737      AddPromotedToType (ISD::XOR,    VT, MVT::v2i64);
738      setOperationAction(ISD::LOAD,   VT, Promote);
739      AddPromotedToType (ISD::LOAD,   VT, MVT::v2i64);
740      setOperationAction(ISD::SELECT, VT, Promote);
741      AddPromotedToType (ISD::SELECT, VT, MVT::v2i64);
742    }
743
744    setTruncStoreAction(MVT::f64, MVT::f32, Expand);
745
746    // Custom lower v2i64 and v2f64 selects.
747    setOperationAction(ISD::LOAD,               MVT::v2f64, Legal);
748    setOperationAction(ISD::LOAD,               MVT::v2i64, Legal);
749    setOperationAction(ISD::SELECT,             MVT::v2f64, Custom);
750    setOperationAction(ISD::SELECT,             MVT::v2i64, Custom);
751
752    setOperationAction(ISD::FP_TO_SINT,         MVT::v4i32, Legal);
753    setOperationAction(ISD::SINT_TO_FP,         MVT::v4i32, Legal);
754    if (!DisableMMX && Subtarget->hasMMX()) {
755      setOperationAction(ISD::FP_TO_SINT,         MVT::v2i32, Custom);
756      setOperationAction(ISD::SINT_TO_FP,         MVT::v2i32, Custom);
757    }
758  }
759
760  if (Subtarget->hasSSE41()) {
761    // FIXME: Do we need to handle scalar-to-vector here?
762    setOperationAction(ISD::MUL,                MVT::v4i32, Legal);
763
764    // i8 and i16 vectors are custom , because the source register and source
765    // source memory operand types are not the same width.  f32 vectors are
766    // custom since the immediate controlling the insert encodes additional
767    // information.
768    setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i8, Custom);
769    setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
770    setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
771    setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
772
773    setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
774    setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
775    setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
776    setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
777
778    if (Subtarget->is64Bit()) {
779      setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Legal);
780      setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Legal);
781    }
782  }
783
784  if (Subtarget->hasSSE42()) {
785    setOperationAction(ISD::VSETCC,             MVT::v2i64, Custom);
786  }
787
788  if (!UseSoftFloat && Subtarget->hasAVX()) {
789    addRegisterClass(MVT::v8f32, X86::VR256RegisterClass);
790    addRegisterClass(MVT::v4f64, X86::VR256RegisterClass);
791    addRegisterClass(MVT::v8i32, X86::VR256RegisterClass);
792    addRegisterClass(MVT::v4i64, X86::VR256RegisterClass);
793
794    setOperationAction(ISD::LOAD,               MVT::v8f32, Legal);
795    setOperationAction(ISD::LOAD,               MVT::v8i32, Legal);
796    setOperationAction(ISD::LOAD,               MVT::v4f64, Legal);
797    setOperationAction(ISD::LOAD,               MVT::v4i64, Legal);
798    setOperationAction(ISD::FADD,               MVT::v8f32, Legal);
799    setOperationAction(ISD::FSUB,               MVT::v8f32, Legal);
800    setOperationAction(ISD::FMUL,               MVT::v8f32, Legal);
801    setOperationAction(ISD::FDIV,               MVT::v8f32, Legal);
802    setOperationAction(ISD::FSQRT,              MVT::v8f32, Legal);
803    setOperationAction(ISD::FNEG,               MVT::v8f32, Custom);
804    //setOperationAction(ISD::BUILD_VECTOR,       MVT::v8f32, Custom);
805    //setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v8f32, Custom);
806    //setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8f32, Custom);
807    //setOperationAction(ISD::SELECT,             MVT::v8f32, Custom);
808    //setOperationAction(ISD::VSETCC,             MVT::v8f32, Custom);
809
810    // Operations to consider commented out -v16i16 v32i8
811    //setOperationAction(ISD::ADD,                MVT::v16i16, Legal);
812    setOperationAction(ISD::ADD,                MVT::v8i32, Custom);
813    setOperationAction(ISD::ADD,                MVT::v4i64, Custom);
814    //setOperationAction(ISD::SUB,                MVT::v32i8, Legal);
815    //setOperationAction(ISD::SUB,                MVT::v16i16, Legal);
816    setOperationAction(ISD::SUB,                MVT::v8i32, Custom);
817    setOperationAction(ISD::SUB,                MVT::v4i64, Custom);
818    //setOperationAction(ISD::MUL,                MVT::v16i16, Legal);
819    setOperationAction(ISD::FADD,               MVT::v4f64, Legal);
820    setOperationAction(ISD::FSUB,               MVT::v4f64, Legal);
821    setOperationAction(ISD::FMUL,               MVT::v4f64, Legal);
822    setOperationAction(ISD::FDIV,               MVT::v4f64, Legal);
823    setOperationAction(ISD::FSQRT,              MVT::v4f64, Legal);
824    setOperationAction(ISD::FNEG,               MVT::v4f64, Custom);
825
826    setOperationAction(ISD::VSETCC,             MVT::v4f64, Custom);
827    // setOperationAction(ISD::VSETCC,             MVT::v32i8, Custom);
828    // setOperationAction(ISD::VSETCC,             MVT::v16i16, Custom);
829    setOperationAction(ISD::VSETCC,             MVT::v8i32, Custom);
830
831    // setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v32i8, Custom);
832    // setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v16i16, Custom);
833    // setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i16, Custom);
834    setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i32, Custom);
835    setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8f32, Custom);
836
837    setOperationAction(ISD::BUILD_VECTOR,       MVT::v4f64, Custom);
838    setOperationAction(ISD::BUILD_VECTOR,       MVT::v4i64, Custom);
839    setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4f64, Custom);
840    setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4i64, Custom);
841    setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f64, Custom);
842    setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f64, Custom);
843
844#if 0
845    // Not sure we want to do this since there are no 256-bit integer
846    // operations in AVX
847
848    // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
849    // This includes 256-bit vectors
850    for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v4i64; ++i) {
851      MVT VT = (MVT::SimpleValueType)i;
852
853      // Do not attempt to custom lower non-power-of-2 vectors
854      if (!isPowerOf2_32(VT.getVectorNumElements()))
855        continue;
856
857      setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
858      setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
859      setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
860    }
861
862    if (Subtarget->is64Bit()) {
863      setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i64, Custom);
864      setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i64, Custom);
865    }
866#endif
867
868#if 0
869    // Not sure we want to do this since there are no 256-bit integer
870    // operations in AVX
871
872    // Promote v32i8, v16i16, v8i32 load, select, and, or, xor to v4i64.
873    // Including 256-bit vectors
874    for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v4i64; i++) {
875      MVT VT = (MVT::SimpleValueType)i;
876
877      if (!VT.is256BitVector()) {
878        continue;
879      }
880      setOperationAction(ISD::AND,    VT, Promote);
881      AddPromotedToType (ISD::AND,    VT, MVT::v4i64);
882      setOperationAction(ISD::OR,     VT, Promote);
883      AddPromotedToType (ISD::OR,     VT, MVT::v4i64);
884      setOperationAction(ISD::XOR,    VT, Promote);
885      AddPromotedToType (ISD::XOR,    VT, MVT::v4i64);
886      setOperationAction(ISD::LOAD,   VT, Promote);
887      AddPromotedToType (ISD::LOAD,   VT, MVT::v4i64);
888      setOperationAction(ISD::SELECT, VT, Promote);
889      AddPromotedToType (ISD::SELECT, VT, MVT::v4i64);
890    }
891
892    setTruncStoreAction(MVT::f64, MVT::f32, Expand);
893#endif
894  }
895
896  // We want to custom lower some of our intrinsics.
897  setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
898
899  // Add/Sub/Mul with overflow operations are custom lowered.
900  setOperationAction(ISD::SADDO, MVT::i32, Custom);
901  setOperationAction(ISD::SADDO, MVT::i64, Custom);
902  setOperationAction(ISD::UADDO, MVT::i32, Custom);
903  setOperationAction(ISD::UADDO, MVT::i64, Custom);
904  setOperationAction(ISD::SSUBO, MVT::i32, Custom);
905  setOperationAction(ISD::SSUBO, MVT::i64, Custom);
906  setOperationAction(ISD::USUBO, MVT::i32, Custom);
907  setOperationAction(ISD::USUBO, MVT::i64, Custom);
908  setOperationAction(ISD::SMULO, MVT::i32, Custom);
909  setOperationAction(ISD::SMULO, MVT::i64, Custom);
910
911  if (!Subtarget->is64Bit()) {
912    // These libcalls are not available in 32-bit.
913    setLibcallName(RTLIB::SHL_I128, 0);
914    setLibcallName(RTLIB::SRL_I128, 0);
915    setLibcallName(RTLIB::SRA_I128, 0);
916  }
917
918  // We have target-specific dag combine patterns for the following nodes:
919  setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
920  setTargetDAGCombine(ISD::BUILD_VECTOR);
921  setTargetDAGCombine(ISD::SELECT);
922  setTargetDAGCombine(ISD::SHL);
923  setTargetDAGCombine(ISD::SRA);
924  setTargetDAGCombine(ISD::SRL);
925  setTargetDAGCombine(ISD::STORE);
926  setTargetDAGCombine(ISD::MEMBARRIER);
927  if (Subtarget->is64Bit())
928    setTargetDAGCombine(ISD::MUL);
929
930  computeRegisterProperties();
931
932  // FIXME: These should be based on subtarget info. Plus, the values should
933  // be smaller when we are in optimizing for size mode.
934  maxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
935  maxStoresPerMemcpy = 16; // For @llvm.memcpy -> sequence of stores
936  maxStoresPerMemmove = 3; // For @llvm.memmove -> sequence of stores
937  allowUnalignedMemoryAccesses = true; // x86 supports it!
938  setPrefLoopAlignment(16);
939  benefitFromCodePlacementOpt = true;
940}
941
942
943MVT X86TargetLowering::getSetCCResultType(MVT VT) const {
944  return MVT::i8;
945}
946
947
948/// getMaxByValAlign - Helper for getByValTypeAlignment to determine
949/// the desired ByVal argument alignment.
950static void getMaxByValAlign(const Type *Ty, unsigned &MaxAlign) {
951  if (MaxAlign == 16)
952    return;
953  if (const VectorType *VTy = dyn_cast<VectorType>(Ty)) {
954    if (VTy->getBitWidth() == 128)
955      MaxAlign = 16;
956  } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
957    unsigned EltAlign = 0;
958    getMaxByValAlign(ATy->getElementType(), EltAlign);
959    if (EltAlign > MaxAlign)
960      MaxAlign = EltAlign;
961  } else if (const StructType *STy = dyn_cast<StructType>(Ty)) {
962    for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
963      unsigned EltAlign = 0;
964      getMaxByValAlign(STy->getElementType(i), EltAlign);
965      if (EltAlign > MaxAlign)
966        MaxAlign = EltAlign;
967      if (MaxAlign == 16)
968        break;
969    }
970  }
971  return;
972}
973
974/// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
975/// function arguments in the caller parameter area. For X86, aggregates
976/// that contain SSE vectors are placed at 16-byte boundaries while the rest
977/// are at 4-byte boundaries.
978unsigned X86TargetLowering::getByValTypeAlignment(const Type *Ty) const {
979  if (Subtarget->is64Bit()) {
980    // Max of 8 and alignment of type.
981    unsigned TyAlign = TD->getABITypeAlignment(Ty);
982    if (TyAlign > 8)
983      return TyAlign;
984    return 8;
985  }
986
987  unsigned Align = 4;
988  if (Subtarget->hasSSE1())
989    getMaxByValAlign(Ty, Align);
990  return Align;
991}
992
993/// getOptimalMemOpType - Returns the target specific optimal type for load
994/// and store operations as a result of memset, memcpy, and memmove
995/// lowering. It returns MVT::iAny if SelectionDAG should be responsible for
996/// determining it.
997MVT
998X86TargetLowering::getOptimalMemOpType(uint64_t Size, unsigned Align,
999                                       bool isSrcConst, bool isSrcStr,
1000                                       SelectionDAG &DAG) const {
1001  // FIXME: This turns off use of xmm stores for memset/memcpy on targets like
1002  // linux.  This is because the stack realignment code can't handle certain
1003  // cases like PR2962.  This should be removed when PR2962 is fixed.
1004  const Function *F = DAG.getMachineFunction().getFunction();
1005  bool NoImplicitFloatOps = F->hasFnAttr(Attribute::NoImplicitFloat);
1006  if (!NoImplicitFloatOps && Subtarget->getStackAlignment() >= 16) {
1007    if ((isSrcConst || isSrcStr) && Subtarget->hasSSE2() && Size >= 16)
1008      return MVT::v4i32;
1009    if ((isSrcConst || isSrcStr) && Subtarget->hasSSE1() && Size >= 16)
1010      return MVT::v4f32;
1011  }
1012  if (Subtarget->is64Bit() && Size >= 8)
1013    return MVT::i64;
1014  return MVT::i32;
1015}
1016
1017/// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
1018/// jumptable.
1019SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1020                                                      SelectionDAG &DAG) const {
1021  if (usesGlobalOffsetTable())
1022    return DAG.getGLOBAL_OFFSET_TABLE(getPointerTy());
1023  if (!Subtarget->isPICStyleRIPRel())
1024    // This doesn't have DebugLoc associated with it, but is not really the
1025    // same as a Register.
1026    return DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc::getUnknownLoc(),
1027                       getPointerTy());
1028  return Table;
1029}
1030
1031/// getFunctionAlignment - Return the Log2 alignment of this function.
1032unsigned X86TargetLowering::getFunctionAlignment(const Function *F) const {
1033  return F->hasFnAttr(Attribute::OptimizeForSize) ? 1 : 4;
1034}
1035
1036//===----------------------------------------------------------------------===//
1037//               Return Value Calling Convention Implementation
1038//===----------------------------------------------------------------------===//
1039
1040#include "X86GenCallingConv.inc"
1041
1042/// LowerRET - Lower an ISD::RET node.
1043SDValue X86TargetLowering::LowerRET(SDValue Op, SelectionDAG &DAG) {
1044  DebugLoc dl = Op.getDebugLoc();
1045  assert((Op.getNumOperands() & 1) == 1 && "ISD::RET should have odd # args");
1046
1047  SmallVector<CCValAssign, 16> RVLocs;
1048  unsigned CC = DAG.getMachineFunction().getFunction()->getCallingConv();
1049  bool isVarArg = DAG.getMachineFunction().getFunction()->isVarArg();
1050  CCState CCInfo(CC, isVarArg, getTargetMachine(), RVLocs);
1051  CCInfo.AnalyzeReturn(Op.getNode(), RetCC_X86);
1052
1053  // If this is the first return lowered for this function, add the regs to the
1054  // liveout set for the function.
1055  if (DAG.getMachineFunction().getRegInfo().liveout_empty()) {
1056    for (unsigned i = 0; i != RVLocs.size(); ++i)
1057      if (RVLocs[i].isRegLoc())
1058        DAG.getMachineFunction().getRegInfo().addLiveOut(RVLocs[i].getLocReg());
1059  }
1060  SDValue Chain = Op.getOperand(0);
1061
1062  // Handle tail call return.
1063  Chain = GetPossiblePreceedingTailCall(Chain, X86ISD::TAILCALL);
1064  if (Chain.getOpcode() == X86ISD::TAILCALL) {
1065    SDValue TailCall = Chain;
1066    SDValue TargetAddress = TailCall.getOperand(1);
1067    SDValue StackAdjustment = TailCall.getOperand(2);
1068    assert(((TargetAddress.getOpcode() == ISD::Register &&
1069               (cast<RegisterSDNode>(TargetAddress)->getReg() == X86::EAX ||
1070                cast<RegisterSDNode>(TargetAddress)->getReg() == X86::R11)) ||
1071              TargetAddress.getOpcode() == ISD::TargetExternalSymbol ||
1072              TargetAddress.getOpcode() == ISD::TargetGlobalAddress) &&
1073             "Expecting an global address, external symbol, or register");
1074    assert(StackAdjustment.getOpcode() == ISD::Constant &&
1075           "Expecting a const value");
1076
1077    SmallVector<SDValue,8> Operands;
1078    Operands.push_back(Chain.getOperand(0));
1079    Operands.push_back(TargetAddress);
1080    Operands.push_back(StackAdjustment);
1081    // Copy registers used by the call. Last operand is a flag so it is not
1082    // copied.
1083    for (unsigned i=3; i < TailCall.getNumOperands()-1; i++) {
1084      Operands.push_back(Chain.getOperand(i));
1085    }
1086    return DAG.getNode(X86ISD::TC_RETURN, dl, MVT::Other, &Operands[0],
1087                       Operands.size());
1088  }
1089
1090  // Regular return.
1091  SDValue Flag;
1092
1093  SmallVector<SDValue, 6> RetOps;
1094  RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1095  // Operand #1 = Bytes To Pop
1096  RetOps.push_back(DAG.getConstant(getBytesToPopOnReturn(), MVT::i16));
1097
1098  // Copy the result values into the output registers.
1099  for (unsigned i = 0; i != RVLocs.size(); ++i) {
1100    CCValAssign &VA = RVLocs[i];
1101    assert(VA.isRegLoc() && "Can only return in registers!");
1102    SDValue ValToCopy = Op.getOperand(i*2+1);
1103
1104    // Returns in ST0/ST1 are handled specially: these are pushed as operands to
1105    // the RET instruction and handled by the FP Stackifier.
1106    if (VA.getLocReg() == X86::ST0 ||
1107        VA.getLocReg() == X86::ST1) {
1108      // If this is a copy from an xmm register to ST(0), use an FPExtend to
1109      // change the value to the FP stack register class.
1110      if (isScalarFPTypeInSSEReg(VA.getValVT()))
1111        ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
1112      RetOps.push_back(ValToCopy);
1113      // Don't emit a copytoreg.
1114      continue;
1115    }
1116
1117    // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
1118    // which is returned in RAX / RDX.
1119    if (Subtarget->is64Bit()) {
1120      MVT ValVT = ValToCopy.getValueType();
1121      if (ValVT.isVector() && ValVT.getSizeInBits() == 64) {
1122        ValToCopy = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i64, ValToCopy);
1123        if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1)
1124          ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, ValToCopy);
1125      }
1126    }
1127
1128    Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
1129    Flag = Chain.getValue(1);
1130  }
1131
1132  // The x86-64 ABI for returning structs by value requires that we copy
1133  // the sret argument into %rax for the return. We saved the argument into
1134  // a virtual register in the entry block, so now we copy the value out
1135  // and into %rax.
1136  if (Subtarget->is64Bit() &&
1137      DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
1138    MachineFunction &MF = DAG.getMachineFunction();
1139    X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1140    unsigned Reg = FuncInfo->getSRetReturnReg();
1141    if (!Reg) {
1142      Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(MVT::i64));
1143      FuncInfo->setSRetReturnReg(Reg);
1144    }
1145    SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
1146
1147    Chain = DAG.getCopyToReg(Chain, dl, X86::RAX, Val, Flag);
1148    Flag = Chain.getValue(1);
1149  }
1150
1151  RetOps[0] = Chain;  // Update chain.
1152
1153  // Add the flag if we have it.
1154  if (Flag.getNode())
1155    RetOps.push_back(Flag);
1156
1157  return DAG.getNode(X86ISD::RET_FLAG, dl,
1158                     MVT::Other, &RetOps[0], RetOps.size());
1159}
1160
1161
1162/// LowerCallResult - Lower the result values of an ISD::CALL into the
1163/// appropriate copies out of appropriate physical registers.  This assumes that
1164/// Chain/InFlag are the input chain/flag to use, and that TheCall is the call
1165/// being lowered.  The returns a SDNode with the same number of values as the
1166/// ISD::CALL.
1167SDNode *X86TargetLowering::
1168LowerCallResult(SDValue Chain, SDValue InFlag, CallSDNode *TheCall,
1169                unsigned CallingConv, SelectionDAG &DAG) {
1170
1171  DebugLoc dl = TheCall->getDebugLoc();
1172  // Assign locations to each value returned by this call.
1173  SmallVector<CCValAssign, 16> RVLocs;
1174  bool isVarArg = TheCall->isVarArg();
1175  bool Is64Bit = Subtarget->is64Bit();
1176  CCState CCInfo(CallingConv, isVarArg, getTargetMachine(), RVLocs);
1177  CCInfo.AnalyzeCallResult(TheCall, RetCC_X86);
1178
1179  SmallVector<SDValue, 8> ResultVals;
1180
1181  // Copy all of the result registers out of their specified physreg.
1182  for (unsigned i = 0; i != RVLocs.size(); ++i) {
1183    CCValAssign &VA = RVLocs[i];
1184    MVT CopyVT = VA.getValVT();
1185
1186    // If this is x86-64, and we disabled SSE, we can't return FP values
1187    if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
1188        ((Is64Bit || TheCall->isInreg()) && !Subtarget->hasSSE1())) {
1189      cerr << "SSE register return with SSE disabled\n";
1190      exit(1);
1191    }
1192
1193    // If this is a call to a function that returns an fp value on the floating
1194    // point stack, but where we prefer to use the value in xmm registers, copy
1195    // it out as F80 and use a truncate to move it from fp stack reg to xmm reg.
1196    if ((VA.getLocReg() == X86::ST0 ||
1197         VA.getLocReg() == X86::ST1) &&
1198        isScalarFPTypeInSSEReg(VA.getValVT())) {
1199      CopyVT = MVT::f80;
1200    }
1201
1202    SDValue Val;
1203    if (Is64Bit && CopyVT.isVector() && CopyVT.getSizeInBits() == 64) {
1204      // For x86-64, MMX values are returned in XMM0 / XMM1 except for v1i64.
1205      if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1206        Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1207                                   MVT::v2i64, InFlag).getValue(1);
1208        Val = Chain.getValue(0);
1209        Val = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64,
1210                          Val, DAG.getConstant(0, MVT::i64));
1211      } else {
1212        Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1213                                   MVT::i64, InFlag).getValue(1);
1214        Val = Chain.getValue(0);
1215      }
1216      Val = DAG.getNode(ISD::BIT_CONVERT, dl, CopyVT, Val);
1217    } else {
1218      Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1219                                 CopyVT, InFlag).getValue(1);
1220      Val = Chain.getValue(0);
1221    }
1222    InFlag = Chain.getValue(2);
1223
1224    if (CopyVT != VA.getValVT()) {
1225      // Round the F80 the right size, which also moves to the appropriate xmm
1226      // register.
1227      Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
1228                        // This truncation won't change the value.
1229                        DAG.getIntPtrConstant(1));
1230    }
1231
1232    ResultVals.push_back(Val);
1233  }
1234
1235  // Merge everything together with a MERGE_VALUES node.
1236  ResultVals.push_back(Chain);
1237  return DAG.getNode(ISD::MERGE_VALUES, dl, TheCall->getVTList(),
1238                     &ResultVals[0], ResultVals.size()).getNode();
1239}
1240
1241
1242//===----------------------------------------------------------------------===//
1243//                C & StdCall & Fast Calling Convention implementation
1244//===----------------------------------------------------------------------===//
1245//  StdCall calling convention seems to be standard for many Windows' API
1246//  routines and around. It differs from C calling convention just a little:
1247//  callee should clean up the stack, not caller. Symbols should be also
1248//  decorated in some fancy way :) It doesn't support any vector arguments.
1249//  For info on fast calling convention see Fast Calling Convention (tail call)
1250//  implementation LowerX86_32FastCCCallTo.
1251
1252/// CallIsStructReturn - Determines whether a CALL node uses struct return
1253/// semantics.
1254static bool CallIsStructReturn(CallSDNode *TheCall) {
1255  unsigned NumOps = TheCall->getNumArgs();
1256  if (!NumOps)
1257    return false;
1258
1259  return TheCall->getArgFlags(0).isSRet();
1260}
1261
1262/// ArgsAreStructReturn - Determines whether a FORMAL_ARGUMENTS node uses struct
1263/// return semantics.
1264static bool ArgsAreStructReturn(SDValue Op) {
1265  unsigned NumArgs = Op.getNode()->getNumValues() - 1;
1266  if (!NumArgs)
1267    return false;
1268
1269  return cast<ARG_FLAGSSDNode>(Op.getOperand(3))->getArgFlags().isSRet();
1270}
1271
1272/// IsCalleePop - Determines whether a CALL or FORMAL_ARGUMENTS node requires
1273/// the callee to pop its own arguments. Callee pop is necessary to support tail
1274/// calls.
1275bool X86TargetLowering::IsCalleePop(bool IsVarArg, unsigned CallingConv) {
1276  if (IsVarArg)
1277    return false;
1278
1279  switch (CallingConv) {
1280  default:
1281    return false;
1282  case CallingConv::X86_StdCall:
1283    return !Subtarget->is64Bit();
1284  case CallingConv::X86_FastCall:
1285    return !Subtarget->is64Bit();
1286  case CallingConv::Fast:
1287    return PerformTailCallOpt;
1288  }
1289}
1290
1291/// CCAssignFnForNode - Selects the correct CCAssignFn for a the
1292/// given CallingConvention value.
1293CCAssignFn *X86TargetLowering::CCAssignFnForNode(unsigned CC) const {
1294  if (Subtarget->is64Bit()) {
1295    if (Subtarget->isTargetWin64())
1296      return CC_X86_Win64_C;
1297    else
1298      return CC_X86_64_C;
1299  }
1300
1301  if (CC == CallingConv::X86_FastCall)
1302    return CC_X86_32_FastCall;
1303  else if (CC == CallingConv::Fast)
1304    return CC_X86_32_FastCC;
1305  else
1306    return CC_X86_32_C;
1307}
1308
1309/// NameDecorationForFORMAL_ARGUMENTS - Selects the appropriate decoration to
1310/// apply to a MachineFunction containing a given FORMAL_ARGUMENTS node.
1311NameDecorationStyle
1312X86TargetLowering::NameDecorationForFORMAL_ARGUMENTS(SDValue Op) {
1313  unsigned CC = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
1314  if (CC == CallingConv::X86_FastCall)
1315    return FastCall;
1316  else if (CC == CallingConv::X86_StdCall)
1317    return StdCall;
1318  return None;
1319}
1320
1321
1322/// CallRequiresGOTInRegister - Check whether the call requires the GOT pointer
1323/// in a register before calling.
1324bool X86TargetLowering::CallRequiresGOTPtrInReg(bool Is64Bit, bool IsTailCall) {
1325  return !IsTailCall && !Is64Bit &&
1326    getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1327    Subtarget->isPICStyleGOT();
1328}
1329
1330/// CallRequiresFnAddressInReg - Check whether the call requires the function
1331/// address to be loaded in a register.
1332bool
1333X86TargetLowering::CallRequiresFnAddressInReg(bool Is64Bit, bool IsTailCall) {
1334  return !Is64Bit && IsTailCall &&
1335    getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1336    Subtarget->isPICStyleGOT();
1337}
1338
1339/// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
1340/// by "Src" to address "Dst" with size and alignment information specified by
1341/// the specific parameter attribute. The copy will be passed as a byval
1342/// function parameter.
1343static SDValue
1344CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
1345                          ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
1346                          DebugLoc dl) {
1347  SDValue SizeNode     = DAG.getConstant(Flags.getByValSize(), MVT::i32);
1348  return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
1349                       /*AlwaysInline=*/true, NULL, 0, NULL, 0);
1350}
1351
1352SDValue X86TargetLowering::LowerMemArgument(SDValue Op, SelectionDAG &DAG,
1353                                              const CCValAssign &VA,
1354                                              MachineFrameInfo *MFI,
1355                                              unsigned CC,
1356                                              SDValue Root, unsigned i) {
1357  // Create the nodes corresponding to a load from this parameter slot.
1358  ISD::ArgFlagsTy Flags =
1359    cast<ARG_FLAGSSDNode>(Op.getOperand(3 + i))->getArgFlags();
1360  bool AlwaysUseMutable = (CC==CallingConv::Fast) && PerformTailCallOpt;
1361  bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
1362
1363  // FIXME: For now, all byval parameter objects are marked mutable. This can be
1364  // changed with more analysis.
1365  // In case of tail call optimization mark all arguments mutable. Since they
1366  // could be overwritten by lowering of arguments in case of a tail call.
1367  int FI = MFI->CreateFixedObject(VA.getValVT().getSizeInBits()/8,
1368                                  VA.getLocMemOffset(), isImmutable);
1369  SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
1370  if (Flags.isByVal())
1371    return FIN;
1372  return DAG.getLoad(VA.getValVT(), Op.getDebugLoc(), Root, FIN,
1373                     PseudoSourceValue::getFixedStack(FI), 0);
1374}
1375
1376SDValue
1377X86TargetLowering::LowerFORMAL_ARGUMENTS(SDValue Op, SelectionDAG &DAG) {
1378  MachineFunction &MF = DAG.getMachineFunction();
1379  X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1380  DebugLoc dl = Op.getDebugLoc();
1381
1382  const Function* Fn = MF.getFunction();
1383  if (Fn->hasExternalLinkage() &&
1384      Subtarget->isTargetCygMing() &&
1385      Fn->getName() == "main")
1386    FuncInfo->setForceFramePointer(true);
1387
1388  // Decorate the function name.
1389  FuncInfo->setDecorationStyle(NameDecorationForFORMAL_ARGUMENTS(Op));
1390
1391  MachineFrameInfo *MFI = MF.getFrameInfo();
1392  SDValue Root = Op.getOperand(0);
1393  bool isVarArg = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue() != 0;
1394  unsigned CC = MF.getFunction()->getCallingConv();
1395  bool Is64Bit = Subtarget->is64Bit();
1396  bool IsWin64 = Subtarget->isTargetWin64();
1397
1398  assert(!(isVarArg && CC == CallingConv::Fast) &&
1399         "Var args not supported with calling convention fastcc");
1400
1401  // Assign locations to all of the incoming arguments.
1402  SmallVector<CCValAssign, 16> ArgLocs;
1403  CCState CCInfo(CC, isVarArg, getTargetMachine(), ArgLocs);
1404  CCInfo.AnalyzeFormalArguments(Op.getNode(), CCAssignFnForNode(CC));
1405
1406  SmallVector<SDValue, 8> ArgValues;
1407  unsigned LastVal = ~0U;
1408  for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1409    CCValAssign &VA = ArgLocs[i];
1410    // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
1411    // places.
1412    assert(VA.getValNo() != LastVal &&
1413           "Don't support value assigned to multiple locs yet");
1414    LastVal = VA.getValNo();
1415
1416    if (VA.isRegLoc()) {
1417      MVT RegVT = VA.getLocVT();
1418      TargetRegisterClass *RC = NULL;
1419      if (RegVT == MVT::i32)
1420        RC = X86::GR32RegisterClass;
1421      else if (Is64Bit && RegVT == MVT::i64)
1422        RC = X86::GR64RegisterClass;
1423      else if (RegVT == MVT::f32)
1424        RC = X86::FR32RegisterClass;
1425      else if (RegVT == MVT::f64)
1426        RC = X86::FR64RegisterClass;
1427      else if (RegVT.isVector() && RegVT.getSizeInBits() == 128)
1428        RC = X86::VR128RegisterClass;
1429      else if (RegVT.isVector()) {
1430        assert(RegVT.getSizeInBits() == 64);
1431        if (!Is64Bit)
1432          RC = X86::VR64RegisterClass;     // MMX values are passed in MMXs.
1433        else {
1434          // Darwin calling convention passes MMX values in either GPRs or
1435          // XMMs in x86-64. Other targets pass them in memory.
1436          if (RegVT != MVT::v1i64 && Subtarget->hasSSE2()) {
1437            RC = X86::VR128RegisterClass;  // MMX values are passed in XMMs.
1438            RegVT = MVT::v2i64;
1439          } else {
1440            RC = X86::GR64RegisterClass;   // v1i64 values are passed in GPRs.
1441            RegVT = MVT::i64;
1442          }
1443        }
1444      } else {
1445        assert(0 && "Unknown argument type!");
1446      }
1447
1448      unsigned Reg = DAG.getMachineFunction().addLiveIn(VA.getLocReg(), RC);
1449      SDValue ArgValue = DAG.getCopyFromReg(Root, dl, Reg, RegVT);
1450
1451      // If this is an 8 or 16-bit value, it is really passed promoted to 32
1452      // bits.  Insert an assert[sz]ext to capture this, then truncate to the
1453      // right size.
1454      if (VA.getLocInfo() == CCValAssign::SExt)
1455        ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
1456                               DAG.getValueType(VA.getValVT()));
1457      else if (VA.getLocInfo() == CCValAssign::ZExt)
1458        ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
1459                               DAG.getValueType(VA.getValVT()));
1460
1461      if (VA.getLocInfo() != CCValAssign::Full)
1462        ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
1463
1464      // Handle MMX values passed in GPRs.
1465      if (Is64Bit && RegVT != VA.getLocVT()) {
1466        if (RegVT.getSizeInBits() == 64 && RC == X86::GR64RegisterClass)
1467          ArgValue = DAG.getNode(ISD::BIT_CONVERT, dl, VA.getLocVT(), ArgValue);
1468        else if (RC == X86::VR128RegisterClass) {
1469          ArgValue = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64,
1470                                 ArgValue, DAG.getConstant(0, MVT::i64));
1471          ArgValue = DAG.getNode(ISD::BIT_CONVERT, dl, VA.getLocVT(), ArgValue);
1472        }
1473      }
1474
1475      ArgValues.push_back(ArgValue);
1476    } else {
1477      assert(VA.isMemLoc());
1478      ArgValues.push_back(LowerMemArgument(Op, DAG, VA, MFI, CC, Root, i));
1479    }
1480  }
1481
1482  // The x86-64 ABI for returning structs by value requires that we copy
1483  // the sret argument into %rax for the return. Save the argument into
1484  // a virtual register so that we can access it from the return points.
1485  if (Is64Bit && DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
1486    MachineFunction &MF = DAG.getMachineFunction();
1487    X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1488    unsigned Reg = FuncInfo->getSRetReturnReg();
1489    if (!Reg) {
1490      Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(MVT::i64));
1491      FuncInfo->setSRetReturnReg(Reg);
1492    }
1493    SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, ArgValues[0]);
1494    Root = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Root);
1495  }
1496
1497  unsigned StackSize = CCInfo.getNextStackOffset();
1498  // align stack specially for tail calls
1499  if (PerformTailCallOpt && CC == CallingConv::Fast)
1500    StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
1501
1502  // If the function takes variable number of arguments, make a frame index for
1503  // the start of the first vararg value... for expansion of llvm.va_start.
1504  if (isVarArg) {
1505    if (Is64Bit || CC != CallingConv::X86_FastCall) {
1506      VarArgsFrameIndex = MFI->CreateFixedObject(1, StackSize);
1507    }
1508    if (Is64Bit) {
1509      unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
1510
1511      // FIXME: We should really autogenerate these arrays
1512      static const unsigned GPR64ArgRegsWin64[] = {
1513        X86::RCX, X86::RDX, X86::R8,  X86::R9
1514      };
1515      static const unsigned XMMArgRegsWin64[] = {
1516        X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3
1517      };
1518      static const unsigned GPR64ArgRegs64Bit[] = {
1519        X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
1520      };
1521      static const unsigned XMMArgRegs64Bit[] = {
1522        X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
1523        X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
1524      };
1525      const unsigned *GPR64ArgRegs, *XMMArgRegs;
1526
1527      if (IsWin64) {
1528        TotalNumIntRegs = 4; TotalNumXMMRegs = 4;
1529        GPR64ArgRegs = GPR64ArgRegsWin64;
1530        XMMArgRegs = XMMArgRegsWin64;
1531      } else {
1532        TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
1533        GPR64ArgRegs = GPR64ArgRegs64Bit;
1534        XMMArgRegs = XMMArgRegs64Bit;
1535      }
1536      unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
1537                                                       TotalNumIntRegs);
1538      unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs,
1539                                                       TotalNumXMMRegs);
1540
1541      bool NoImplicitFloatOps = Fn->hasFnAttr(Attribute::NoImplicitFloat);
1542      assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
1543             "SSE register cannot be used when SSE is disabled!");
1544      assert(!(NumXMMRegs && UseSoftFloat && NoImplicitFloatOps) &&
1545             "SSE register cannot be used when SSE is disabled!");
1546      if (UseSoftFloat || NoImplicitFloatOps || !Subtarget->hasSSE1())
1547        // Kernel mode asks for SSE to be disabled, so don't push them
1548        // on the stack.
1549        TotalNumXMMRegs = 0;
1550
1551      // For X86-64, if there are vararg parameters that are passed via
1552      // registers, then we must store them to their spots on the stack so they
1553      // may be loaded by deferencing the result of va_next.
1554      VarArgsGPOffset = NumIntRegs * 8;
1555      VarArgsFPOffset = TotalNumIntRegs * 8 + NumXMMRegs * 16;
1556      RegSaveFrameIndex = MFI->CreateStackObject(TotalNumIntRegs * 8 +
1557                                                 TotalNumXMMRegs * 16, 16);
1558
1559      // Store the integer parameter registers.
1560      SmallVector<SDValue, 8> MemOps;
1561      SDValue RSFIN = DAG.getFrameIndex(RegSaveFrameIndex, getPointerTy());
1562      SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
1563                                  DAG.getIntPtrConstant(VarArgsGPOffset));
1564      for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
1565        unsigned VReg = MF.addLiveIn(GPR64ArgRegs[NumIntRegs],
1566                                     X86::GR64RegisterClass);
1567        SDValue Val = DAG.getCopyFromReg(Root, dl, VReg, MVT::i64);
1568        SDValue Store =
1569          DAG.getStore(Val.getValue(1), dl, Val, FIN,
1570                       PseudoSourceValue::getFixedStack(RegSaveFrameIndex), 0);
1571        MemOps.push_back(Store);
1572        FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), FIN,
1573                          DAG.getIntPtrConstant(8));
1574      }
1575
1576      // Now store the XMM (fp + vector) parameter registers.
1577      FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
1578                        DAG.getIntPtrConstant(VarArgsFPOffset));
1579      for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
1580        unsigned VReg = MF.addLiveIn(XMMArgRegs[NumXMMRegs],
1581                                     X86::VR128RegisterClass);
1582        SDValue Val = DAG.getCopyFromReg(Root, dl, VReg, MVT::v4f32);
1583        SDValue Store =
1584          DAG.getStore(Val.getValue(1), dl, Val, FIN,
1585                       PseudoSourceValue::getFixedStack(RegSaveFrameIndex), 0);
1586        MemOps.push_back(Store);
1587        FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), FIN,
1588                          DAG.getIntPtrConstant(16));
1589      }
1590      if (!MemOps.empty())
1591          Root = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1592                             &MemOps[0], MemOps.size());
1593    }
1594  }
1595
1596  ArgValues.push_back(Root);
1597
1598  // Some CCs need callee pop.
1599  if (IsCalleePop(isVarArg, CC)) {
1600    BytesToPopOnReturn  = StackSize; // Callee pops everything.
1601    BytesCallerReserves = 0;
1602  } else {
1603    BytesToPopOnReturn  = 0; // Callee pops nothing.
1604    // If this is an sret function, the return should pop the hidden pointer.
1605    if (!Is64Bit && CC != CallingConv::Fast && ArgsAreStructReturn(Op))
1606      BytesToPopOnReturn = 4;
1607    BytesCallerReserves = StackSize;
1608  }
1609
1610  if (!Is64Bit) {
1611    RegSaveFrameIndex = 0xAAAAAAA;   // RegSaveFrameIndex is X86-64 only.
1612    if (CC == CallingConv::X86_FastCall)
1613      VarArgsFrameIndex = 0xAAAAAAA;   // fastcc functions can't have varargs.
1614  }
1615
1616  FuncInfo->setBytesToPopOnReturn(BytesToPopOnReturn);
1617
1618  // Return the new list of results.
1619  return DAG.getNode(ISD::MERGE_VALUES, dl, Op.getNode()->getVTList(),
1620                     &ArgValues[0], ArgValues.size()).getValue(Op.getResNo());
1621}
1622
1623SDValue
1624X86TargetLowering::LowerMemOpCallTo(CallSDNode *TheCall, SelectionDAG &DAG,
1625                                    const SDValue &StackPtr,
1626                                    const CCValAssign &VA,
1627                                    SDValue Chain,
1628                                    SDValue Arg, ISD::ArgFlagsTy Flags) {
1629  DebugLoc dl = TheCall->getDebugLoc();
1630  unsigned LocMemOffset = VA.getLocMemOffset();
1631  SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
1632  PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
1633  if (Flags.isByVal()) {
1634    return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
1635  }
1636  return DAG.getStore(Chain, dl, Arg, PtrOff,
1637                      PseudoSourceValue::getStack(), LocMemOffset);
1638}
1639
1640/// EmitTailCallLoadRetAddr - Emit a load of return address if tail call
1641/// optimization is performed and it is required.
1642SDValue
1643X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
1644                                           SDValue &OutRetAddr,
1645                                           SDValue Chain,
1646                                           bool IsTailCall,
1647                                           bool Is64Bit,
1648                                           int FPDiff,
1649                                           DebugLoc dl) {
1650  if (!IsTailCall || FPDiff==0) return Chain;
1651
1652  // Adjust the Return address stack slot.
1653  MVT VT = getPointerTy();
1654  OutRetAddr = getReturnAddressFrameIndex(DAG);
1655
1656  // Load the "old" Return address.
1657  OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, NULL, 0);
1658  return SDValue(OutRetAddr.getNode(), 1);
1659}
1660
1661/// EmitTailCallStoreRetAddr - Emit a store of the return adress if tail call
1662/// optimization is performed and it is required (FPDiff!=0).
1663static SDValue
1664EmitTailCallStoreRetAddr(SelectionDAG & DAG, MachineFunction &MF,
1665                         SDValue Chain, SDValue RetAddrFrIdx,
1666                         bool Is64Bit, int FPDiff, DebugLoc dl) {
1667  // Store the return address to the appropriate stack slot.
1668  if (!FPDiff) return Chain;
1669  // Calculate the new stack slot for the return address.
1670  int SlotSize = Is64Bit ? 8 : 4;
1671  int NewReturnAddrFI =
1672    MF.getFrameInfo()->CreateFixedObject(SlotSize, FPDiff-SlotSize);
1673  MVT VT = Is64Bit ? MVT::i64 : MVT::i32;
1674  SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, VT);
1675  Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
1676                       PseudoSourceValue::getFixedStack(NewReturnAddrFI), 0);
1677  return Chain;
1678}
1679
1680SDValue X86TargetLowering::LowerCALL(SDValue Op, SelectionDAG &DAG) {
1681  MachineFunction &MF = DAG.getMachineFunction();
1682  CallSDNode *TheCall = cast<CallSDNode>(Op.getNode());
1683  SDValue Chain       = TheCall->getChain();
1684  unsigned CC         = TheCall->getCallingConv();
1685  bool isVarArg       = TheCall->isVarArg();
1686  bool IsTailCall     = TheCall->isTailCall() &&
1687                        CC == CallingConv::Fast && PerformTailCallOpt;
1688  SDValue Callee      = TheCall->getCallee();
1689  bool Is64Bit        = Subtarget->is64Bit();
1690  bool IsStructRet    = CallIsStructReturn(TheCall);
1691  DebugLoc dl         = TheCall->getDebugLoc();
1692
1693  assert(!(isVarArg && CC == CallingConv::Fast) &&
1694         "Var args not supported with calling convention fastcc");
1695
1696  // Analyze operands of the call, assigning locations to each operand.
1697  SmallVector<CCValAssign, 16> ArgLocs;
1698  CCState CCInfo(CC, isVarArg, getTargetMachine(), ArgLocs);
1699  CCInfo.AnalyzeCallOperands(TheCall, CCAssignFnForNode(CC));
1700
1701  // Get a count of how many bytes are to be pushed on the stack.
1702  unsigned NumBytes = CCInfo.getNextStackOffset();
1703  if (PerformTailCallOpt && CC == CallingConv::Fast)
1704    NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
1705
1706  int FPDiff = 0;
1707  if (IsTailCall) {
1708    // Lower arguments at fp - stackoffset + fpdiff.
1709    unsigned NumBytesCallerPushed =
1710      MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn();
1711    FPDiff = NumBytesCallerPushed - NumBytes;
1712
1713    // Set the delta of movement of the returnaddr stackslot.
1714    // But only set if delta is greater than previous delta.
1715    if (FPDiff < (MF.getInfo<X86MachineFunctionInfo>()->getTCReturnAddrDelta()))
1716      MF.getInfo<X86MachineFunctionInfo>()->setTCReturnAddrDelta(FPDiff);
1717  }
1718
1719  Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true));
1720
1721  SDValue RetAddrFrIdx;
1722  // Load return adress for tail calls.
1723  Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, IsTailCall, Is64Bit,
1724                                  FPDiff, dl);
1725
1726  SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
1727  SmallVector<SDValue, 8> MemOpChains;
1728  SDValue StackPtr;
1729
1730  // Walk the register/memloc assignments, inserting copies/loads.  In the case
1731  // of tail call optimization arguments are handle later.
1732  for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1733    CCValAssign &VA = ArgLocs[i];
1734    SDValue Arg = TheCall->getArg(i);
1735    ISD::ArgFlagsTy Flags = TheCall->getArgFlags(i);
1736    bool isByVal = Flags.isByVal();
1737
1738    // Promote the value if needed.
1739    switch (VA.getLocInfo()) {
1740    default: assert(0 && "Unknown loc info!");
1741    case CCValAssign::Full: break;
1742    case CCValAssign::SExt:
1743      Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
1744      break;
1745    case CCValAssign::ZExt:
1746      Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
1747      break;
1748    case CCValAssign::AExt:
1749      Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
1750      break;
1751    }
1752
1753    if (VA.isRegLoc()) {
1754      if (Is64Bit) {
1755        MVT RegVT = VA.getLocVT();
1756        if (RegVT.isVector() && RegVT.getSizeInBits() == 64)
1757          switch (VA.getLocReg()) {
1758          default:
1759            break;
1760          case X86::RDI: case X86::RSI: case X86::RDX: case X86::RCX:
1761          case X86::R8: {
1762            // Special case: passing MMX values in GPR registers.
1763            Arg = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i64, Arg);
1764            break;
1765          }
1766          case X86::XMM0: case X86::XMM1: case X86::XMM2: case X86::XMM3:
1767          case X86::XMM4: case X86::XMM5: case X86::XMM6: case X86::XMM7: {
1768            // Special case: passing MMX values in XMM registers.
1769            Arg = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i64, Arg);
1770            Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
1771            Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
1772            break;
1773          }
1774          }
1775      }
1776      RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1777    } else {
1778      if (!IsTailCall || (IsTailCall && isByVal)) {
1779        assert(VA.isMemLoc());
1780        if (StackPtr.getNode() == 0)
1781          StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr, getPointerTy());
1782
1783        MemOpChains.push_back(LowerMemOpCallTo(TheCall, DAG, StackPtr, VA,
1784                                               Chain, Arg, Flags));
1785      }
1786    }
1787  }
1788
1789  if (!MemOpChains.empty())
1790    Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1791                        &MemOpChains[0], MemOpChains.size());
1792
1793  // Build a sequence of copy-to-reg nodes chained together with token chain
1794  // and flag operands which copy the outgoing args into registers.
1795  SDValue InFlag;
1796  // Tail call byval lowering might overwrite argument registers so in case of
1797  // tail call optimization the copies to registers are lowered later.
1798  if (!IsTailCall)
1799    for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1800      Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1801                               RegsToPass[i].second, InFlag);
1802      InFlag = Chain.getValue(1);
1803    }
1804
1805  // ELF / PIC requires GOT in the EBX register before function calls via PLT
1806  // GOT pointer.
1807  if (CallRequiresGOTPtrInReg(Is64Bit, IsTailCall)) {
1808    Chain = DAG.getCopyToReg(Chain, dl, X86::EBX,
1809                             DAG.getNode(X86ISD::GlobalBaseReg,
1810                                         DebugLoc::getUnknownLoc(),
1811                                         getPointerTy()),
1812                             InFlag);
1813    InFlag = Chain.getValue(1);
1814  }
1815  // If we are tail calling and generating PIC/GOT style code load the address
1816  // of the callee into ecx. The value in ecx is used as target of the tail
1817  // jump. This is done to circumvent the ebx/callee-saved problem for tail
1818  // calls on PIC/GOT architectures. Normally we would just put the address of
1819  // GOT into ebx and then call target@PLT. But for tail callss ebx would be
1820  // restored (since ebx is callee saved) before jumping to the target@PLT.
1821  if (CallRequiresFnAddressInReg(Is64Bit, IsTailCall)) {
1822    // Note: The actual moving to ecx is done further down.
1823    GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
1824    if (G && !G->getGlobal()->hasHiddenVisibility() &&
1825        !G->getGlobal()->hasProtectedVisibility())
1826      Callee =  LowerGlobalAddress(Callee, DAG);
1827    else if (isa<ExternalSymbolSDNode>(Callee))
1828      Callee = LowerExternalSymbol(Callee,DAG);
1829  }
1830
1831  if (Is64Bit && isVarArg) {
1832    // From AMD64 ABI document:
1833    // For calls that may call functions that use varargs or stdargs
1834    // (prototype-less calls or calls to functions containing ellipsis (...) in
1835    // the declaration) %al is used as hidden argument to specify the number
1836    // of SSE registers used. The contents of %al do not need to match exactly
1837    // the number of registers, but must be an ubound on the number of SSE
1838    // registers used and is in the range 0 - 8 inclusive.
1839
1840    // FIXME: Verify this on Win64
1841    // Count the number of XMM registers allocated.
1842    static const unsigned XMMArgRegs[] = {
1843      X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
1844      X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
1845    };
1846    unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
1847    assert((Subtarget->hasSSE1() || !NumXMMRegs)
1848           && "SSE registers cannot be used when SSE is disabled");
1849
1850    Chain = DAG.getCopyToReg(Chain, dl, X86::AL,
1851                             DAG.getConstant(NumXMMRegs, MVT::i8), InFlag);
1852    InFlag = Chain.getValue(1);
1853  }
1854
1855
1856  // For tail calls lower the arguments to the 'real' stack slot.
1857  if (IsTailCall) {
1858    SmallVector<SDValue, 8> MemOpChains2;
1859    SDValue FIN;
1860    int FI = 0;
1861    // Do not flag preceeding copytoreg stuff together with the following stuff.
1862    InFlag = SDValue();
1863    for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1864      CCValAssign &VA = ArgLocs[i];
1865      if (!VA.isRegLoc()) {
1866        assert(VA.isMemLoc());
1867        SDValue Arg = TheCall->getArg(i);
1868        ISD::ArgFlagsTy Flags = TheCall->getArgFlags(i);
1869        // Create frame index.
1870        int32_t Offset = VA.getLocMemOffset()+FPDiff;
1871        uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
1872        FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset);
1873        FIN = DAG.getFrameIndex(FI, getPointerTy());
1874
1875        if (Flags.isByVal()) {
1876          // Copy relative to framepointer.
1877          SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
1878          if (StackPtr.getNode() == 0)
1879            StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr,
1880                                          getPointerTy());
1881          Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
1882
1883          MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN, Chain,
1884                                                           Flags, DAG, dl));
1885        } else {
1886          // Store relative to framepointer.
1887          MemOpChains2.push_back(
1888            DAG.getStore(Chain, dl, Arg, FIN,
1889                         PseudoSourceValue::getFixedStack(FI), 0));
1890        }
1891      }
1892    }
1893
1894    if (!MemOpChains2.empty())
1895      Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1896                          &MemOpChains2[0], MemOpChains2.size());
1897
1898    // Copy arguments to their registers.
1899    for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1900      Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1901                               RegsToPass[i].second, InFlag);
1902      InFlag = Chain.getValue(1);
1903    }
1904    InFlag =SDValue();
1905
1906    // Store the return address to the appropriate stack slot.
1907    Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx, Is64Bit,
1908                                     FPDiff, dl);
1909  }
1910
1911  // If the callee is a GlobalAddress node (quite common, every direct call is)
1912  // turn it into a TargetGlobalAddress node so that legalize doesn't hack it.
1913  if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1914    // We should use extra load for direct calls to dllimported functions in
1915    // non-JIT mode.
1916    if (!Subtarget->GVRequiresExtraLoad(G->getGlobal(),
1917                                        getTargetMachine(), true))
1918      Callee = DAG.getTargetGlobalAddress(G->getGlobal(), getPointerTy(),
1919                                          G->getOffset());
1920  } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
1921    Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy());
1922  } else if (IsTailCall) {
1923    unsigned Opc = Is64Bit ? X86::R11 : X86::EAX;
1924
1925    Chain = DAG.getCopyToReg(Chain,  dl,
1926                             DAG.getRegister(Opc, getPointerTy()),
1927                             Callee,InFlag);
1928    Callee = DAG.getRegister(Opc, getPointerTy());
1929    // Add register as live out.
1930    DAG.getMachineFunction().getRegInfo().addLiveOut(Opc);
1931  }
1932
1933  // Returns a chain & a flag for retval copy to use.
1934  SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
1935  SmallVector<SDValue, 8> Ops;
1936
1937  if (IsTailCall) {
1938    Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
1939                           DAG.getIntPtrConstant(0, true), InFlag);
1940    InFlag = Chain.getValue(1);
1941
1942    // Returns a chain & a flag for retval copy to use.
1943    NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
1944    Ops.clear();
1945  }
1946
1947  Ops.push_back(Chain);
1948  Ops.push_back(Callee);
1949
1950  if (IsTailCall)
1951    Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
1952
1953  // Add argument registers to the end of the list so that they are known live
1954  // into the call.
1955  for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
1956    Ops.push_back(DAG.getRegister(RegsToPass[i].first,
1957                                  RegsToPass[i].second.getValueType()));
1958
1959  // Add an implicit use GOT pointer in EBX.
1960  if (!IsTailCall && !Is64Bit &&
1961      getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1962      Subtarget->isPICStyleGOT())
1963    Ops.push_back(DAG.getRegister(X86::EBX, getPointerTy()));
1964
1965  // Add an implicit use of AL for x86 vararg functions.
1966  if (Is64Bit && isVarArg)
1967    Ops.push_back(DAG.getRegister(X86::AL, MVT::i8));
1968
1969  if (InFlag.getNode())
1970    Ops.push_back(InFlag);
1971
1972  if (IsTailCall) {
1973    assert(InFlag.getNode() &&
1974           "Flag must be set. Depend on flag being set in LowerRET");
1975    Chain = DAG.getNode(X86ISD::TAILCALL, dl,
1976                        TheCall->getVTList(), &Ops[0], Ops.size());
1977
1978    return SDValue(Chain.getNode(), Op.getResNo());
1979  }
1980
1981  Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, &Ops[0], Ops.size());
1982  InFlag = Chain.getValue(1);
1983
1984  // Create the CALLSEQ_END node.
1985  unsigned NumBytesForCalleeToPush;
1986  if (IsCalleePop(isVarArg, CC))
1987    NumBytesForCalleeToPush = NumBytes;    // Callee pops everything
1988  else if (!Is64Bit && CC != CallingConv::Fast && IsStructRet)
1989    // If this is is a call to a struct-return function, the callee
1990    // pops the hidden struct pointer, so we have to push it back.
1991    // This is common for Darwin/X86, Linux & Mingw32 targets.
1992    NumBytesForCalleeToPush = 4;
1993  else
1994    NumBytesForCalleeToPush = 0;  // Callee pops nothing.
1995
1996  // Returns a flag for retval copy to use.
1997  Chain = DAG.getCALLSEQ_END(Chain,
1998                             DAG.getIntPtrConstant(NumBytes, true),
1999                             DAG.getIntPtrConstant(NumBytesForCalleeToPush,
2000                                                   true),
2001                             InFlag);
2002  InFlag = Chain.getValue(1);
2003
2004  // Handle result values, copying them out of physregs into vregs that we
2005  // return.
2006  return SDValue(LowerCallResult(Chain, InFlag, TheCall, CC, DAG),
2007                 Op.getResNo());
2008}
2009
2010
2011//===----------------------------------------------------------------------===//
2012//                Fast Calling Convention (tail call) implementation
2013//===----------------------------------------------------------------------===//
2014
2015//  Like std call, callee cleans arguments, convention except that ECX is
2016//  reserved for storing the tail called function address. Only 2 registers are
2017//  free for argument passing (inreg). Tail call optimization is performed
2018//  provided:
2019//                * tailcallopt is enabled
2020//                * caller/callee are fastcc
2021//  On X86_64 architecture with GOT-style position independent code only local
2022//  (within module) calls are supported at the moment.
2023//  To keep the stack aligned according to platform abi the function
2024//  GetAlignedArgumentStackSize ensures that argument delta is always multiples
2025//  of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
2026//  If a tail called function callee has more arguments than the caller the
2027//  caller needs to make sure that there is room to move the RETADDR to. This is
2028//  achieved by reserving an area the size of the argument delta right after the
2029//  original REtADDR, but before the saved framepointer or the spilled registers
2030//  e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
2031//  stack layout:
2032//    arg1
2033//    arg2
2034//    RETADDR
2035//    [ new RETADDR
2036//      move area ]
2037//    (possible EBP)
2038//    ESI
2039//    EDI
2040//    local1 ..
2041
2042/// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
2043/// for a 16 byte align requirement.
2044unsigned X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
2045                                                        SelectionDAG& DAG) {
2046  MachineFunction &MF = DAG.getMachineFunction();
2047  const TargetMachine &TM = MF.getTarget();
2048  const TargetFrameInfo &TFI = *TM.getFrameInfo();
2049  unsigned StackAlignment = TFI.getStackAlignment();
2050  uint64_t AlignMask = StackAlignment - 1;
2051  int64_t Offset = StackSize;
2052  uint64_t SlotSize = TD->getPointerSize();
2053  if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
2054    // Number smaller than 12 so just add the difference.
2055    Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
2056  } else {
2057    // Mask out lower bits, add stackalignment once plus the 12 bytes.
2058    Offset = ((~AlignMask) & Offset) + StackAlignment +
2059      (StackAlignment-SlotSize);
2060  }
2061  return Offset;
2062}
2063
2064/// IsEligibleForTailCallElimination - Check to see whether the next instruction
2065/// following the call is a return. A function is eligible if caller/callee
2066/// calling conventions match, currently only fastcc supports tail calls, and
2067/// the function CALL is immediatly followed by a RET.
2068bool X86TargetLowering::IsEligibleForTailCallOptimization(CallSDNode *TheCall,
2069                                                      SDValue Ret,
2070                                                      SelectionDAG& DAG) const {
2071  if (!PerformTailCallOpt)
2072    return false;
2073
2074  if (CheckTailCallReturnConstraints(TheCall, Ret)) {
2075    MachineFunction &MF = DAG.getMachineFunction();
2076    unsigned CallerCC = MF.getFunction()->getCallingConv();
2077    unsigned CalleeCC= TheCall->getCallingConv();
2078    if (CalleeCC == CallingConv::Fast && CallerCC == CalleeCC) {
2079      SDValue Callee = TheCall->getCallee();
2080      // On x86/32Bit PIC/GOT  tail calls are supported.
2081      if (getTargetMachine().getRelocationModel() != Reloc::PIC_ ||
2082          !Subtarget->isPICStyleGOT()|| !Subtarget->is64Bit())
2083        return true;
2084
2085      // Can only do local tail calls (in same module, hidden or protected) on
2086      // x86_64 PIC/GOT at the moment.
2087      if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
2088        return G->getGlobal()->hasHiddenVisibility()
2089            || G->getGlobal()->hasProtectedVisibility();
2090    }
2091  }
2092
2093  return false;
2094}
2095
2096FastISel *
2097X86TargetLowering::createFastISel(MachineFunction &mf,
2098                                  MachineModuleInfo *mmo,
2099                                  DwarfWriter *dw,
2100                                  DenseMap<const Value *, unsigned> &vm,
2101                                  DenseMap<const BasicBlock *,
2102                                           MachineBasicBlock *> &bm,
2103                                  DenseMap<const AllocaInst *, int> &am
2104#ifndef NDEBUG
2105                                  , SmallSet<Instruction*, 8> &cil
2106#endif
2107                                  ) {
2108  return X86::createFastISel(mf, mmo, dw, vm, bm, am
2109#ifndef NDEBUG
2110                             , cil
2111#endif
2112                             );
2113}
2114
2115
2116//===----------------------------------------------------------------------===//
2117//                           Other Lowering Hooks
2118//===----------------------------------------------------------------------===//
2119
2120
2121SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) {
2122  MachineFunction &MF = DAG.getMachineFunction();
2123  X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2124  int ReturnAddrIndex = FuncInfo->getRAIndex();
2125
2126  if (ReturnAddrIndex == 0) {
2127    // Set up a frame object for the return address.
2128    uint64_t SlotSize = TD->getPointerSize();
2129    ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize, -SlotSize);
2130    FuncInfo->setRAIndex(ReturnAddrIndex);
2131  }
2132
2133  return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
2134}
2135
2136
2137/// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
2138/// specific condition code, returning the condition code and the LHS/RHS of the
2139/// comparison to make.
2140static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
2141                               SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
2142  if (!isFP) {
2143    if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
2144      if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
2145        // X > -1   -> X == 0, jump !sign.
2146        RHS = DAG.getConstant(0, RHS.getValueType());
2147        return X86::COND_NS;
2148      } else if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
2149        // X < 0   -> X == 0, jump on sign.
2150        return X86::COND_S;
2151      } else if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
2152        // X < 1   -> X <= 0
2153        RHS = DAG.getConstant(0, RHS.getValueType());
2154        return X86::COND_LE;
2155      }
2156    }
2157
2158    switch (SetCCOpcode) {
2159    default: assert(0 && "Invalid integer condition!");
2160    case ISD::SETEQ:  return X86::COND_E;
2161    case ISD::SETGT:  return X86::COND_G;
2162    case ISD::SETGE:  return X86::COND_GE;
2163    case ISD::SETLT:  return X86::COND_L;
2164    case ISD::SETLE:  return X86::COND_LE;
2165    case ISD::SETNE:  return X86::COND_NE;
2166    case ISD::SETULT: return X86::COND_B;
2167    case ISD::SETUGT: return X86::COND_A;
2168    case ISD::SETULE: return X86::COND_BE;
2169    case ISD::SETUGE: return X86::COND_AE;
2170    }
2171  }
2172
2173  // First determine if it is required or is profitable to flip the operands.
2174
2175  // If LHS is a foldable load, but RHS is not, flip the condition.
2176  if ((ISD::isNON_EXTLoad(LHS.getNode()) && LHS.hasOneUse()) &&
2177      !(ISD::isNON_EXTLoad(RHS.getNode()) && RHS.hasOneUse())) {
2178    SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
2179    std::swap(LHS, RHS);
2180  }
2181
2182  switch (SetCCOpcode) {
2183  default: break;
2184  case ISD::SETOLT:
2185  case ISD::SETOLE:
2186  case ISD::SETUGT:
2187  case ISD::SETUGE:
2188    std::swap(LHS, RHS);
2189    break;
2190  }
2191
2192  // On a floating point condition, the flags are set as follows:
2193  // ZF  PF  CF   op
2194  //  0 | 0 | 0 | X > Y
2195  //  0 | 0 | 1 | X < Y
2196  //  1 | 0 | 0 | X == Y
2197  //  1 | 1 | 1 | unordered
2198  switch (SetCCOpcode) {
2199  default: assert(0 && "Condcode should be pre-legalized away");
2200  case ISD::SETUEQ:
2201  case ISD::SETEQ:   return X86::COND_E;
2202  case ISD::SETOLT:              // flipped
2203  case ISD::SETOGT:
2204  case ISD::SETGT:   return X86::COND_A;
2205  case ISD::SETOLE:              // flipped
2206  case ISD::SETOGE:
2207  case ISD::SETGE:   return X86::COND_AE;
2208  case ISD::SETUGT:              // flipped
2209  case ISD::SETULT:
2210  case ISD::SETLT:   return X86::COND_B;
2211  case ISD::SETUGE:              // flipped
2212  case ISD::SETULE:
2213  case ISD::SETLE:   return X86::COND_BE;
2214  case ISD::SETONE:
2215  case ISD::SETNE:   return X86::COND_NE;
2216  case ISD::SETUO:   return X86::COND_P;
2217  case ISD::SETO:    return X86::COND_NP;
2218  }
2219}
2220
2221/// hasFPCMov - is there a floating point cmov for the specific X86 condition
2222/// code. Current x86 isa includes the following FP cmov instructions:
2223/// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
2224static bool hasFPCMov(unsigned X86CC) {
2225  switch (X86CC) {
2226  default:
2227    return false;
2228  case X86::COND_B:
2229  case X86::COND_BE:
2230  case X86::COND_E:
2231  case X86::COND_P:
2232  case X86::COND_A:
2233  case X86::COND_AE:
2234  case X86::COND_NE:
2235  case X86::COND_NP:
2236    return true;
2237  }
2238}
2239
2240/// isUndefOrInRange - Return true if Val is undef or if its value falls within
2241/// the specified range (L, H].
2242static bool isUndefOrInRange(int Val, int Low, int Hi) {
2243  return (Val < 0) || (Val >= Low && Val < Hi);
2244}
2245
2246/// isUndefOrEqual - Val is either less than zero (undef) or equal to the
2247/// specified value.
2248static bool isUndefOrEqual(int Val, int CmpVal) {
2249  if (Val < 0 || Val == CmpVal)
2250    return true;
2251  return false;
2252}
2253
2254/// isPSHUFDMask - Return true if the node specifies a shuffle of elements that
2255/// is suitable for input to PSHUFD or PSHUFW.  That is, it doesn't reference
2256/// the second operand.
2257static bool isPSHUFDMask(const SmallVectorImpl<int> &Mask, MVT VT) {
2258  if (VT == MVT::v4f32 || VT == MVT::v4i32 || VT == MVT::v4i16)
2259    return (Mask[0] < 4 && Mask[1] < 4 && Mask[2] < 4 && Mask[3] < 4);
2260  if (VT == MVT::v2f64 || VT == MVT::v2i64)
2261    return (Mask[0] < 2 && Mask[1] < 2);
2262  return false;
2263}
2264
2265bool X86::isPSHUFDMask(ShuffleVectorSDNode *N) {
2266  SmallVector<int, 8> M;
2267  N->getMask(M);
2268  return ::isPSHUFDMask(M, N->getValueType(0));
2269}
2270
2271/// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that
2272/// is suitable for input to PSHUFHW.
2273static bool isPSHUFHWMask(const SmallVectorImpl<int> &Mask, MVT VT) {
2274  if (VT != MVT::v8i16)
2275    return false;
2276
2277  // Lower quadword copied in order or undef.
2278  for (int i = 0; i != 4; ++i)
2279    if (Mask[i] >= 0 && Mask[i] != i)
2280      return false;
2281
2282  // Upper quadword shuffled.
2283  for (int i = 4; i != 8; ++i)
2284    if (Mask[i] >= 0 && (Mask[i] < 4 || Mask[i] > 7))
2285      return false;
2286
2287  return true;
2288}
2289
2290bool X86::isPSHUFHWMask(ShuffleVectorSDNode *N) {
2291  SmallVector<int, 8> M;
2292  N->getMask(M);
2293  return ::isPSHUFHWMask(M, N->getValueType(0));
2294}
2295
2296/// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that
2297/// is suitable for input to PSHUFLW.
2298static bool isPSHUFLWMask(const SmallVectorImpl<int> &Mask, MVT VT) {
2299  if (VT != MVT::v8i16)
2300    return false;
2301
2302  // Upper quadword copied in order.
2303  for (int i = 4; i != 8; ++i)
2304    if (Mask[i] >= 0 && Mask[i] != i)
2305      return false;
2306
2307  // Lower quadword shuffled.
2308  for (int i = 0; i != 4; ++i)
2309    if (Mask[i] >= 4)
2310      return false;
2311
2312  return true;
2313}
2314
2315bool X86::isPSHUFLWMask(ShuffleVectorSDNode *N) {
2316  SmallVector<int, 8> M;
2317  N->getMask(M);
2318  return ::isPSHUFLWMask(M, N->getValueType(0));
2319}
2320
2321/// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
2322/// specifies a shuffle of elements that is suitable for input to SHUFP*.
2323static bool isSHUFPMask(const SmallVectorImpl<int> &Mask, MVT VT) {
2324  int NumElems = VT.getVectorNumElements();
2325  if (NumElems != 2 && NumElems != 4)
2326    return false;
2327
2328  int Half = NumElems / 2;
2329  for (int i = 0; i < Half; ++i)
2330    if (!isUndefOrInRange(Mask[i], 0, NumElems))
2331      return false;
2332  for (int i = Half; i < NumElems; ++i)
2333    if (!isUndefOrInRange(Mask[i], NumElems, NumElems*2))
2334      return false;
2335
2336  return true;
2337}
2338
2339bool X86::isSHUFPMask(ShuffleVectorSDNode *N) {
2340  SmallVector<int, 8> M;
2341  N->getMask(M);
2342  return ::isSHUFPMask(M, N->getValueType(0));
2343}
2344
2345/// isCommutedSHUFP - Returns true if the shuffle mask is exactly
2346/// the reverse of what x86 shuffles want. x86 shuffles requires the lower
2347/// half elements to come from vector 1 (which would equal the dest.) and
2348/// the upper half to come from vector 2.
2349static bool isCommutedSHUFPMask(const SmallVectorImpl<int> &Mask, MVT VT) {
2350  int NumElems = VT.getVectorNumElements();
2351
2352  if (NumElems != 2 && NumElems != 4)
2353    return false;
2354
2355  int Half = NumElems / 2;
2356  for (int i = 0; i < Half; ++i)
2357    if (!isUndefOrInRange(Mask[i], NumElems, NumElems*2))
2358      return false;
2359  for (int i = Half; i < NumElems; ++i)
2360    if (!isUndefOrInRange(Mask[i], 0, NumElems))
2361      return false;
2362  return true;
2363}
2364
2365static bool isCommutedSHUFP(ShuffleVectorSDNode *N) {
2366  SmallVector<int, 8> M;
2367  N->getMask(M);
2368  return isCommutedSHUFPMask(M, N->getValueType(0));
2369}
2370
2371/// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
2372/// specifies a shuffle of elements that is suitable for input to MOVHLPS.
2373bool X86::isMOVHLPSMask(ShuffleVectorSDNode *N) {
2374  if (N->getValueType(0).getVectorNumElements() != 4)
2375    return false;
2376
2377  // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
2378  return isUndefOrEqual(N->getMaskElt(0), 6) &&
2379         isUndefOrEqual(N->getMaskElt(1), 7) &&
2380         isUndefOrEqual(N->getMaskElt(2), 2) &&
2381         isUndefOrEqual(N->getMaskElt(3), 3);
2382}
2383
2384/// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
2385/// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
2386bool X86::isMOVLPMask(ShuffleVectorSDNode *N) {
2387  unsigned NumElems = N->getValueType(0).getVectorNumElements();
2388
2389  if (NumElems != 2 && NumElems != 4)
2390    return false;
2391
2392  for (unsigned i = 0; i < NumElems/2; ++i)
2393    if (!isUndefOrEqual(N->getMaskElt(i), i + NumElems))
2394      return false;
2395
2396  for (unsigned i = NumElems/2; i < NumElems; ++i)
2397    if (!isUndefOrEqual(N->getMaskElt(i), i))
2398      return false;
2399
2400  return true;
2401}
2402
2403/// isMOVHPMask - Return true if the specified VECTOR_SHUFFLE operand
2404/// specifies a shuffle of elements that is suitable for input to MOVHP{S|D}
2405/// and MOVLHPS.
2406bool X86::isMOVHPMask(ShuffleVectorSDNode *N) {
2407  unsigned NumElems = N->getValueType(0).getVectorNumElements();
2408
2409  if (NumElems != 2 && NumElems != 4)
2410    return false;
2411
2412  for (unsigned i = 0; i < NumElems/2; ++i)
2413    if (!isUndefOrEqual(N->getMaskElt(i), i))
2414      return false;
2415
2416  for (unsigned i = 0; i < NumElems/2; ++i)
2417    if (!isUndefOrEqual(N->getMaskElt(i + NumElems/2), i + NumElems))
2418      return false;
2419
2420  return true;
2421}
2422
2423/// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
2424/// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
2425/// <2, 3, 2, 3>
2426bool X86::isMOVHLPS_v_undef_Mask(ShuffleVectorSDNode *N) {
2427  unsigned NumElems = N->getValueType(0).getVectorNumElements();
2428
2429  if (NumElems != 4)
2430    return false;
2431
2432  return isUndefOrEqual(N->getMaskElt(0), 2) &&
2433         isUndefOrEqual(N->getMaskElt(1), 3) &&
2434         isUndefOrEqual(N->getMaskElt(2), 2) &&
2435         isUndefOrEqual(N->getMaskElt(3), 3);
2436}
2437
2438/// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
2439/// specifies a shuffle of elements that is suitable for input to UNPCKL.
2440static bool isUNPCKLMask(const SmallVectorImpl<int> &Mask, MVT VT,
2441                         bool V2IsSplat = false) {
2442  int NumElts = VT.getVectorNumElements();
2443  if (NumElts != 2 && NumElts != 4 && NumElts != 8 && NumElts != 16)
2444    return false;
2445
2446  for (int i = 0, j = 0; i != NumElts; i += 2, ++j) {
2447    int BitI  = Mask[i];
2448    int BitI1 = Mask[i+1];
2449    if (!isUndefOrEqual(BitI, j))
2450      return false;
2451    if (V2IsSplat) {
2452      if (!isUndefOrEqual(BitI1, NumElts))
2453        return false;
2454    } else {
2455      if (!isUndefOrEqual(BitI1, j + NumElts))
2456        return false;
2457    }
2458  }
2459  return true;
2460}
2461
2462bool X86::isUNPCKLMask(ShuffleVectorSDNode *N, bool V2IsSplat) {
2463  SmallVector<int, 8> M;
2464  N->getMask(M);
2465  return ::isUNPCKLMask(M, N->getValueType(0), V2IsSplat);
2466}
2467
2468/// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
2469/// specifies a shuffle of elements that is suitable for input to UNPCKH.
2470static bool isUNPCKHMask(const SmallVectorImpl<int> &Mask, MVT VT,
2471                         bool V2IsSplat = false) {
2472  int NumElts = VT.getVectorNumElements();
2473  if (NumElts != 2 && NumElts != 4 && NumElts != 8 && NumElts != 16)
2474    return false;
2475
2476  for (int i = 0, j = 0; i != NumElts; i += 2, ++j) {
2477    int BitI  = Mask[i];
2478    int BitI1 = Mask[i+1];
2479    if (!isUndefOrEqual(BitI, j + NumElts/2))
2480      return false;
2481    if (V2IsSplat) {
2482      if (isUndefOrEqual(BitI1, NumElts))
2483        return false;
2484    } else {
2485      if (!isUndefOrEqual(BitI1, j + NumElts/2 + NumElts))
2486        return false;
2487    }
2488  }
2489  return true;
2490}
2491
2492bool X86::isUNPCKHMask(ShuffleVectorSDNode *N, bool V2IsSplat) {
2493  SmallVector<int, 8> M;
2494  N->getMask(M);
2495  return ::isUNPCKHMask(M, N->getValueType(0), V2IsSplat);
2496}
2497
2498/// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
2499/// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
2500/// <0, 0, 1, 1>
2501static bool isUNPCKL_v_undef_Mask(const SmallVectorImpl<int> &Mask, MVT VT) {
2502  int NumElems = VT.getVectorNumElements();
2503  if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
2504    return false;
2505
2506  for (int i = 0, j = 0; i != NumElems; i += 2, ++j) {
2507    int BitI  = Mask[i];
2508    int BitI1 = Mask[i+1];
2509    if (!isUndefOrEqual(BitI, j))
2510      return false;
2511    if (!isUndefOrEqual(BitI1, j))
2512      return false;
2513  }
2514  return true;
2515}
2516
2517bool X86::isUNPCKL_v_undef_Mask(ShuffleVectorSDNode *N) {
2518  SmallVector<int, 8> M;
2519  N->getMask(M);
2520  return ::isUNPCKL_v_undef_Mask(M, N->getValueType(0));
2521}
2522
2523/// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
2524/// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
2525/// <2, 2, 3, 3>
2526static bool isUNPCKH_v_undef_Mask(const SmallVectorImpl<int> &Mask, MVT VT) {
2527  int NumElems = VT.getVectorNumElements();
2528  if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
2529    return false;
2530
2531  for (int i = 0, j = NumElems / 2; i != NumElems; i += 2, ++j) {
2532    int BitI  = Mask[i];
2533    int BitI1 = Mask[i+1];
2534    if (!isUndefOrEqual(BitI, j))
2535      return false;
2536    if (!isUndefOrEqual(BitI1, j))
2537      return false;
2538  }
2539  return true;
2540}
2541
2542bool X86::isUNPCKH_v_undef_Mask(ShuffleVectorSDNode *N) {
2543  SmallVector<int, 8> M;
2544  N->getMask(M);
2545  return ::isUNPCKH_v_undef_Mask(M, N->getValueType(0));
2546}
2547
2548/// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
2549/// specifies a shuffle of elements that is suitable for input to MOVSS,
2550/// MOVSD, and MOVD, i.e. setting the lowest element.
2551static bool isMOVLMask(const SmallVectorImpl<int> &Mask, MVT VT) {
2552  if (VT.getVectorElementType().getSizeInBits() < 32)
2553    return false;
2554
2555  int NumElts = VT.getVectorNumElements();
2556
2557  if (!isUndefOrEqual(Mask[0], NumElts))
2558    return false;
2559
2560  for (int i = 1; i < NumElts; ++i)
2561    if (!isUndefOrEqual(Mask[i], i))
2562      return false;
2563
2564  return true;
2565}
2566
2567bool X86::isMOVLMask(ShuffleVectorSDNode *N) {
2568  SmallVector<int, 8> M;
2569  N->getMask(M);
2570  return ::isMOVLMask(M, N->getValueType(0));
2571}
2572
2573/// isCommutedMOVL - Returns true if the shuffle mask is except the reverse
2574/// of what x86 movss want. X86 movs requires the lowest  element to be lowest
2575/// element of vector 2 and the other elements to come from vector 1 in order.
2576static bool isCommutedMOVLMask(const SmallVectorImpl<int> &Mask, MVT VT,
2577                               bool V2IsSplat = false, bool V2IsUndef = false) {
2578  int NumOps = VT.getVectorNumElements();
2579  if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
2580    return false;
2581
2582  if (!isUndefOrEqual(Mask[0], 0))
2583    return false;
2584
2585  for (int i = 1; i < NumOps; ++i)
2586    if (!(isUndefOrEqual(Mask[i], i+NumOps) ||
2587          (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) ||
2588          (V2IsSplat && isUndefOrEqual(Mask[i], NumOps))))
2589      return false;
2590
2591  return true;
2592}
2593
2594static bool isCommutedMOVL(ShuffleVectorSDNode *N, bool V2IsSplat = false,
2595                           bool V2IsUndef = false) {
2596  SmallVector<int, 8> M;
2597  N->getMask(M);
2598  return isCommutedMOVLMask(M, N->getValueType(0), V2IsSplat, V2IsUndef);
2599}
2600
2601/// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
2602/// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
2603bool X86::isMOVSHDUPMask(ShuffleVectorSDNode *N) {
2604  if (N->getValueType(0).getVectorNumElements() != 4)
2605    return false;
2606
2607  // Expect 1, 1, 3, 3
2608  for (unsigned i = 0; i < 2; ++i) {
2609    int Elt = N->getMaskElt(i);
2610    if (Elt >= 0 && Elt != 1)
2611      return false;
2612  }
2613
2614  bool HasHi = false;
2615  for (unsigned i = 2; i < 4; ++i) {
2616    int Elt = N->getMaskElt(i);
2617    if (Elt >= 0 && Elt != 3)
2618      return false;
2619    if (Elt == 3)
2620      HasHi = true;
2621  }
2622  // Don't use movshdup if it can be done with a shufps.
2623  // FIXME: verify that matching u, u, 3, 3 is what we want.
2624  return HasHi;
2625}
2626
2627/// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
2628/// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
2629bool X86::isMOVSLDUPMask(ShuffleVectorSDNode *N) {
2630  if (N->getValueType(0).getVectorNumElements() != 4)
2631    return false;
2632
2633  // Expect 0, 0, 2, 2
2634  for (unsigned i = 0; i < 2; ++i)
2635    if (N->getMaskElt(i) > 0)
2636      return false;
2637
2638  bool HasHi = false;
2639  for (unsigned i = 2; i < 4; ++i) {
2640    int Elt = N->getMaskElt(i);
2641    if (Elt >= 0 && Elt != 2)
2642      return false;
2643    if (Elt == 2)
2644      HasHi = true;
2645  }
2646  // Don't use movsldup if it can be done with a shufps.
2647  return HasHi;
2648}
2649
2650/// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
2651/// specifies a shuffle of elements that is suitable for input to MOVDDUP.
2652bool X86::isMOVDDUPMask(ShuffleVectorSDNode *N) {
2653  int e = N->getValueType(0).getVectorNumElements() / 2;
2654
2655  for (int i = 0; i < e; ++i)
2656    if (!isUndefOrEqual(N->getMaskElt(i), i))
2657      return false;
2658  for (int i = 0; i < e; ++i)
2659    if (!isUndefOrEqual(N->getMaskElt(e+i), i))
2660      return false;
2661  return true;
2662}
2663
2664/// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
2665/// the specified isShuffleMask VECTOR_SHUFFLE mask with PSHUF* and SHUFP*
2666/// instructions.
2667unsigned X86::getShuffleSHUFImmediate(SDNode *N) {
2668  ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
2669  int NumOperands = SVOp->getValueType(0).getVectorNumElements();
2670
2671  unsigned Shift = (NumOperands == 4) ? 2 : 1;
2672  unsigned Mask = 0;
2673  for (int i = 0; i < NumOperands; ++i) {
2674    int Val = SVOp->getMaskElt(NumOperands-i-1);
2675    if (Val < 0) Val = 0;
2676    if (Val >= NumOperands) Val -= NumOperands;
2677    Mask |= Val;
2678    if (i != NumOperands - 1)
2679      Mask <<= Shift;
2680  }
2681  return Mask;
2682}
2683
2684/// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
2685/// the specified isShuffleMask VECTOR_SHUFFLE mask with PSHUFHW
2686/// instructions.
2687unsigned X86::getShufflePSHUFHWImmediate(SDNode *N) {
2688  ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
2689  unsigned Mask = 0;
2690  // 8 nodes, but we only care about the last 4.
2691  for (unsigned i = 7; i >= 4; --i) {
2692    int Val = SVOp->getMaskElt(i);
2693    if (Val >= 0)
2694      Mask |= (Val - 4);
2695    if (i != 4)
2696      Mask <<= 2;
2697  }
2698  return Mask;
2699}
2700
2701/// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
2702/// the specified isShuffleMask VECTOR_SHUFFLE mask with PSHUFLW
2703/// instructions.
2704unsigned X86::getShufflePSHUFLWImmediate(SDNode *N) {
2705  ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
2706  unsigned Mask = 0;
2707  // 8 nodes, but we only care about the first 4.
2708  for (int i = 3; i >= 0; --i) {
2709    int Val = SVOp->getMaskElt(i);
2710    if (Val >= 0)
2711      Mask |= Val;
2712    if (i != 0)
2713      Mask <<= 2;
2714  }
2715  return Mask;
2716}
2717
2718/// CommuteVectorShuffle - Swap vector_shuffle operands as well as values in
2719/// their permute mask.
2720static SDValue CommuteVectorShuffle(ShuffleVectorSDNode *SVOp,
2721                                    SelectionDAG &DAG) {
2722  MVT VT = SVOp->getValueType(0);
2723  unsigned NumElems = VT.getVectorNumElements();
2724  SmallVector<int, 8> MaskVec;
2725
2726  for (unsigned i = 0; i != NumElems; ++i) {
2727    int idx = SVOp->getMaskElt(i);
2728    if (idx < 0)
2729      MaskVec.push_back(idx);
2730    else if (idx < (int)NumElems)
2731      MaskVec.push_back(idx + NumElems);
2732    else
2733      MaskVec.push_back(idx - NumElems);
2734  }
2735  return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(1),
2736                              SVOp->getOperand(0), &MaskVec[0]);
2737}
2738
2739/// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
2740/// the two vector operands have swapped position.
2741static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask, MVT VT) {
2742  unsigned NumElems = VT.getVectorNumElements();
2743  for (unsigned i = 0; i != NumElems; ++i) {
2744    int idx = Mask[i];
2745    if (idx < 0)
2746      continue;
2747    else if (idx < (int)NumElems)
2748      Mask[i] = idx + NumElems;
2749    else
2750      Mask[i] = idx - NumElems;
2751  }
2752}
2753
2754/// ShouldXformToMOVHLPS - Return true if the node should be transformed to
2755/// match movhlps. The lower half elements should come from upper half of
2756/// V1 (and in order), and the upper half elements should come from the upper
2757/// half of V2 (and in order).
2758static bool ShouldXformToMOVHLPS(ShuffleVectorSDNode *Op) {
2759  if (Op->getValueType(0).getVectorNumElements() != 4)
2760    return false;
2761  for (unsigned i = 0, e = 2; i != e; ++i)
2762    if (!isUndefOrEqual(Op->getMaskElt(i), i+2))
2763      return false;
2764  for (unsigned i = 2; i != 4; ++i)
2765    if (!isUndefOrEqual(Op->getMaskElt(i), i+4))
2766      return false;
2767  return true;
2768}
2769
2770/// isScalarLoadToVector - Returns true if the node is a scalar load that
2771/// is promoted to a vector. It also returns the LoadSDNode by reference if
2772/// required.
2773static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = NULL) {
2774  if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
2775    return false;
2776  N = N->getOperand(0).getNode();
2777  if (!ISD::isNON_EXTLoad(N))
2778    return false;
2779  if (LD)
2780    *LD = cast<LoadSDNode>(N);
2781  return true;
2782}
2783
2784/// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
2785/// match movlp{s|d}. The lower half elements should come from lower half of
2786/// V1 (and in order), and the upper half elements should come from the upper
2787/// half of V2 (and in order). And since V1 will become the source of the
2788/// MOVLP, it must be either a vector load or a scalar load to vector.
2789static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2,
2790                               ShuffleVectorSDNode *Op) {
2791  if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
2792    return false;
2793  // Is V2 is a vector load, don't do this transformation. We will try to use
2794  // load folding shufps op.
2795  if (ISD::isNON_EXTLoad(V2))
2796    return false;
2797
2798  unsigned NumElems = Op->getValueType(0).getVectorNumElements();
2799
2800  if (NumElems != 2 && NumElems != 4)
2801    return false;
2802  for (unsigned i = 0, e = NumElems/2; i != e; ++i)
2803    if (!isUndefOrEqual(Op->getMaskElt(i), i))
2804      return false;
2805  for (unsigned i = NumElems/2; i != NumElems; ++i)
2806    if (!isUndefOrEqual(Op->getMaskElt(i), i+NumElems))
2807      return false;
2808  return true;
2809}
2810
2811/// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
2812/// all the same.
2813static bool isSplatVector(SDNode *N) {
2814  if (N->getOpcode() != ISD::BUILD_VECTOR)
2815    return false;
2816
2817  SDValue SplatValue = N->getOperand(0);
2818  for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
2819    if (N->getOperand(i) != SplatValue)
2820      return false;
2821  return true;
2822}
2823
2824/// isZeroNode - Returns true if Elt is a constant zero or a floating point
2825/// constant +0.0.
2826static inline bool isZeroNode(SDValue Elt) {
2827  return ((isa<ConstantSDNode>(Elt) &&
2828           cast<ConstantSDNode>(Elt)->getZExtValue() == 0) ||
2829          (isa<ConstantFPSDNode>(Elt) &&
2830           cast<ConstantFPSDNode>(Elt)->getValueAPF().isPosZero()));
2831}
2832
2833/// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
2834/// to an zero vector.
2835/// FIXME: move to dag combiner / method on ShuffleVectorSDNode
2836static bool isZeroShuffle(ShuffleVectorSDNode *N) {
2837  SDValue V1 = N->getOperand(0);
2838  SDValue V2 = N->getOperand(1);
2839  unsigned NumElems = N->getValueType(0).getVectorNumElements();
2840  for (unsigned i = 0; i != NumElems; ++i) {
2841    int Idx = N->getMaskElt(i);
2842    if (Idx >= (int)NumElems) {
2843      unsigned Opc = V2.getOpcode();
2844      if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
2845        continue;
2846      if (Opc != ISD::BUILD_VECTOR || !isZeroNode(V2.getOperand(Idx-NumElems)))
2847        return false;
2848    } else if (Idx >= 0) {
2849      unsigned Opc = V1.getOpcode();
2850      if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
2851        continue;
2852      if (Opc != ISD::BUILD_VECTOR || !isZeroNode(V1.getOperand(Idx)))
2853        return false;
2854    }
2855  }
2856  return true;
2857}
2858
2859/// getZeroVector - Returns a vector of specified type with all zero elements.
2860///
2861static SDValue getZeroVector(MVT VT, bool HasSSE2, SelectionDAG &DAG,
2862                             DebugLoc dl) {
2863  assert(VT.isVector() && "Expected a vector type");
2864
2865  // Always build zero vectors as <4 x i32> or <2 x i32> bitcasted to their dest
2866  // type.  This ensures they get CSE'd.
2867  SDValue Vec;
2868  if (VT.getSizeInBits() == 64) { // MMX
2869    SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
2870    Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2i32, Cst, Cst);
2871  } else if (HasSSE2) {  // SSE2
2872    SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
2873    Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
2874  } else { // SSE1
2875    SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
2876    Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
2877  }
2878  return DAG.getNode(ISD::BIT_CONVERT, dl, VT, Vec);
2879}
2880
2881/// getOnesVector - Returns a vector of specified type with all bits set.
2882///
2883static SDValue getOnesVector(MVT VT, SelectionDAG &DAG, DebugLoc dl) {
2884  assert(VT.isVector() && "Expected a vector type");
2885
2886  // Always build ones vectors as <4 x i32> or <2 x i32> bitcasted to their dest
2887  // type.  This ensures they get CSE'd.
2888  SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
2889  SDValue Vec;
2890  if (VT.getSizeInBits() == 64)  // MMX
2891    Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2i32, Cst, Cst);
2892  else                                              // SSE
2893    Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
2894  return DAG.getNode(ISD::BIT_CONVERT, dl, VT, Vec);
2895}
2896
2897
2898/// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
2899/// that point to V2 points to its first element.
2900static SDValue NormalizeMask(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
2901  MVT VT = SVOp->getValueType(0);
2902  unsigned NumElems = VT.getVectorNumElements();
2903
2904  bool Changed = false;
2905  SmallVector<int, 8> MaskVec;
2906  SVOp->getMask(MaskVec);
2907
2908  for (unsigned i = 0; i != NumElems; ++i) {
2909    if (MaskVec[i] > (int)NumElems) {
2910      MaskVec[i] = NumElems;
2911      Changed = true;
2912    }
2913  }
2914  if (Changed)
2915    return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(0),
2916                                SVOp->getOperand(1), &MaskVec[0]);
2917  return SDValue(SVOp, 0);
2918}
2919
2920/// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
2921/// operation of specified width.
2922static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, MVT VT, SDValue V1,
2923                       SDValue V2) {
2924  unsigned NumElems = VT.getVectorNumElements();
2925  SmallVector<int, 8> Mask;
2926  Mask.push_back(NumElems);
2927  for (unsigned i = 1; i != NumElems; ++i)
2928    Mask.push_back(i);
2929  return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
2930}
2931
2932/// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
2933static SDValue getUnpackl(SelectionDAG &DAG, DebugLoc dl, MVT VT, SDValue V1,
2934                          SDValue V2) {
2935  unsigned NumElems = VT.getVectorNumElements();
2936  SmallVector<int, 8> Mask;
2937  for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
2938    Mask.push_back(i);
2939    Mask.push_back(i + NumElems);
2940  }
2941  return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
2942}
2943
2944/// getUnpackhMask - Returns a vector_shuffle node for an unpackh operation.
2945static SDValue getUnpackh(SelectionDAG &DAG, DebugLoc dl, MVT VT, SDValue V1,
2946                          SDValue V2) {
2947  unsigned NumElems = VT.getVectorNumElements();
2948  unsigned Half = NumElems/2;
2949  SmallVector<int, 8> Mask;
2950  for (unsigned i = 0; i != Half; ++i) {
2951    Mask.push_back(i + Half);
2952    Mask.push_back(i + NumElems + Half);
2953  }
2954  return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
2955}
2956
2957/// PromoteSplat - Promote a splat of v4f32, v8i16 or v16i8 to v4i32.
2958static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG,
2959                            bool HasSSE2) {
2960  if (SV->getValueType(0).getVectorNumElements() <= 4)
2961    return SDValue(SV, 0);
2962
2963  MVT PVT = MVT::v4f32;
2964  MVT VT = SV->getValueType(0);
2965  DebugLoc dl = SV->getDebugLoc();
2966  SDValue V1 = SV->getOperand(0);
2967  int NumElems = VT.getVectorNumElements();
2968  int EltNo = SV->getSplatIndex();
2969
2970  // unpack elements to the correct location
2971  while (NumElems > 4) {
2972    if (EltNo < NumElems/2) {
2973      V1 = getUnpackl(DAG, dl, VT, V1, V1);
2974    } else {
2975      V1 = getUnpackh(DAG, dl, VT, V1, V1);
2976      EltNo -= NumElems/2;
2977    }
2978    NumElems >>= 1;
2979  }
2980
2981  // Perform the splat.
2982  int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo };
2983  V1 = DAG.getNode(ISD::BIT_CONVERT, dl, PVT, V1);
2984  V1 = DAG.getVectorShuffle(PVT, dl, V1, DAG.getUNDEF(PVT), &SplatMask[0]);
2985  return DAG.getNode(ISD::BIT_CONVERT, dl, VT, V1);
2986}
2987
2988/// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
2989/// vector of zero or undef vector.  This produces a shuffle where the low
2990/// element of V2 is swizzled into the zero/undef vector, landing at element
2991/// Idx.  This produces a shuffle mask like 4,1,2,3 (idx=0) or  0,1,2,4 (idx=3).
2992static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
2993                                             bool isZero, bool HasSSE2,
2994                                             SelectionDAG &DAG) {
2995  MVT VT = V2.getValueType();
2996  SDValue V1 = isZero
2997    ? getZeroVector(VT, HasSSE2, DAG, V2.getDebugLoc()) : DAG.getUNDEF(VT);
2998  unsigned NumElems = VT.getVectorNumElements();
2999  SmallVector<int, 16> MaskVec;
3000  for (unsigned i = 0; i != NumElems; ++i)
3001    // If this is the insertion idx, put the low elt of V2 here.
3002    MaskVec.push_back(i == Idx ? NumElems : i);
3003  return DAG.getVectorShuffle(VT, V2.getDebugLoc(), V1, V2, &MaskVec[0]);
3004}
3005
3006/// getNumOfConsecutiveZeros - Return the number of elements in a result of
3007/// a shuffle that is zero.
3008static
3009unsigned getNumOfConsecutiveZeros(ShuffleVectorSDNode *SVOp, int NumElems,
3010                                  bool Low, SelectionDAG &DAG) {
3011  unsigned NumZeros = 0;
3012  for (int i = 0; i < NumElems; ++i) {
3013    unsigned Index = Low ? i : NumElems-i-1;
3014    int Idx = SVOp->getMaskElt(Index);
3015    if (Idx < 0) {
3016      ++NumZeros;
3017      continue;
3018    }
3019    SDValue Elt = DAG.getShuffleScalarElt(SVOp, Index);
3020    if (Elt.getNode() && isZeroNode(Elt))
3021      ++NumZeros;
3022    else
3023      break;
3024  }
3025  return NumZeros;
3026}
3027
3028/// isVectorShift - Returns true if the shuffle can be implemented as a
3029/// logical left or right shift of a vector.
3030/// FIXME: split into pslldqi, psrldqi, palignr variants.
3031static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
3032                          bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
3033  int NumElems = SVOp->getValueType(0).getVectorNumElements();
3034
3035  isLeft = true;
3036  unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems, true, DAG);
3037  if (!NumZeros) {
3038    isLeft = false;
3039    NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems, false, DAG);
3040    if (!NumZeros)
3041      return false;
3042  }
3043  bool SeenV1 = false;
3044  bool SeenV2 = false;
3045  for (int i = NumZeros; i < NumElems; ++i) {
3046    int Val = isLeft ? (i - NumZeros) : i;
3047    int Idx = SVOp->getMaskElt(isLeft ? i : (i - NumZeros));
3048    if (Idx < 0)
3049      continue;
3050    if (Idx < NumElems)
3051      SeenV1 = true;
3052    else {
3053      Idx -= NumElems;
3054      SeenV2 = true;
3055    }
3056    if (Idx != Val)
3057      return false;
3058  }
3059  if (SeenV1 && SeenV2)
3060    return false;
3061
3062  ShVal = SeenV1 ? SVOp->getOperand(0) : SVOp->getOperand(1);
3063  ShAmt = NumZeros;
3064  return true;
3065}
3066
3067
3068/// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
3069///
3070static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
3071                                       unsigned NumNonZero, unsigned NumZero,
3072                                       SelectionDAG &DAG, TargetLowering &TLI) {
3073  if (NumNonZero > 8)
3074    return SDValue();
3075
3076  DebugLoc dl = Op.getDebugLoc();
3077  SDValue V(0, 0);
3078  bool First = true;
3079  for (unsigned i = 0; i < 16; ++i) {
3080    bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
3081    if (ThisIsNonZero && First) {
3082      if (NumZero)
3083        V = getZeroVector(MVT::v8i16, true, DAG, dl);
3084      else
3085        V = DAG.getUNDEF(MVT::v8i16);
3086      First = false;
3087    }
3088
3089    if ((i & 1) != 0) {
3090      SDValue ThisElt(0, 0), LastElt(0, 0);
3091      bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
3092      if (LastIsNonZero) {
3093        LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
3094                              MVT::i16, Op.getOperand(i-1));
3095      }
3096      if (ThisIsNonZero) {
3097        ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
3098        ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
3099                              ThisElt, DAG.getConstant(8, MVT::i8));
3100        if (LastIsNonZero)
3101          ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
3102      } else
3103        ThisElt = LastElt;
3104
3105      if (ThisElt.getNode())
3106        V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
3107                        DAG.getIntPtrConstant(i/2));
3108    }
3109  }
3110
3111  return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v16i8, V);
3112}
3113
3114/// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
3115///
3116static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
3117                                       unsigned NumNonZero, unsigned NumZero,
3118                                       SelectionDAG &DAG, TargetLowering &TLI) {
3119  if (NumNonZero > 4)
3120    return SDValue();
3121
3122  DebugLoc dl = Op.getDebugLoc();
3123  SDValue V(0, 0);
3124  bool First = true;
3125  for (unsigned i = 0; i < 8; ++i) {
3126    bool isNonZero = (NonZeros & (1 << i)) != 0;
3127    if (isNonZero) {
3128      if (First) {
3129        if (NumZero)
3130          V = getZeroVector(MVT::v8i16, true, DAG, dl);
3131        else
3132          V = DAG.getUNDEF(MVT::v8i16);
3133        First = false;
3134      }
3135      V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
3136                      MVT::v8i16, V, Op.getOperand(i),
3137                      DAG.getIntPtrConstant(i));
3138    }
3139  }
3140
3141  return V;
3142}
3143
3144/// getVShift - Return a vector logical shift node.
3145///
3146static SDValue getVShift(bool isLeft, MVT VT, SDValue SrcOp,
3147                         unsigned NumBits, SelectionDAG &DAG,
3148                         const TargetLowering &TLI, DebugLoc dl) {
3149  bool isMMX = VT.getSizeInBits() == 64;
3150  MVT ShVT = isMMX ? MVT::v1i64 : MVT::v2i64;
3151  unsigned Opc = isLeft ? X86ISD::VSHL : X86ISD::VSRL;
3152  SrcOp = DAG.getNode(ISD::BIT_CONVERT, dl, ShVT, SrcOp);
3153  return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
3154                     DAG.getNode(Opc, dl, ShVT, SrcOp,
3155                             DAG.getConstant(NumBits, TLI.getShiftAmountTy())));
3156}
3157
3158SDValue
3159X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) {
3160  DebugLoc dl = Op.getDebugLoc();
3161  // All zero's are handled with pxor, all one's are handled with pcmpeqd.
3162  if (ISD::isBuildVectorAllZeros(Op.getNode())
3163      || ISD::isBuildVectorAllOnes(Op.getNode())) {
3164    // Canonicalize this to either <4 x i32> or <2 x i32> (SSE vs MMX) to
3165    // 1) ensure the zero vectors are CSE'd, and 2) ensure that i64 scalars are
3166    // eliminated on x86-32 hosts.
3167    if (Op.getValueType() == MVT::v4i32 || Op.getValueType() == MVT::v2i32)
3168      return Op;
3169
3170    if (ISD::isBuildVectorAllOnes(Op.getNode()))
3171      return getOnesVector(Op.getValueType(), DAG, dl);
3172    return getZeroVector(Op.getValueType(), Subtarget->hasSSE2(), DAG, dl);
3173  }
3174
3175  MVT VT = Op.getValueType();
3176  MVT EVT = VT.getVectorElementType();
3177  unsigned EVTBits = EVT.getSizeInBits();
3178
3179  unsigned NumElems = Op.getNumOperands();
3180  unsigned NumZero  = 0;
3181  unsigned NumNonZero = 0;
3182  unsigned NonZeros = 0;
3183  bool IsAllConstants = true;
3184  SmallSet<SDValue, 8> Values;
3185  for (unsigned i = 0; i < NumElems; ++i) {
3186    SDValue Elt = Op.getOperand(i);
3187    if (Elt.getOpcode() == ISD::UNDEF)
3188      continue;
3189    Values.insert(Elt);
3190    if (Elt.getOpcode() != ISD::Constant &&
3191        Elt.getOpcode() != ISD::ConstantFP)
3192      IsAllConstants = false;
3193    if (isZeroNode(Elt))
3194      NumZero++;
3195    else {
3196      NonZeros |= (1 << i);
3197      NumNonZero++;
3198    }
3199  }
3200
3201  if (NumNonZero == 0) {
3202    // All undef vector. Return an UNDEF.  All zero vectors were handled above.
3203    return DAG.getUNDEF(VT);
3204  }
3205
3206  // Special case for single non-zero, non-undef, element.
3207  if (NumNonZero == 1) {
3208    unsigned Idx = CountTrailingZeros_32(NonZeros);
3209    SDValue Item = Op.getOperand(Idx);
3210
3211    // If this is an insertion of an i64 value on x86-32, and if the top bits of
3212    // the value are obviously zero, truncate the value to i32 and do the
3213    // insertion that way.  Only do this if the value is non-constant or if the
3214    // value is a constant being inserted into element 0.  It is cheaper to do
3215    // a constant pool load than it is to do a movd + shuffle.
3216    if (EVT == MVT::i64 && !Subtarget->is64Bit() &&
3217        (!IsAllConstants || Idx == 0)) {
3218      if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
3219        // Handle MMX and SSE both.
3220        MVT VecVT = VT == MVT::v2i64 ? MVT::v4i32 : MVT::v2i32;
3221        unsigned VecElts = VT == MVT::v2i64 ? 4 : 2;
3222
3223        // Truncate the value (which may itself be a constant) to i32, and
3224        // convert it to a vector with movd (S2V+shuffle to zero extend).
3225        Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
3226        Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
3227        Item = getShuffleVectorZeroOrUndef(Item, 0, true,
3228                                           Subtarget->hasSSE2(), DAG);
3229
3230        // Now we have our 32-bit value zero extended in the low element of
3231        // a vector.  If Idx != 0, swizzle it into place.
3232        if (Idx != 0) {
3233          SmallVector<int, 4> Mask;
3234          Mask.push_back(Idx);
3235          for (unsigned i = 1; i != VecElts; ++i)
3236            Mask.push_back(i);
3237          Item = DAG.getVectorShuffle(VecVT, dl, Item,
3238                                      DAG.getUNDEF(Item.getValueType()),
3239                                      &Mask[0]);
3240        }
3241        return DAG.getNode(ISD::BIT_CONVERT, dl, Op.getValueType(), Item);
3242      }
3243    }
3244
3245    // If we have a constant or non-constant insertion into the low element of
3246    // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
3247    // the rest of the elements.  This will be matched as movd/movq/movss/movsd
3248    // depending on what the source datatype is.
3249    if (Idx == 0) {
3250      if (NumZero == 0) {
3251        return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
3252      } else if (EVT == MVT::i32 || EVT == MVT::f32 || EVT == MVT::f64 ||
3253          (EVT == MVT::i64 && Subtarget->is64Bit())) {
3254        Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
3255        // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
3256        return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget->hasSSE2(),
3257                                           DAG);
3258      } else if (EVT == MVT::i16 || EVT == MVT::i8) {
3259        Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
3260        MVT MiddleVT = VT.getSizeInBits() == 64 ? MVT::v2i32 : MVT::v4i32;
3261        Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MiddleVT, Item);
3262        Item = getShuffleVectorZeroOrUndef(Item, 0, true,
3263                                           Subtarget->hasSSE2(), DAG);
3264        return DAG.getNode(ISD::BIT_CONVERT, dl, VT, Item);
3265      }
3266    }
3267
3268    // Is it a vector logical left shift?
3269    if (NumElems == 2 && Idx == 1 &&
3270        isZeroNode(Op.getOperand(0)) && !isZeroNode(Op.getOperand(1))) {
3271      unsigned NumBits = VT.getSizeInBits();
3272      return getVShift(true, VT,
3273                       DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
3274                                   VT, Op.getOperand(1)),
3275                       NumBits/2, DAG, *this, dl);
3276    }
3277
3278    if (IsAllConstants) // Otherwise, it's better to do a constpool load.
3279      return SDValue();
3280
3281    // Otherwise, if this is a vector with i32 or f32 elements, and the element
3282    // is a non-constant being inserted into an element other than the low one,
3283    // we can't use a constant pool load.  Instead, use SCALAR_TO_VECTOR (aka
3284    // movd/movss) to move this into the low element, then shuffle it into
3285    // place.
3286    if (EVTBits == 32) {
3287      Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
3288
3289      // Turn it into a shuffle of zero and zero-extended scalar to vector.
3290      Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0,
3291                                         Subtarget->hasSSE2(), DAG);
3292      SmallVector<int, 8> MaskVec;
3293      for (unsigned i = 0; i < NumElems; i++)
3294        MaskVec.push_back(i == Idx ? 0 : 1);
3295      return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
3296    }
3297  }
3298
3299  // Splat is obviously ok. Let legalizer expand it to a shuffle.
3300  if (Values.size() == 1)
3301    return SDValue();
3302
3303  // A vector full of immediates; various special cases are already
3304  // handled, so this is best done with a single constant-pool load.
3305  if (IsAllConstants)
3306    return SDValue();
3307
3308  // Let legalizer expand 2-wide build_vectors.
3309  if (EVTBits == 64) {
3310    if (NumNonZero == 1) {
3311      // One half is zero or undef.
3312      unsigned Idx = CountTrailingZeros_32(NonZeros);
3313      SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
3314                                 Op.getOperand(Idx));
3315      return getShuffleVectorZeroOrUndef(V2, Idx, true,
3316                                         Subtarget->hasSSE2(), DAG);
3317    }
3318    return SDValue();
3319  }
3320
3321  // If element VT is < 32 bits, convert it to inserts into a zero vector.
3322  if (EVTBits == 8 && NumElems == 16) {
3323    SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
3324                                        *this);
3325    if (V.getNode()) return V;
3326  }
3327
3328  if (EVTBits == 16 && NumElems == 8) {
3329    SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
3330                                        *this);
3331    if (V.getNode()) return V;
3332  }
3333
3334  // If element VT is == 32 bits, turn it into a number of shuffles.
3335  SmallVector<SDValue, 8> V;
3336  V.resize(NumElems);
3337  if (NumElems == 4 && NumZero > 0) {
3338    for (unsigned i = 0; i < 4; ++i) {
3339      bool isZero = !(NonZeros & (1 << i));
3340      if (isZero)
3341        V[i] = getZeroVector(VT, Subtarget->hasSSE2(), DAG, dl);
3342      else
3343        V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
3344    }
3345
3346    for (unsigned i = 0; i < 2; ++i) {
3347      switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
3348        default: break;
3349        case 0:
3350          V[i] = V[i*2];  // Must be a zero vector.
3351          break;
3352        case 1:
3353          V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
3354          break;
3355        case 2:
3356          V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
3357          break;
3358        case 3:
3359          V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
3360          break;
3361      }
3362    }
3363
3364    SmallVector<int, 8> MaskVec;
3365    bool Reverse = (NonZeros & 0x3) == 2;
3366    for (unsigned i = 0; i < 2; ++i)
3367      MaskVec.push_back(Reverse ? 1-i : i);
3368    Reverse = ((NonZeros & (0x3 << 2)) >> 2) == 2;
3369    for (unsigned i = 0; i < 2; ++i)
3370      MaskVec.push_back(Reverse ? 1-i+NumElems : i+NumElems);
3371    return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
3372  }
3373
3374  if (Values.size() > 2) {
3375    // If we have SSE 4.1, Expand into a number of inserts unless the number of
3376    // values to be inserted is equal to the number of elements, in which case
3377    // use the unpack code below in the hopes of matching the consecutive elts
3378    // load merge pattern for shuffles.
3379    // FIXME: We could probably just check that here directly.
3380    if (Values.size() < NumElems && VT.getSizeInBits() == 128 &&
3381        getSubtarget()->hasSSE41()) {
3382      V[0] = DAG.getUNDEF(VT);
3383      for (unsigned i = 0; i < NumElems; ++i)
3384        if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
3385          V[0] = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, V[0],
3386                             Op.getOperand(i), DAG.getIntPtrConstant(i));
3387      return V[0];
3388    }
3389    // Expand into a number of unpckl*.
3390    // e.g. for v4f32
3391    //   Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
3392    //         : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
3393    //   Step 2: unpcklps X, Y ==>    <3, 2, 1, 0>
3394    for (unsigned i = 0; i < NumElems; ++i)
3395      V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
3396    NumElems >>= 1;
3397    while (NumElems != 0) {
3398      for (unsigned i = 0; i < NumElems; ++i)
3399        V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + NumElems]);
3400      NumElems >>= 1;
3401    }
3402    return V[0];
3403  }
3404
3405  return SDValue();
3406}
3407
3408// v8i16 shuffles - Prefer shuffles in the following order:
3409// 1. [all]   pshuflw, pshufhw, optional move
3410// 2. [ssse3] 1 x pshufb
3411// 3. [ssse3] 2 x pshufb + 1 x por
3412// 4. [all]   mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
3413static
3414SDValue LowerVECTOR_SHUFFLEv8i16(ShuffleVectorSDNode *SVOp,
3415                                 SelectionDAG &DAG, X86TargetLowering &TLI) {
3416  SDValue V1 = SVOp->getOperand(0);
3417  SDValue V2 = SVOp->getOperand(1);
3418  DebugLoc dl = SVOp->getDebugLoc();
3419  SmallVector<int, 8> MaskVals;
3420
3421  // Determine if more than 1 of the words in each of the low and high quadwords
3422  // of the result come from the same quadword of one of the two inputs.  Undef
3423  // mask values count as coming from any quadword, for better codegen.
3424  SmallVector<unsigned, 4> LoQuad(4);
3425  SmallVector<unsigned, 4> HiQuad(4);
3426  BitVector InputQuads(4);
3427  for (unsigned i = 0; i < 8; ++i) {
3428    SmallVectorImpl<unsigned> &Quad = i < 4 ? LoQuad : HiQuad;
3429    int EltIdx = SVOp->getMaskElt(i);
3430    MaskVals.push_back(EltIdx);
3431    if (EltIdx < 0) {
3432      ++Quad[0];
3433      ++Quad[1];
3434      ++Quad[2];
3435      ++Quad[3];
3436      continue;
3437    }
3438    ++Quad[EltIdx / 4];
3439    InputQuads.set(EltIdx / 4);
3440  }
3441
3442  int BestLoQuad = -1;
3443  unsigned MaxQuad = 1;
3444  for (unsigned i = 0; i < 4; ++i) {
3445    if (LoQuad[i] > MaxQuad) {
3446      BestLoQuad = i;
3447      MaxQuad = LoQuad[i];
3448    }
3449  }
3450
3451  int BestHiQuad = -1;
3452  MaxQuad = 1;
3453  for (unsigned i = 0; i < 4; ++i) {
3454    if (HiQuad[i] > MaxQuad) {
3455      BestHiQuad = i;
3456      MaxQuad = HiQuad[i];
3457    }
3458  }
3459
3460  // For SSSE3, If all 8 words of the result come from only 1 quadword of each
3461  // of the two input vectors, shuffle them into one input vector so only a
3462  // single pshufb instruction is necessary. If There are more than 2 input
3463  // quads, disable the next transformation since it does not help SSSE3.
3464  bool V1Used = InputQuads[0] || InputQuads[1];
3465  bool V2Used = InputQuads[2] || InputQuads[3];
3466  if (TLI.getSubtarget()->hasSSSE3()) {
3467    if (InputQuads.count() == 2 && V1Used && V2Used) {
3468      BestLoQuad = InputQuads.find_first();
3469      BestHiQuad = InputQuads.find_next(BestLoQuad);
3470    }
3471    if (InputQuads.count() > 2) {
3472      BestLoQuad = -1;
3473      BestHiQuad = -1;
3474    }
3475  }
3476
3477  // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
3478  // the shuffle mask.  If a quad is scored as -1, that means that it contains
3479  // words from all 4 input quadwords.
3480  SDValue NewV;
3481  if (BestLoQuad >= 0 || BestHiQuad >= 0) {
3482    SmallVector<int, 8> MaskV;
3483    MaskV.push_back(BestLoQuad < 0 ? 0 : BestLoQuad);
3484    MaskV.push_back(BestHiQuad < 0 ? 1 : BestHiQuad);
3485    NewV = DAG.getVectorShuffle(MVT::v2i64, dl,
3486                  DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64, V1),
3487                  DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64, V2), &MaskV[0]);
3488    NewV = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v8i16, NewV);
3489
3490    // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
3491    // source words for the shuffle, to aid later transformations.
3492    bool AllWordsInNewV = true;
3493    bool InOrder[2] = { true, true };
3494    for (unsigned i = 0; i != 8; ++i) {
3495      int idx = MaskVals[i];
3496      if (idx != (int)i)
3497        InOrder[i/4] = false;
3498      if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
3499        continue;
3500      AllWordsInNewV = false;
3501      break;
3502    }
3503
3504    bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
3505    if (AllWordsInNewV) {
3506      for (int i = 0; i != 8; ++i) {
3507        int idx = MaskVals[i];
3508        if (idx < 0)
3509          continue;
3510        idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
3511        if ((idx != i) && idx < 4)
3512          pshufhw = false;
3513        if ((idx != i) && idx > 3)
3514          pshuflw = false;
3515      }
3516      V1 = NewV;
3517      V2Used = false;
3518      BestLoQuad = 0;
3519      BestHiQuad = 1;
3520    }
3521
3522    // If we've eliminated the use of V2, and the new mask is a pshuflw or
3523    // pshufhw, that's as cheap as it gets.  Return the new shuffle.
3524    if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
3525      return DAG.getVectorShuffle(MVT::v8i16, dl, NewV,
3526                                  DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
3527    }
3528  }
3529
3530  // If we have SSSE3, and all words of the result are from 1 input vector,
3531  // case 2 is generated, otherwise case 3 is generated.  If no SSSE3
3532  // is present, fall back to case 4.
3533  if (TLI.getSubtarget()->hasSSSE3()) {
3534    SmallVector<SDValue,16> pshufbMask;
3535
3536    // If we have elements from both input vectors, set the high bit of the
3537    // shuffle mask element to zero out elements that come from V2 in the V1
3538    // mask, and elements that come from V1 in the V2 mask, so that the two
3539    // results can be OR'd together.
3540    bool TwoInputs = V1Used && V2Used;
3541    for (unsigned i = 0; i != 8; ++i) {
3542      int EltIdx = MaskVals[i] * 2;
3543      if (TwoInputs && (EltIdx >= 16)) {
3544        pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
3545        pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
3546        continue;
3547      }
3548      pshufbMask.push_back(DAG.getConstant(EltIdx,   MVT::i8));
3549      pshufbMask.push_back(DAG.getConstant(EltIdx+1, MVT::i8));
3550    }
3551    V1 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v16i8, V1);
3552    V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
3553                     DAG.getNode(ISD::BUILD_VECTOR, dl,
3554                                 MVT::v16i8, &pshufbMask[0], 16));
3555    if (!TwoInputs)
3556      return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v8i16, V1);
3557
3558    // Calculate the shuffle mask for the second input, shuffle it, and
3559    // OR it with the first shuffled input.
3560    pshufbMask.clear();
3561    for (unsigned i = 0; i != 8; ++i) {
3562      int EltIdx = MaskVals[i] * 2;
3563      if (EltIdx < 16) {
3564        pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
3565        pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
3566        continue;
3567      }
3568      pshufbMask.push_back(DAG.getConstant(EltIdx - 16, MVT::i8));
3569      pshufbMask.push_back(DAG.getConstant(EltIdx - 15, MVT::i8));
3570    }
3571    V2 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v16i8, V2);
3572    V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
3573                     DAG.getNode(ISD::BUILD_VECTOR, dl,
3574                                 MVT::v16i8, &pshufbMask[0], 16));
3575    V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
3576    return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v8i16, V1);
3577  }
3578
3579  // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
3580  // and update MaskVals with new element order.
3581  BitVector InOrder(8);
3582  if (BestLoQuad >= 0) {
3583    SmallVector<int, 8> MaskV;
3584    for (int i = 0; i != 4; ++i) {
3585      int idx = MaskVals[i];
3586      if (idx < 0) {
3587        MaskV.push_back(-1);
3588        InOrder.set(i);
3589      } else if ((idx / 4) == BestLoQuad) {
3590        MaskV.push_back(idx & 3);
3591        InOrder.set(i);
3592      } else {
3593        MaskV.push_back(-1);
3594      }
3595    }
3596    for (unsigned i = 4; i != 8; ++i)
3597      MaskV.push_back(i);
3598    NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
3599                                &MaskV[0]);
3600  }
3601
3602  // If BestHi >= 0, generate a pshufhw to put the high elements in order,
3603  // and update MaskVals with the new element order.
3604  if (BestHiQuad >= 0) {
3605    SmallVector<int, 8> MaskV;
3606    for (unsigned i = 0; i != 4; ++i)
3607      MaskV.push_back(i);
3608    for (unsigned i = 4; i != 8; ++i) {
3609      int idx = MaskVals[i];
3610      if (idx < 0) {
3611        MaskV.push_back(-1);
3612        InOrder.set(i);
3613      } else if ((idx / 4) == BestHiQuad) {
3614        MaskV.push_back((idx & 3) + 4);
3615        InOrder.set(i);
3616      } else {
3617        MaskV.push_back(-1);
3618      }
3619    }
3620    NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
3621                                &MaskV[0]);
3622  }
3623
3624  // In case BestHi & BestLo were both -1, which means each quadword has a word
3625  // from each of the four input quadwords, calculate the InOrder bitvector now
3626  // before falling through to the insert/extract cleanup.
3627  if (BestLoQuad == -1 && BestHiQuad == -1) {
3628    NewV = V1;
3629    for (int i = 0; i != 8; ++i)
3630      if (MaskVals[i] < 0 || MaskVals[i] == i)
3631        InOrder.set(i);
3632  }
3633
3634  // The other elements are put in the right place using pextrw and pinsrw.
3635  for (unsigned i = 0; i != 8; ++i) {
3636    if (InOrder[i])
3637      continue;
3638    int EltIdx = MaskVals[i];
3639    if (EltIdx < 0)
3640      continue;
3641    SDValue ExtOp = (EltIdx < 8)
3642    ? DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
3643                  DAG.getIntPtrConstant(EltIdx))
3644    : DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
3645                  DAG.getIntPtrConstant(EltIdx - 8));
3646    NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
3647                       DAG.getIntPtrConstant(i));
3648  }
3649  return NewV;
3650}
3651
3652// v16i8 shuffles - Prefer shuffles in the following order:
3653// 1. [ssse3] 1 x pshufb
3654// 2. [ssse3] 2 x pshufb + 1 x por
3655// 3. [all]   v8i16 shuffle + N x pextrw + rotate + pinsrw
3656static
3657SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
3658                                 SelectionDAG &DAG, X86TargetLowering &TLI) {
3659  SDValue V1 = SVOp->getOperand(0);
3660  SDValue V2 = SVOp->getOperand(1);
3661  DebugLoc dl = SVOp->getDebugLoc();
3662  SmallVector<int, 16> MaskVals;
3663  SVOp->getMask(MaskVals);
3664
3665  // If we have SSSE3, case 1 is generated when all result bytes come from
3666  // one of  the inputs.  Otherwise, case 2 is generated.  If no SSSE3 is
3667  // present, fall back to case 3.
3668  // FIXME: kill V2Only once shuffles are canonizalized by getNode.
3669  bool V1Only = true;
3670  bool V2Only = true;
3671  for (unsigned i = 0; i < 16; ++i) {
3672    int EltIdx = MaskVals[i];
3673    if (EltIdx < 0)
3674      continue;
3675    if (EltIdx < 16)
3676      V2Only = false;
3677    else
3678      V1Only = false;
3679  }
3680
3681  // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
3682  if (TLI.getSubtarget()->hasSSSE3()) {
3683    SmallVector<SDValue,16> pshufbMask;
3684
3685    // If all result elements are from one input vector, then only translate
3686    // undef mask values to 0x80 (zero out result) in the pshufb mask.
3687    //
3688    // Otherwise, we have elements from both input vectors, and must zero out
3689    // elements that come from V2 in the first mask, and V1 in the second mask
3690    // so that we can OR them together.
3691    bool TwoInputs = !(V1Only || V2Only);
3692    for (unsigned i = 0; i != 16; ++i) {
3693      int EltIdx = MaskVals[i];
3694      if (EltIdx < 0 || (TwoInputs && EltIdx >= 16)) {
3695        pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
3696        continue;
3697      }
3698      pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
3699    }
3700    // If all the elements are from V2, assign it to V1 and return after
3701    // building the first pshufb.
3702    if (V2Only)
3703      V1 = V2;
3704    V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
3705                     DAG.getNode(ISD::BUILD_VECTOR, dl,
3706                                 MVT::v16i8, &pshufbMask[0], 16));
3707    if (!TwoInputs)
3708      return V1;
3709
3710    // Calculate the shuffle mask for the second input, shuffle it, and
3711    // OR it with the first shuffled input.
3712    pshufbMask.clear();
3713    for (unsigned i = 0; i != 16; ++i) {
3714      int EltIdx = MaskVals[i];
3715      if (EltIdx < 16) {
3716        pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
3717        continue;
3718      }
3719      pshufbMask.push_back(DAG.getConstant(EltIdx - 16, MVT::i8));
3720    }
3721    V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
3722                     DAG.getNode(ISD::BUILD_VECTOR, dl,
3723                                 MVT::v16i8, &pshufbMask[0], 16));
3724    return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
3725  }
3726
3727  // No SSSE3 - Calculate in place words and then fix all out of place words
3728  // With 0-16 extracts & inserts.  Worst case is 16 bytes out of order from
3729  // the 16 different words that comprise the two doublequadword input vectors.
3730  V1 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v8i16, V1);
3731  V2 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v8i16, V2);
3732  SDValue NewV = V2Only ? V2 : V1;
3733  for (int i = 0; i != 8; ++i) {
3734    int Elt0 = MaskVals[i*2];
3735    int Elt1 = MaskVals[i*2+1];
3736
3737    // This word of the result is all undef, skip it.
3738    if (Elt0 < 0 && Elt1 < 0)
3739      continue;
3740
3741    // This word of the result is already in the correct place, skip it.
3742    if (V1Only && (Elt0 == i*2) && (Elt1 == i*2+1))
3743      continue;
3744    if (V2Only && (Elt0 == i*2+16) && (Elt1 == i*2+17))
3745      continue;
3746
3747    SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
3748    SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
3749    SDValue InsElt;
3750
3751    // If Elt0 and Elt1 are defined, are consecutive, and can be load
3752    // using a single extract together, load it and store it.
3753    if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
3754      InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
3755                           DAG.getIntPtrConstant(Elt1 / 2));
3756      NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
3757                        DAG.getIntPtrConstant(i));
3758      continue;
3759    }
3760
3761    // If Elt1 is defined, extract it from the appropriate source.  If the
3762    // source byte is not also odd, shift the extracted word left 8 bits
3763    // otherwise clear the bottom 8 bits if we need to do an or.
3764    if (Elt1 >= 0) {
3765      InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
3766                           DAG.getIntPtrConstant(Elt1 / 2));
3767      if ((Elt1 & 1) == 0)
3768        InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
3769                             DAG.getConstant(8, TLI.getShiftAmountTy()));
3770      else if (Elt0 >= 0)
3771        InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
3772                             DAG.getConstant(0xFF00, MVT::i16));
3773    }
3774    // If Elt0 is defined, extract it from the appropriate source.  If the
3775    // source byte is not also even, shift the extracted word right 8 bits. If
3776    // Elt1 was also defined, OR the extracted values together before
3777    // inserting them in the result.
3778    if (Elt0 >= 0) {
3779      SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
3780                                    Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
3781      if ((Elt0 & 1) != 0)
3782        InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
3783                              DAG.getConstant(8, TLI.getShiftAmountTy()));
3784      else if (Elt1 >= 0)
3785        InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
3786                             DAG.getConstant(0x00FF, MVT::i16));
3787      InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
3788                         : InsElt0;
3789    }
3790    NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
3791                       DAG.getIntPtrConstant(i));
3792  }
3793  return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v16i8, NewV);
3794}
3795
3796/// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
3797/// ones, or rewriting v4i32 / v2f32 as 2 wide ones if possible. This can be
3798/// done when every pair / quad of shuffle mask elements point to elements in
3799/// the right sequence. e.g.
3800/// vector_shuffle <>, <>, < 3, 4, | 10, 11, | 0, 1, | 14, 15>
3801static
3802SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
3803                                 SelectionDAG &DAG,
3804                                 TargetLowering &TLI, DebugLoc dl) {
3805  MVT VT = SVOp->getValueType(0);
3806  SDValue V1 = SVOp->getOperand(0);
3807  SDValue V2 = SVOp->getOperand(1);
3808  unsigned NumElems = VT.getVectorNumElements();
3809  unsigned NewWidth = (NumElems == 4) ? 2 : 4;
3810  MVT MaskVT = MVT::getIntVectorWithNumElements(NewWidth);
3811  MVT MaskEltVT = MaskVT.getVectorElementType();
3812  MVT NewVT = MaskVT;
3813  switch (VT.getSimpleVT()) {
3814  default: assert(false && "Unexpected!");
3815  case MVT::v4f32: NewVT = MVT::v2f64; break;
3816  case MVT::v4i32: NewVT = MVT::v2i64; break;
3817  case MVT::v8i16: NewVT = MVT::v4i32; break;
3818  case MVT::v16i8: NewVT = MVT::v4i32; break;
3819  }
3820
3821  if (NewWidth == 2) {
3822    if (VT.isInteger())
3823      NewVT = MVT::v2i64;
3824    else
3825      NewVT = MVT::v2f64;
3826  }
3827  int Scale = NumElems / NewWidth;
3828  SmallVector<int, 8> MaskVec;
3829  for (unsigned i = 0; i < NumElems; i += Scale) {
3830    int StartIdx = -1;
3831    for (int j = 0; j < Scale; ++j) {
3832      int EltIdx = SVOp->getMaskElt(i+j);
3833      if (EltIdx < 0)
3834        continue;
3835      if (StartIdx == -1)
3836        StartIdx = EltIdx - (EltIdx % Scale);
3837      if (EltIdx != StartIdx + j)
3838        return SDValue();
3839    }
3840    if (StartIdx == -1)
3841      MaskVec.push_back(-1);
3842    else
3843      MaskVec.push_back(StartIdx / Scale);
3844  }
3845
3846  V1 = DAG.getNode(ISD::BIT_CONVERT, dl, NewVT, V1);
3847  V2 = DAG.getNode(ISD::BIT_CONVERT, dl, NewVT, V2);
3848  return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
3849}
3850
3851/// getVZextMovL - Return a zero-extending vector move low node.
3852///
3853static SDValue getVZextMovL(MVT VT, MVT OpVT,
3854                            SDValue SrcOp, SelectionDAG &DAG,
3855                            const X86Subtarget *Subtarget, DebugLoc dl) {
3856  if (VT == MVT::v2f64 || VT == MVT::v4f32) {
3857    LoadSDNode *LD = NULL;
3858    if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
3859      LD = dyn_cast<LoadSDNode>(SrcOp);
3860    if (!LD) {
3861      // movssrr and movsdrr do not clear top bits. Try to use movd, movq
3862      // instead.
3863      MVT EVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
3864      if ((EVT != MVT::i64 || Subtarget->is64Bit()) &&
3865          SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
3866          SrcOp.getOperand(0).getOpcode() == ISD::BIT_CONVERT &&
3867          SrcOp.getOperand(0).getOperand(0).getValueType() == EVT) {
3868        // PR2108
3869        OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
3870        return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
3871                           DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
3872                                       DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
3873                                                   OpVT,
3874                                                   SrcOp.getOperand(0)
3875                                                          .getOperand(0))));
3876      }
3877    }
3878  }
3879
3880  return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
3881                     DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
3882                                 DAG.getNode(ISD::BIT_CONVERT, dl,
3883                                             OpVT, SrcOp)));
3884}
3885
3886/// LowerVECTOR_SHUFFLE_4wide - Handle all 4 wide cases with a number of
3887/// shuffles.
3888static SDValue
3889LowerVECTOR_SHUFFLE_4wide(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
3890  SDValue V1 = SVOp->getOperand(0);
3891  SDValue V2 = SVOp->getOperand(1);
3892  DebugLoc dl = SVOp->getDebugLoc();
3893  MVT VT = SVOp->getValueType(0);
3894
3895  SmallVector<std::pair<int, int>, 8> Locs;
3896  Locs.resize(4);
3897  SmallVector<int, 8> Mask1(4U, -1);
3898  SmallVector<int, 8> PermMask;
3899  SVOp->getMask(PermMask);
3900
3901  unsigned NumHi = 0;
3902  unsigned NumLo = 0;
3903  for (unsigned i = 0; i != 4; ++i) {
3904    int Idx = PermMask[i];
3905    if (Idx < 0) {
3906      Locs[i] = std::make_pair(-1, -1);
3907    } else {
3908      assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
3909      if (Idx < 4) {
3910        Locs[i] = std::make_pair(0, NumLo);
3911        Mask1[NumLo] = Idx;
3912        NumLo++;
3913      } else {
3914        Locs[i] = std::make_pair(1, NumHi);
3915        if (2+NumHi < 4)
3916          Mask1[2+NumHi] = Idx;
3917        NumHi++;
3918      }
3919    }
3920  }
3921
3922  if (NumLo <= 2 && NumHi <= 2) {
3923    // If no more than two elements come from either vector. This can be
3924    // implemented with two shuffles. First shuffle gather the elements.
3925    // The second shuffle, which takes the first shuffle as both of its
3926    // vector operands, put the elements into the right order.
3927    V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
3928
3929    SmallVector<int, 8> Mask2(4U, -1);
3930
3931    for (unsigned i = 0; i != 4; ++i) {
3932      if (Locs[i].first == -1)
3933        continue;
3934      else {
3935        unsigned Idx = (i < 2) ? 0 : 4;
3936        Idx += Locs[i].first * 2 + Locs[i].second;
3937        Mask2[i] = Idx;
3938      }
3939    }
3940
3941    return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
3942  } else if (NumLo == 3 || NumHi == 3) {
3943    // Otherwise, we must have three elements from one vector, call it X, and
3944    // one element from the other, call it Y.  First, use a shufps to build an
3945    // intermediate vector with the one element from Y and the element from X
3946    // that will be in the same half in the final destination (the indexes don't
3947    // matter). Then, use a shufps to build the final vector, taking the half
3948    // containing the element from Y from the intermediate, and the other half
3949    // from X.
3950    if (NumHi == 3) {
3951      // Normalize it so the 3 elements come from V1.
3952      CommuteVectorShuffleMask(PermMask, VT);
3953      std::swap(V1, V2);
3954    }
3955
3956    // Find the element from V2.
3957    unsigned HiIndex;
3958    for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
3959      int Val = PermMask[HiIndex];
3960      if (Val < 0)
3961        continue;
3962      if (Val >= 4)
3963        break;
3964    }
3965
3966    Mask1[0] = PermMask[HiIndex];
3967    Mask1[1] = -1;
3968    Mask1[2] = PermMask[HiIndex^1];
3969    Mask1[3] = -1;
3970    V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
3971
3972    if (HiIndex >= 2) {
3973      Mask1[0] = PermMask[0];
3974      Mask1[1] = PermMask[1];
3975      Mask1[2] = HiIndex & 1 ? 6 : 4;
3976      Mask1[3] = HiIndex & 1 ? 4 : 6;
3977      return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
3978    } else {
3979      Mask1[0] = HiIndex & 1 ? 2 : 0;
3980      Mask1[1] = HiIndex & 1 ? 0 : 2;
3981      Mask1[2] = PermMask[2];
3982      Mask1[3] = PermMask[3];
3983      if (Mask1[2] >= 0)
3984        Mask1[2] += 4;
3985      if (Mask1[3] >= 0)
3986        Mask1[3] += 4;
3987      return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
3988    }
3989  }
3990
3991  // Break it into (shuffle shuffle_hi, shuffle_lo).
3992  Locs.clear();
3993  SmallVector<int,8> LoMask(4U, -1);
3994  SmallVector<int,8> HiMask(4U, -1);
3995
3996  SmallVector<int,8> *MaskPtr = &LoMask;
3997  unsigned MaskIdx = 0;
3998  unsigned LoIdx = 0;
3999  unsigned HiIdx = 2;
4000  for (unsigned i = 0; i != 4; ++i) {
4001    if (i == 2) {
4002      MaskPtr = &HiMask;
4003      MaskIdx = 1;
4004      LoIdx = 0;
4005      HiIdx = 2;
4006    }
4007    int Idx = PermMask[i];
4008    if (Idx < 0) {
4009      Locs[i] = std::make_pair(-1, -1);
4010    } else if (Idx < 4) {
4011      Locs[i] = std::make_pair(MaskIdx, LoIdx);
4012      (*MaskPtr)[LoIdx] = Idx;
4013      LoIdx++;
4014    } else {
4015      Locs[i] = std::make_pair(MaskIdx, HiIdx);
4016      (*MaskPtr)[HiIdx] = Idx;
4017      HiIdx++;
4018    }
4019  }
4020
4021  SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
4022  SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
4023  SmallVector<int, 8> MaskOps;
4024  for (unsigned i = 0; i != 4; ++i) {
4025    if (Locs[i].first == -1) {
4026      MaskOps.push_back(-1);
4027    } else {
4028      unsigned Idx = Locs[i].first * 4 + Locs[i].second;
4029      MaskOps.push_back(Idx);
4030    }
4031  }
4032  return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
4033}
4034
4035SDValue
4036X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) {
4037  ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
4038  SDValue V1 = Op.getOperand(0);
4039  SDValue V2 = Op.getOperand(1);
4040  MVT VT = Op.getValueType();
4041  DebugLoc dl = Op.getDebugLoc();
4042  unsigned NumElems = VT.getVectorNumElements();
4043  bool isMMX = VT.getSizeInBits() == 64;
4044  bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
4045  bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
4046  bool V1IsSplat = false;
4047  bool V2IsSplat = false;
4048
4049  if (isZeroShuffle(SVOp))
4050    return getZeroVector(VT, Subtarget->hasSSE2(), DAG, dl);
4051
4052  // Promote splats to v4f32.
4053  if (SVOp->isSplat()) {
4054    if (isMMX || NumElems < 4)
4055      return Op;
4056    return PromoteSplat(SVOp, DAG, Subtarget->hasSSE2());
4057  }
4058
4059  // If the shuffle can be profitably rewritten as a narrower shuffle, then
4060  // do it!
4061  if (VT == MVT::v8i16 || VT == MVT::v16i8) {
4062    SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, *this, dl);
4063    if (NewOp.getNode())
4064      return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
4065                         LowerVECTOR_SHUFFLE(NewOp, DAG));
4066  } else if ((VT == MVT::v4i32 || (VT == MVT::v4f32 && Subtarget->hasSSE2()))) {
4067    // FIXME: Figure out a cleaner way to do this.
4068    // Try to make use of movq to zero out the top part.
4069    if (ISD::isBuildVectorAllZeros(V2.getNode())) {
4070      SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, *this, dl);
4071      if (NewOp.getNode()) {
4072        if (isCommutedMOVL(cast<ShuffleVectorSDNode>(NewOp), true, false))
4073          return getVZextMovL(VT, NewOp.getValueType(), NewOp.getOperand(0),
4074                              DAG, Subtarget, dl);
4075      }
4076    } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
4077      SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, *this, dl);
4078      if (NewOp.getNode() && X86::isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)))
4079        return getVZextMovL(VT, NewOp.getValueType(), NewOp.getOperand(1),
4080                            DAG, Subtarget, dl);
4081    }
4082  }
4083
4084  if (X86::isPSHUFDMask(SVOp))
4085    return Op;
4086
4087  // Check if this can be converted into a logical shift.
4088  bool isLeft = false;
4089  unsigned ShAmt = 0;
4090  SDValue ShVal;
4091  bool isShift = getSubtarget()->hasSSE2() &&
4092  isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
4093  if (isShift && ShVal.hasOneUse()) {
4094    // If the shifted value has multiple uses, it may be cheaper to use
4095    // v_set0 + movlhps or movhlps, etc.
4096    MVT EVT = VT.getVectorElementType();
4097    ShAmt *= EVT.getSizeInBits();
4098    return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
4099  }
4100
4101  if (X86::isMOVLMask(SVOp)) {
4102    if (V1IsUndef)
4103      return V2;
4104    if (ISD::isBuildVectorAllZeros(V1.getNode()))
4105      return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
4106    if (!isMMX)
4107      return Op;
4108  }
4109
4110  // FIXME: fold these into legal mask.
4111  if (!isMMX && (X86::isMOVSHDUPMask(SVOp) ||
4112                 X86::isMOVSLDUPMask(SVOp) ||
4113                 X86::isMOVHLPSMask(SVOp) ||
4114                 X86::isMOVHPMask(SVOp) ||
4115                 X86::isMOVLPMask(SVOp)))
4116    return Op;
4117
4118  if (ShouldXformToMOVHLPS(SVOp) ||
4119      ShouldXformToMOVLP(V1.getNode(), V2.getNode(), SVOp))
4120    return CommuteVectorShuffle(SVOp, DAG);
4121
4122  if (isShift) {
4123    // No better options. Use a vshl / vsrl.
4124    MVT EVT = VT.getVectorElementType();
4125    ShAmt *= EVT.getSizeInBits();
4126    return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
4127  }
4128
4129  bool Commuted = false;
4130  // FIXME: This should also accept a bitcast of a splat?  Be careful, not
4131  // 1,1,1,1 -> v8i16 though.
4132  V1IsSplat = isSplatVector(V1.getNode());
4133  V2IsSplat = isSplatVector(V2.getNode());
4134
4135  // Canonicalize the splat or undef, if present, to be on the RHS.
4136  if ((V1IsSplat || V1IsUndef) && !(V2IsSplat || V2IsUndef)) {
4137    Op = CommuteVectorShuffle(SVOp, DAG);
4138    SVOp = cast<ShuffleVectorSDNode>(Op);
4139    V1 = SVOp->getOperand(0);
4140    V2 = SVOp->getOperand(1);
4141    std::swap(V1IsSplat, V2IsSplat);
4142    std::swap(V1IsUndef, V2IsUndef);
4143    Commuted = true;
4144  }
4145
4146  if (isCommutedMOVL(SVOp, V2IsSplat, V2IsUndef)) {
4147    // Shuffling low element of v1 into undef, just return v1.
4148    if (V2IsUndef)
4149      return V1;
4150    // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
4151    // the instruction selector will not match, so get a canonical MOVL with
4152    // swapped operands to undo the commute.
4153    return getMOVL(DAG, dl, VT, V2, V1);
4154  }
4155
4156  if (X86::isUNPCKL_v_undef_Mask(SVOp) ||
4157      X86::isUNPCKH_v_undef_Mask(SVOp) ||
4158      X86::isUNPCKLMask(SVOp) ||
4159      X86::isUNPCKHMask(SVOp))
4160    return Op;
4161
4162  if (V2IsSplat) {
4163    // Normalize mask so all entries that point to V2 points to its first
4164    // element then try to match unpck{h|l} again. If match, return a
4165    // new vector_shuffle with the corrected mask.
4166    SDValue NewMask = NormalizeMask(SVOp, DAG);
4167    ShuffleVectorSDNode *NSVOp = cast<ShuffleVectorSDNode>(NewMask);
4168    if (NSVOp != SVOp) {
4169      if (X86::isUNPCKLMask(NSVOp, true)) {
4170        return NewMask;
4171      } else if (X86::isUNPCKHMask(NSVOp, true)) {
4172        return NewMask;
4173      }
4174    }
4175  }
4176
4177  if (Commuted) {
4178    // Commute is back and try unpck* again.
4179    // FIXME: this seems wrong.
4180    SDValue NewOp = CommuteVectorShuffle(SVOp, DAG);
4181    ShuffleVectorSDNode *NewSVOp = cast<ShuffleVectorSDNode>(NewOp);
4182    if (X86::isUNPCKL_v_undef_Mask(NewSVOp) ||
4183        X86::isUNPCKH_v_undef_Mask(NewSVOp) ||
4184        X86::isUNPCKLMask(NewSVOp) ||
4185        X86::isUNPCKHMask(NewSVOp))
4186      return NewOp;
4187  }
4188
4189  // FIXME: for mmx, bitcast v2i32 to v4i16 for shuffle.
4190
4191  // Normalize the node to match x86 shuffle ops if needed
4192  if (!isMMX && V2.getOpcode() != ISD::UNDEF && isCommutedSHUFP(SVOp))
4193    return CommuteVectorShuffle(SVOp, DAG);
4194
4195  // Check for legal shuffle and return?
4196  SmallVector<int, 16> PermMask;
4197  SVOp->getMask(PermMask);
4198  if (isShuffleMaskLegal(PermMask, VT))
4199    return Op;
4200
4201  // Handle v8i16 specifically since SSE can do byte extraction and insertion.
4202  if (VT == MVT::v8i16) {
4203    SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(SVOp, DAG, *this);
4204    if (NewOp.getNode())
4205      return NewOp;
4206  }
4207
4208  if (VT == MVT::v16i8) {
4209    SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, DAG, *this);
4210    if (NewOp.getNode())
4211      return NewOp;
4212  }
4213
4214  // Handle all 4 wide cases with a number of shuffles except for MMX.
4215  if (NumElems == 4 && !isMMX)
4216    return LowerVECTOR_SHUFFLE_4wide(SVOp, DAG);
4217
4218  return SDValue();
4219}
4220
4221SDValue
4222X86TargetLowering::LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op,
4223                                                SelectionDAG &DAG) {
4224  MVT VT = Op.getValueType();
4225  DebugLoc dl = Op.getDebugLoc();
4226  if (VT.getSizeInBits() == 8) {
4227    SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
4228                                    Op.getOperand(0), Op.getOperand(1));
4229    SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
4230                                    DAG.getValueType(VT));
4231    return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
4232  } else if (VT.getSizeInBits() == 16) {
4233    unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
4234    // If Idx is 0, it's cheaper to do a move instead of a pextrw.
4235    if (Idx == 0)
4236      return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
4237                         DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
4238                                     DAG.getNode(ISD::BIT_CONVERT, dl,
4239                                                 MVT::v4i32,
4240                                                 Op.getOperand(0)),
4241                                     Op.getOperand(1)));
4242    SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
4243                                    Op.getOperand(0), Op.getOperand(1));
4244    SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
4245                                    DAG.getValueType(VT));
4246    return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
4247  } else if (VT == MVT::f32) {
4248    // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
4249    // the result back to FR32 register. It's only worth matching if the
4250    // result has a single use which is a store or a bitcast to i32.  And in
4251    // the case of a store, it's not worth it if the index is a constant 0,
4252    // because a MOVSSmr can be used instead, which is smaller and faster.
4253    if (!Op.hasOneUse())
4254      return SDValue();
4255    SDNode *User = *Op.getNode()->use_begin();
4256    if ((User->getOpcode() != ISD::STORE ||
4257         (isa<ConstantSDNode>(Op.getOperand(1)) &&
4258          cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
4259        (User->getOpcode() != ISD::BIT_CONVERT ||
4260         User->getValueType(0) != MVT::i32))
4261      return SDValue();
4262    SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
4263                                  DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v4i32,
4264                                              Op.getOperand(0)),
4265                                              Op.getOperand(1));
4266    return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::f32, Extract);
4267  } else if (VT == MVT::i32) {
4268    // ExtractPS works with constant index.
4269    if (isa<ConstantSDNode>(Op.getOperand(1)))
4270      return Op;
4271  }
4272  return SDValue();
4273}
4274
4275
4276SDValue
4277X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
4278  if (!isa<ConstantSDNode>(Op.getOperand(1)))
4279    return SDValue();
4280
4281  if (Subtarget->hasSSE41()) {
4282    SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
4283    if (Res.getNode())
4284      return Res;
4285  }
4286
4287  MVT VT = Op.getValueType();
4288  DebugLoc dl = Op.getDebugLoc();
4289  // TODO: handle v16i8.
4290  if (VT.getSizeInBits() == 16) {
4291    SDValue Vec = Op.getOperand(0);
4292    unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
4293    if (Idx == 0)
4294      return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
4295                         DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
4296                                     DAG.getNode(ISD::BIT_CONVERT, dl,
4297                                                 MVT::v4i32, Vec),
4298                                     Op.getOperand(1)));
4299    // Transform it so it match pextrw which produces a 32-bit result.
4300    MVT EVT = (MVT::SimpleValueType)(VT.getSimpleVT()+1);
4301    SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EVT,
4302                                    Op.getOperand(0), Op.getOperand(1));
4303    SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, EVT, Extract,
4304                                    DAG.getValueType(VT));
4305    return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
4306  } else if (VT.getSizeInBits() == 32) {
4307    unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
4308    if (Idx == 0)
4309      return Op;
4310
4311    // SHUFPS the element to the lowest double word, then movss.
4312    int Mask[4] = { Idx, -1, -1, -1 };
4313    MVT VVT = Op.getOperand(0).getValueType();
4314    SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
4315                                       DAG.getUNDEF(VVT), Mask);
4316    return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
4317                       DAG.getIntPtrConstant(0));
4318  } else if (VT.getSizeInBits() == 64) {
4319    // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
4320    // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
4321    //        to match extract_elt for f64.
4322    unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
4323    if (Idx == 0)
4324      return Op;
4325
4326    // UNPCKHPD the element to the lowest double word, then movsd.
4327    // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
4328    // to a f64mem, the whole operation is folded into a single MOVHPDmr.
4329    int Mask[2] = { 1, -1 };
4330    MVT VVT = Op.getOperand(0).getValueType();
4331    SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
4332                                       DAG.getUNDEF(VVT), Mask);
4333    return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
4334                       DAG.getIntPtrConstant(0));
4335  }
4336
4337  return SDValue();
4338}
4339
4340SDValue
4341X86TargetLowering::LowerINSERT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG){
4342  MVT VT = Op.getValueType();
4343  MVT EVT = VT.getVectorElementType();
4344  DebugLoc dl = Op.getDebugLoc();
4345
4346  SDValue N0 = Op.getOperand(0);
4347  SDValue N1 = Op.getOperand(1);
4348  SDValue N2 = Op.getOperand(2);
4349
4350  if ((EVT.getSizeInBits() == 8 || EVT.getSizeInBits() == 16) &&
4351      isa<ConstantSDNode>(N2)) {
4352    unsigned Opc = (EVT.getSizeInBits() == 8) ? X86ISD::PINSRB
4353                                              : X86ISD::PINSRW;
4354    // Transform it so it match pinsr{b,w} which expects a GR32 as its second
4355    // argument.
4356    if (N1.getValueType() != MVT::i32)
4357      N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
4358    if (N2.getValueType() != MVT::i32)
4359      N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
4360    return DAG.getNode(Opc, dl, VT, N0, N1, N2);
4361  } else if (EVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
4362    // Bits [7:6] of the constant are the source select.  This will always be
4363    //  zero here.  The DAG Combiner may combine an extract_elt index into these
4364    //  bits.  For example (insert (extract, 3), 2) could be matched by putting
4365    //  the '3' into bits [7:6] of X86ISD::INSERTPS.
4366    // Bits [5:4] of the constant are the destination select.  This is the
4367    //  value of the incoming immediate.
4368    // Bits [3:0] of the constant are the zero mask.  The DAG Combiner may
4369    //   combine either bitwise AND or insert of float 0.0 to set these bits.
4370    N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
4371    return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
4372  } else if (EVT == MVT::i32) {
4373    // InsertPS works with constant index.
4374    if (isa<ConstantSDNode>(N2))
4375      return Op;
4376  }
4377  return SDValue();
4378}
4379
4380SDValue
4381X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
4382  MVT VT = Op.getValueType();
4383  MVT EVT = VT.getVectorElementType();
4384
4385  if (Subtarget->hasSSE41())
4386    return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
4387
4388  if (EVT == MVT::i8)
4389    return SDValue();
4390
4391  DebugLoc dl = Op.getDebugLoc();
4392  SDValue N0 = Op.getOperand(0);
4393  SDValue N1 = Op.getOperand(1);
4394  SDValue N2 = Op.getOperand(2);
4395
4396  if (EVT.getSizeInBits() == 16 && isa<ConstantSDNode>(N2)) {
4397    // Transform it so it match pinsrw which expects a 16-bit value in a GR32
4398    // as its second argument.
4399    if (N1.getValueType() != MVT::i32)
4400      N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
4401    if (N2.getValueType() != MVT::i32)
4402      N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
4403    return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
4404  }
4405  return SDValue();
4406}
4407
4408SDValue
4409X86TargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
4410  DebugLoc dl = Op.getDebugLoc();
4411  if (Op.getValueType() == MVT::v2f32)
4412    return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2f32,
4413                       DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i32,
4414                                   DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32,
4415                                               Op.getOperand(0))));
4416
4417  SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
4418  MVT VT = MVT::v2i32;
4419  switch (Op.getValueType().getSimpleVT()) {
4420  default: break;
4421  case MVT::v16i8:
4422  case MVT::v8i16:
4423    VT = MVT::v4i32;
4424    break;
4425  }
4426  return DAG.getNode(ISD::BIT_CONVERT, dl, Op.getValueType(),
4427                     DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, AnyExt));
4428}
4429
4430// ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
4431// their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
4432// one of the above mentioned nodes. It has to be wrapped because otherwise
4433// Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
4434// be used to form addressing mode. These wrapped nodes will be selected
4435// into MOV32ri.
4436SDValue
4437X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) {
4438  ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
4439
4440  // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
4441  // global base reg.
4442  unsigned char OpFlag = 0;
4443  unsigned WrapperKind = X86ISD::Wrapper;
4444  if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
4445    if (Subtarget->isPICStyleStub())
4446      OpFlag = X86II::MO_PIC_BASE_OFFSET;
4447    else if (Subtarget->isPICStyleGOT())
4448      OpFlag = X86II::MO_GOTOFF;
4449    else if (Subtarget->isPICStyleRIPRel() &&
4450             getTargetMachine().getCodeModel() == CodeModel::Small)
4451      WrapperKind = X86ISD::WrapperRIP;
4452  }
4453
4454  SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
4455                                             CP->getAlignment(),
4456                                             CP->getOffset(), OpFlag);
4457  DebugLoc DL = CP->getDebugLoc();
4458  Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
4459  // With PIC, the address is actually $g + Offset.
4460  if (OpFlag) {
4461    Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
4462                         DAG.getNode(X86ISD::GlobalBaseReg,
4463                                     DebugLoc::getUnknownLoc(), getPointerTy()),
4464                         Result);
4465  }
4466
4467  return Result;
4468}
4469
4470SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) {
4471  JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
4472
4473  // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
4474  // global base reg.
4475  unsigned char OpFlag = 0;
4476  unsigned WrapperKind = X86ISD::Wrapper;
4477  if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
4478    if (Subtarget->isPICStyleStub())
4479      OpFlag = X86II::MO_PIC_BASE_OFFSET;
4480    else if (Subtarget->isPICStyleGOT())
4481      OpFlag = X86II::MO_GOTOFF;
4482    else if (Subtarget->isPICStyleRIPRel())
4483      WrapperKind = X86ISD::WrapperRIP;
4484  }
4485
4486  SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
4487                                          OpFlag);
4488  DebugLoc DL = JT->getDebugLoc();
4489  Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
4490
4491  // With PIC, the address is actually $g + Offset.
4492  if (OpFlag) {
4493    Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
4494                         DAG.getNode(X86ISD::GlobalBaseReg,
4495                                     DebugLoc::getUnknownLoc(), getPointerTy()),
4496                         Result);
4497  }
4498
4499  return Result;
4500}
4501
4502SDValue
4503X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) {
4504  const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
4505
4506  // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
4507  // global base reg.
4508  unsigned char OpFlag = 0;
4509  unsigned WrapperKind = X86ISD::Wrapper;
4510  if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
4511    if (Subtarget->isPICStyleStub())
4512      OpFlag = X86II::MO_PIC_BASE_OFFSET;
4513    else if (Subtarget->isPICStyleGOT())
4514      OpFlag = X86II::MO_GOTOFF;
4515    else if (Subtarget->isPICStyleRIPRel())
4516      WrapperKind = X86ISD::WrapperRIP;
4517  }
4518
4519  SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
4520
4521  DebugLoc DL = Op.getDebugLoc();
4522  Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
4523
4524
4525  // With PIC, the address is actually $g + Offset.
4526  if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
4527      !Subtarget->isPICStyleRIPRel()) {
4528    Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
4529                         DAG.getNode(X86ISD::GlobalBaseReg,
4530                                     DebugLoc::getUnknownLoc(),
4531                                     getPointerTy()),
4532                         Result);
4533  }
4534
4535  return Result;
4536}
4537
4538SDValue
4539X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, DebugLoc dl,
4540                                      int64_t Offset,
4541                                      SelectionDAG &DAG) const {
4542  bool IsPic = getTargetMachine().getRelocationModel() == Reloc::PIC_;
4543  bool ExtraLoadRequired =
4544    Subtarget->GVRequiresExtraLoad(GV, getTargetMachine(), false);
4545
4546  // Create the TargetGlobalAddress node, folding in the constant
4547  // offset if it is legal.
4548  SDValue Result;
4549  if (!IsPic && !ExtraLoadRequired && isInt32(Offset)) {
4550    Result = DAG.getTargetGlobalAddress(GV, getPointerTy(), Offset);
4551    Offset = 0;
4552  } else {
4553    unsigned char OpFlags = 0;
4554
4555    if (Subtarget->isPICStyleRIPRel() &&
4556        getTargetMachine().getRelocationModel() != Reloc::Static) {
4557      if (ExtraLoadRequired)
4558        OpFlags = X86II::MO_GOTPCREL;
4559    } else if (Subtarget->isPICStyleGOT() &&
4560               getTargetMachine().getRelocationModel() == Reloc::PIC_) {
4561      if (ExtraLoadRequired)
4562        OpFlags = X86II::MO_GOT;
4563      else
4564        OpFlags = X86II::MO_GOTOFF;
4565    }
4566
4567    Result = DAG.getTargetGlobalAddress(GV, getPointerTy(), 0, OpFlags);
4568  }
4569
4570  if (Subtarget->isPICStyleRIPRel() &&
4571      getTargetMachine().getCodeModel() == CodeModel::Small)
4572    Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
4573  else
4574    Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
4575
4576  // With PIC, the address is actually $g + Offset.
4577  if (IsPic && !Subtarget->isPICStyleRIPRel()) {
4578    Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
4579                         DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
4580                         Result);
4581  }
4582
4583  // For Darwin & Mingw32, external and weak symbols are indirect, so we want to
4584  // load the value at address GV, not the value of GV itself. This means that
4585  // the GlobalAddress must be in the base or index register of the address, not
4586  // the GV offset field. Platform check is inside GVRequiresExtraLoad() call
4587  // The same applies for external symbols during PIC codegen
4588  if (ExtraLoadRequired)
4589    Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
4590                         PseudoSourceValue::getGOT(), 0);
4591
4592  // If there was a non-zero offset that we didn't fold, create an explicit
4593  // addition for it.
4594  if (Offset != 0)
4595    Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
4596                         DAG.getConstant(Offset, getPointerTy()));
4597
4598  return Result;
4599}
4600
4601SDValue
4602X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) {
4603  const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
4604  int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
4605  return LowerGlobalAddress(GV, Op.getDebugLoc(), Offset, DAG);
4606}
4607
4608static SDValue
4609GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
4610           SDValue *InFlag, const MVT PtrVT, unsigned ReturnReg,
4611           unsigned char OperandFlags) {
4612  SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
4613  DebugLoc dl = GA->getDebugLoc();
4614  SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(),
4615                                           GA->getValueType(0),
4616                                           GA->getOffset(),
4617                                           OperandFlags);
4618  if (InFlag) {
4619    SDValue Ops[] = { Chain,  TGA, *InFlag };
4620    Chain = DAG.getNode(X86ISD::TLSADDR, dl, NodeTys, Ops, 3);
4621  } else {
4622    SDValue Ops[]  = { Chain, TGA };
4623    Chain = DAG.getNode(X86ISD::TLSADDR, dl, NodeTys, Ops, 2);
4624  }
4625  SDValue Flag = Chain.getValue(1);
4626  return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
4627}
4628
4629// Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
4630static SDValue
4631LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
4632                                const MVT PtrVT) {
4633  SDValue InFlag;
4634  DebugLoc dl = GA->getDebugLoc();  // ? function entry point might be better
4635  SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
4636                                     DAG.getNode(X86ISD::GlobalBaseReg,
4637                                                 DebugLoc::getUnknownLoc(),
4638                                                 PtrVT), InFlag);
4639  InFlag = Chain.getValue(1);
4640
4641  return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
4642}
4643
4644// Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
4645static SDValue
4646LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
4647                                const MVT PtrVT) {
4648  return GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT,
4649                    X86::RAX, X86II::MO_TLSGD);
4650}
4651
4652// Lower ISD::GlobalTLSAddress using the "initial exec" (for no-pic) or
4653// "local exec" model.
4654static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
4655                                   const MVT PtrVT, TLSModel::Model model,
4656                                   bool is64Bit) {
4657  DebugLoc dl = GA->getDebugLoc();
4658  // Get the Thread Pointer
4659  SDValue Base = DAG.getNode(X86ISD::SegmentBaseAddress,
4660                             DebugLoc::getUnknownLoc(), PtrVT,
4661                             DAG.getRegister(is64Bit? X86::FS : X86::GS,
4662                                             MVT::i32));
4663
4664  SDValue ThreadPointer = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Base,
4665                                      NULL, 0);
4666
4667  unsigned char OperandFlags = 0;
4668  // Most TLS accesses are not RIP relative, even on x86-64.  One exception is
4669  // initialexec.
4670  unsigned WrapperKind = X86ISD::Wrapper;
4671  if (model == TLSModel::LocalExec) {
4672    OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
4673  } else if (is64Bit) {
4674    assert(model == TLSModel::InitialExec);
4675    OperandFlags = X86II::MO_GOTTPOFF;
4676    WrapperKind = X86ISD::WrapperRIP;
4677  } else {
4678    assert(model == TLSModel::InitialExec);
4679    OperandFlags = X86II::MO_INDNTPOFF;
4680  }
4681
4682  // emit "addl x@ntpoff,%eax" (local exec) or "addl x@indntpoff,%eax" (initial
4683  // exec)
4684  SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), GA->getValueType(0),
4685                                           GA->getOffset(), OperandFlags);
4686  SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
4687
4688  if (model == TLSModel::InitialExec)
4689    Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
4690                         PseudoSourceValue::getGOT(), 0);
4691
4692  // The address of the thread local variable is the add of the thread
4693  // pointer with the offset of the variable.
4694  return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
4695}
4696
4697SDValue
4698X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) {
4699  // TODO: implement the "local dynamic" model
4700  // TODO: implement the "initial exec"model for pic executables
4701  assert(Subtarget->isTargetELF() &&
4702         "TLS not implemented for non-ELF targets");
4703  GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
4704  const GlobalValue *GV = GA->getGlobal();
4705
4706  // If GV is an alias then use the aliasee for determining
4707  // thread-localness.
4708  if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
4709    GV = GA->resolveAliasedGlobal(false);
4710
4711  TLSModel::Model model = getTLSModel(GV,
4712                                      getTargetMachine().getRelocationModel());
4713
4714  switch (model) {
4715  case TLSModel::GeneralDynamic:
4716  case TLSModel::LocalDynamic: // not implemented
4717    if (Subtarget->is64Bit())
4718      return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
4719    return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
4720
4721  case TLSModel::InitialExec:
4722  case TLSModel::LocalExec:
4723    return LowerToTLSExecModel(GA, DAG, getPointerTy(), model,
4724                               Subtarget->is64Bit());
4725  }
4726
4727  assert(0 && "Unreachable");
4728  return SDValue();
4729}
4730
4731
4732/// LowerShift - Lower SRA_PARTS and friends, which return two i32 values and
4733/// take a 2 x i32 value to shift plus a shift amount.
4734SDValue X86TargetLowering::LowerShift(SDValue Op, SelectionDAG &DAG) {
4735  assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4736  MVT VT = Op.getValueType();
4737  unsigned VTBits = VT.getSizeInBits();
4738  DebugLoc dl = Op.getDebugLoc();
4739  bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
4740  SDValue ShOpLo = Op.getOperand(0);
4741  SDValue ShOpHi = Op.getOperand(1);
4742  SDValue ShAmt  = Op.getOperand(2);
4743  SDValue Tmp1 = isSRA ?
4744    DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
4745                DAG.getConstant(VTBits - 1, MVT::i8)) :
4746    DAG.getConstant(0, VT);
4747
4748  SDValue Tmp2, Tmp3;
4749  if (Op.getOpcode() == ISD::SHL_PARTS) {
4750    Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
4751    Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
4752  } else {
4753    Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
4754    Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, ShAmt);
4755  }
4756
4757  SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
4758                                  DAG.getConstant(VTBits, MVT::i8));
4759  SDValue Cond = DAG.getNode(X86ISD::CMP, dl, VT,
4760                               AndNode, DAG.getConstant(0, MVT::i8));
4761
4762  SDValue Hi, Lo;
4763  SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
4764  SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
4765  SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
4766
4767  if (Op.getOpcode() == ISD::SHL_PARTS) {
4768    Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
4769    Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
4770  } else {
4771    Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
4772    Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
4773  }
4774
4775  SDValue Ops[2] = { Lo, Hi };
4776  return DAG.getMergeValues(Ops, 2, dl);
4777}
4778
4779SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
4780  MVT SrcVT = Op.getOperand(0).getValueType();
4781
4782  if (SrcVT.isVector()) {
4783    if (SrcVT == MVT::v2i32 && Op.getValueType() == MVT::v2f64) {
4784      return Op;
4785    }
4786    return SDValue();
4787  }
4788
4789  assert(SrcVT.getSimpleVT() <= MVT::i64 && SrcVT.getSimpleVT() >= MVT::i16 &&
4790         "Unknown SINT_TO_FP to lower!");
4791
4792  // These are really Legal; return the operand so the caller accepts it as
4793  // Legal.
4794  if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
4795    return Op;
4796  if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
4797      Subtarget->is64Bit()) {
4798    return Op;
4799  }
4800
4801  DebugLoc dl = Op.getDebugLoc();
4802  unsigned Size = SrcVT.getSizeInBits()/8;
4803  MachineFunction &MF = DAG.getMachineFunction();
4804  int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size);
4805  SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
4806  SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
4807                               StackSlot,
4808                               PseudoSourceValue::getFixedStack(SSFI), 0);
4809  return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
4810}
4811
4812SDValue X86TargetLowering::BuildFILD(SDValue Op, MVT SrcVT, SDValue Chain,
4813                                     SDValue StackSlot,
4814                                     SelectionDAG &DAG) {
4815  // Build the FILD
4816  DebugLoc dl = Op.getDebugLoc();
4817  SDVTList Tys;
4818  bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
4819  if (useSSE)
4820    Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Flag);
4821  else
4822    Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
4823  SmallVector<SDValue, 8> Ops;
4824  Ops.push_back(Chain);
4825  Ops.push_back(StackSlot);
4826  Ops.push_back(DAG.getValueType(SrcVT));
4827  SDValue Result = DAG.getNode(useSSE ? X86ISD::FILD_FLAG : X86ISD::FILD, dl,
4828                                 Tys, &Ops[0], Ops.size());
4829
4830  if (useSSE) {
4831    Chain = Result.getValue(1);
4832    SDValue InFlag = Result.getValue(2);
4833
4834    // FIXME: Currently the FST is flagged to the FILD_FLAG. This
4835    // shouldn't be necessary except that RFP cannot be live across
4836    // multiple blocks. When stackifier is fixed, they can be uncoupled.
4837    MachineFunction &MF = DAG.getMachineFunction();
4838    int SSFI = MF.getFrameInfo()->CreateStackObject(8, 8);
4839    SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
4840    Tys = DAG.getVTList(MVT::Other);
4841    SmallVector<SDValue, 8> Ops;
4842    Ops.push_back(Chain);
4843    Ops.push_back(Result);
4844    Ops.push_back(StackSlot);
4845    Ops.push_back(DAG.getValueType(Op.getValueType()));
4846    Ops.push_back(InFlag);
4847    Chain = DAG.getNode(X86ISD::FST, dl, Tys, &Ops[0], Ops.size());
4848    Result = DAG.getLoad(Op.getValueType(), dl, Chain, StackSlot,
4849                         PseudoSourceValue::getFixedStack(SSFI), 0);
4850  }
4851
4852  return Result;
4853}
4854
4855// LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
4856SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op, SelectionDAG &DAG) {
4857  // This algorithm is not obvious. Here it is in C code, more or less:
4858  /*
4859    double uint64_to_double( uint32_t hi, uint32_t lo ) {
4860      static const __m128i exp = { 0x4330000045300000ULL, 0 };
4861      static const __m128d bias = { 0x1.0p84, 0x1.0p52 };
4862
4863      // Copy ints to xmm registers.
4864      __m128i xh = _mm_cvtsi32_si128( hi );
4865      __m128i xl = _mm_cvtsi32_si128( lo );
4866
4867      // Combine into low half of a single xmm register.
4868      __m128i x = _mm_unpacklo_epi32( xh, xl );
4869      __m128d d;
4870      double sd;
4871
4872      // Merge in appropriate exponents to give the integer bits the right
4873      // magnitude.
4874      x = _mm_unpacklo_epi32( x, exp );
4875
4876      // Subtract away the biases to deal with the IEEE-754 double precision
4877      // implicit 1.
4878      d = _mm_sub_pd( (__m128d) x, bias );
4879
4880      // All conversions up to here are exact. The correctly rounded result is
4881      // calculated using the current rounding mode using the following
4882      // horizontal add.
4883      d = _mm_add_sd( d, _mm_unpackhi_pd( d, d ) );
4884      _mm_store_sd( &sd, d );   // Because we are returning doubles in XMM, this
4885                                // store doesn't really need to be here (except
4886                                // maybe to zero the other double)
4887      return sd;
4888    }
4889  */
4890
4891  DebugLoc dl = Op.getDebugLoc();
4892
4893  // Build some magic constants.
4894  std::vector<Constant*> CV0;
4895  CV0.push_back(ConstantInt::get(APInt(32, 0x45300000)));
4896  CV0.push_back(ConstantInt::get(APInt(32, 0x43300000)));
4897  CV0.push_back(ConstantInt::get(APInt(32, 0)));
4898  CV0.push_back(ConstantInt::get(APInt(32, 0)));
4899  Constant *C0 = ConstantVector::get(CV0);
4900  SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
4901
4902  std::vector<Constant*> CV1;
4903  CV1.push_back(ConstantFP::get(APFloat(APInt(64, 0x4530000000000000ULL))));
4904  CV1.push_back(ConstantFP::get(APFloat(APInt(64, 0x4330000000000000ULL))));
4905  Constant *C1 = ConstantVector::get(CV1);
4906  SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
4907
4908  SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
4909                            DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
4910                                        Op.getOperand(0),
4911                                        DAG.getIntPtrConstant(1)));
4912  SDValue XR2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
4913                            DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
4914                                        Op.getOperand(0),
4915                                        DAG.getIntPtrConstant(0)));
4916  SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32, XR1, XR2);
4917  SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
4918                              PseudoSourceValue::getConstantPool(), 0,
4919                              false, 16);
4920  SDValue Unpck2 = getUnpackl(DAG, dl, MVT::v4i32, Unpck1, CLod0);
4921  SDValue XR2F = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2f64, Unpck2);
4922  SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
4923                              PseudoSourceValue::getConstantPool(), 0,
4924                              false, 16);
4925  SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
4926
4927  // Add the halves; easiest way is to swap them into another reg first.
4928  int ShufMask[2] = { 1, -1 };
4929  SDValue Shuf = DAG.getVectorShuffle(MVT::v2f64, dl, Sub,
4930                                      DAG.getUNDEF(MVT::v2f64), ShufMask);
4931  SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::v2f64, Shuf, Sub);
4932  return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Add,
4933                     DAG.getIntPtrConstant(0));
4934}
4935
4936// LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
4937SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op, SelectionDAG &DAG) {
4938  DebugLoc dl = Op.getDebugLoc();
4939  // FP constant to bias correct the final result.
4940  SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
4941                                   MVT::f64);
4942
4943  // Load the 32-bit value into an XMM register.
4944  SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
4945                             DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
4946                                         Op.getOperand(0),
4947                                         DAG.getIntPtrConstant(0)));
4948
4949  Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
4950                     DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2f64, Load),
4951                     DAG.getIntPtrConstant(0));
4952
4953  // Or the load with the bias.
4954  SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
4955                           DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64,
4956                                       DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
4957                                                   MVT::v2f64, Load)),
4958                           DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64,
4959                                       DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
4960                                                   MVT::v2f64, Bias)));
4961  Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
4962                   DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2f64, Or),
4963                   DAG.getIntPtrConstant(0));
4964
4965  // Subtract the bias.
4966  SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
4967
4968  // Handle final rounding.
4969  MVT DestVT = Op.getValueType();
4970
4971  if (DestVT.bitsLT(MVT::f64)) {
4972    return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
4973                       DAG.getIntPtrConstant(0));
4974  } else if (DestVT.bitsGT(MVT::f64)) {
4975    return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
4976  }
4977
4978  // Handle final rounding.
4979  return Sub;
4980}
4981
4982SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
4983  SDValue N0 = Op.getOperand(0);
4984  DebugLoc dl = Op.getDebugLoc();
4985
4986  // Now not UINT_TO_FP is legal (it's marked custom), dag combiner won't
4987  // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
4988  // the optimization here.
4989  if (DAG.SignBitIsZero(N0))
4990    return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
4991
4992  MVT SrcVT = N0.getValueType();
4993  if (SrcVT == MVT::i64) {
4994    // We only handle SSE2 f64 target here; caller can expand the rest.
4995    if (Op.getValueType() != MVT::f64 || !X86ScalarSSEf64)
4996      return SDValue();
4997
4998    return LowerUINT_TO_FP_i64(Op, DAG);
4999  } else if (SrcVT == MVT::i32 && X86ScalarSSEf64) {
5000    return LowerUINT_TO_FP_i32(Op, DAG);
5001  }
5002
5003  assert(SrcVT == MVT::i32 && "Unknown UINT_TO_FP to lower!");
5004
5005  // Make a 64-bit buffer, and use it to build an FILD.
5006  SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
5007  SDValue WordOff = DAG.getConstant(4, getPointerTy());
5008  SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
5009                                   getPointerTy(), StackSlot, WordOff);
5010  SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
5011                                StackSlot, NULL, 0);
5012  SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
5013                                OffsetSlot, NULL, 0);
5014  return BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
5015}
5016
5017std::pair<SDValue,SDValue> X86TargetLowering::
5018FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG, bool IsSigned) {
5019  DebugLoc dl = Op.getDebugLoc();
5020
5021  MVT DstTy = Op.getValueType();
5022
5023  if (!IsSigned) {
5024    assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
5025    DstTy = MVT::i64;
5026  }
5027
5028  assert(DstTy.getSimpleVT() <= MVT::i64 &&
5029         DstTy.getSimpleVT() >= MVT::i16 &&
5030         "Unknown FP_TO_SINT to lower!");
5031
5032  // These are really Legal.
5033  if (DstTy == MVT::i32 &&
5034      isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
5035    return std::make_pair(SDValue(), SDValue());
5036  if (Subtarget->is64Bit() &&
5037      DstTy == MVT::i64 &&
5038      isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
5039    return std::make_pair(SDValue(), SDValue());
5040
5041  // We lower FP->sint64 into FISTP64, followed by a load, all to a temporary
5042  // stack slot.
5043  MachineFunction &MF = DAG.getMachineFunction();
5044  unsigned MemSize = DstTy.getSizeInBits()/8;
5045  int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize);
5046  SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
5047
5048  unsigned Opc;
5049  switch (DstTy.getSimpleVT()) {
5050  default: assert(0 && "Invalid FP_TO_SINT to lower!");
5051  case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
5052  case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
5053  case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
5054  }
5055
5056  SDValue Chain = DAG.getEntryNode();
5057  SDValue Value = Op.getOperand(0);
5058  if (isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType())) {
5059    assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
5060    Chain = DAG.getStore(Chain, dl, Value, StackSlot,
5061                         PseudoSourceValue::getFixedStack(SSFI), 0);
5062    SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
5063    SDValue Ops[] = {
5064      Chain, StackSlot, DAG.getValueType(Op.getOperand(0).getValueType())
5065    };
5066    Value = DAG.getNode(X86ISD::FLD, dl, Tys, Ops, 3);
5067    Chain = Value.getValue(1);
5068    SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize);
5069    StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
5070  }
5071
5072  // Build the FP_TO_INT*_IN_MEM
5073  SDValue Ops[] = { Chain, Value, StackSlot };
5074  SDValue FIST = DAG.getNode(Opc, dl, MVT::Other, Ops, 3);
5075
5076  return std::make_pair(FIST, StackSlot);
5077}
5078
5079SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op, SelectionDAG &DAG) {
5080  if (Op.getValueType().isVector()) {
5081    if (Op.getValueType() == MVT::v2i32 &&
5082        Op.getOperand(0).getValueType() == MVT::v2f64) {
5083      return Op;
5084    }
5085    return SDValue();
5086  }
5087
5088  std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG, true);
5089  SDValue FIST = Vals.first, StackSlot = Vals.second;
5090  // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
5091  if (FIST.getNode() == 0) return Op;
5092
5093  // Load the result.
5094  return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
5095                     FIST, StackSlot, NULL, 0);
5096}
5097
5098SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op, SelectionDAG &DAG) {
5099  std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG, false);
5100  SDValue FIST = Vals.first, StackSlot = Vals.second;
5101  assert(FIST.getNode() && "Unexpected failure");
5102
5103  // Load the result.
5104  return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
5105                     FIST, StackSlot, NULL, 0);
5106}
5107
5108SDValue X86TargetLowering::LowerFABS(SDValue Op, SelectionDAG &DAG) {
5109  DebugLoc dl = Op.getDebugLoc();
5110  MVT VT = Op.getValueType();
5111  MVT EltVT = VT;
5112  if (VT.isVector())
5113    EltVT = VT.getVectorElementType();
5114  std::vector<Constant*> CV;
5115  if (EltVT == MVT::f64) {
5116    Constant *C = ConstantFP::get(APFloat(APInt(64, ~(1ULL << 63))));
5117    CV.push_back(C);
5118    CV.push_back(C);
5119  } else {
5120    Constant *C = ConstantFP::get(APFloat(APInt(32, ~(1U << 31))));
5121    CV.push_back(C);
5122    CV.push_back(C);
5123    CV.push_back(C);
5124    CV.push_back(C);
5125  }
5126  Constant *C = ConstantVector::get(CV);
5127  SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
5128  SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
5129                               PseudoSourceValue::getConstantPool(), 0,
5130                               false, 16);
5131  return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
5132}
5133
5134SDValue X86TargetLowering::LowerFNEG(SDValue Op, SelectionDAG &DAG) {
5135  DebugLoc dl = Op.getDebugLoc();
5136  MVT VT = Op.getValueType();
5137  MVT EltVT = VT;
5138  unsigned EltNum = 1;
5139  if (VT.isVector()) {
5140    EltVT = VT.getVectorElementType();
5141    EltNum = VT.getVectorNumElements();
5142  }
5143  std::vector<Constant*> CV;
5144  if (EltVT == MVT::f64) {
5145    Constant *C = ConstantFP::get(APFloat(APInt(64, 1ULL << 63)));
5146    CV.push_back(C);
5147    CV.push_back(C);
5148  } else {
5149    Constant *C = ConstantFP::get(APFloat(APInt(32, 1U << 31)));
5150    CV.push_back(C);
5151    CV.push_back(C);
5152    CV.push_back(C);
5153    CV.push_back(C);
5154  }
5155  Constant *C = ConstantVector::get(CV);
5156  SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
5157  SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
5158                               PseudoSourceValue::getConstantPool(), 0,
5159                               false, 16);
5160  if (VT.isVector()) {
5161    return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
5162                       DAG.getNode(ISD::XOR, dl, MVT::v2i64,
5163                    DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64,
5164                                Op.getOperand(0)),
5165                    DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64, Mask)));
5166  } else {
5167    return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
5168  }
5169}
5170
5171SDValue X86TargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) {
5172  SDValue Op0 = Op.getOperand(0);
5173  SDValue Op1 = Op.getOperand(1);
5174  DebugLoc dl = Op.getDebugLoc();
5175  MVT VT = Op.getValueType();
5176  MVT SrcVT = Op1.getValueType();
5177
5178  // If second operand is smaller, extend it first.
5179  if (SrcVT.bitsLT(VT)) {
5180    Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
5181    SrcVT = VT;
5182  }
5183  // And if it is bigger, shrink it first.
5184  if (SrcVT.bitsGT(VT)) {
5185    Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
5186    SrcVT = VT;
5187  }
5188
5189  // At this point the operands and the result should have the same
5190  // type, and that won't be f80 since that is not custom lowered.
5191
5192  // First get the sign bit of second operand.
5193  std::vector<Constant*> CV;
5194  if (SrcVT == MVT::f64) {
5195    CV.push_back(ConstantFP::get(APFloat(APInt(64, 1ULL << 63))));
5196    CV.push_back(ConstantFP::get(APFloat(APInt(64, 0))));
5197  } else {
5198    CV.push_back(ConstantFP::get(APFloat(APInt(32, 1U << 31))));
5199    CV.push_back(ConstantFP::get(APFloat(APInt(32, 0))));
5200    CV.push_back(ConstantFP::get(APFloat(APInt(32, 0))));
5201    CV.push_back(ConstantFP::get(APFloat(APInt(32, 0))));
5202  }
5203  Constant *C = ConstantVector::get(CV);
5204  SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
5205  SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
5206                                PseudoSourceValue::getConstantPool(), 0,
5207                                false, 16);
5208  SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
5209
5210  // Shift sign bit right or left if the two operands have different types.
5211  if (SrcVT.bitsGT(VT)) {
5212    // Op0 is MVT::f32, Op1 is MVT::f64.
5213    SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
5214    SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
5215                          DAG.getConstant(32, MVT::i32));
5216    SignBit = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v4f32, SignBit);
5217    SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
5218                          DAG.getIntPtrConstant(0));
5219  }
5220
5221  // Clear first operand sign bit.
5222  CV.clear();
5223  if (VT == MVT::f64) {
5224    CV.push_back(ConstantFP::get(APFloat(APInt(64, ~(1ULL << 63)))));
5225    CV.push_back(ConstantFP::get(APFloat(APInt(64, 0))));
5226  } else {
5227    CV.push_back(ConstantFP::get(APFloat(APInt(32, ~(1U << 31)))));
5228    CV.push_back(ConstantFP::get(APFloat(APInt(32, 0))));
5229    CV.push_back(ConstantFP::get(APFloat(APInt(32, 0))));
5230    CV.push_back(ConstantFP::get(APFloat(APInt(32, 0))));
5231  }
5232  C = ConstantVector::get(CV);
5233  CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
5234  SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
5235                                PseudoSourceValue::getConstantPool(), 0,
5236                                false, 16);
5237  SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
5238
5239  // Or the value with the sign bit.
5240  return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
5241}
5242
5243/// Emit nodes that will be selected as "test Op0,Op0", or something
5244/// equivalent.
5245SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC,
5246                                    SelectionDAG &DAG) {
5247  DebugLoc dl = Op.getDebugLoc();
5248
5249  // CF and OF aren't always set the way we want. Determine which
5250  // of these we need.
5251  bool NeedCF = false;
5252  bool NeedOF = false;
5253  switch (X86CC) {
5254  case X86::COND_A: case X86::COND_AE:
5255  case X86::COND_B: case X86::COND_BE:
5256    NeedCF = true;
5257    break;
5258  case X86::COND_G: case X86::COND_GE:
5259  case X86::COND_L: case X86::COND_LE:
5260  case X86::COND_O: case X86::COND_NO:
5261    NeedOF = true;
5262    break;
5263  default: break;
5264  }
5265
5266  // See if we can use the EFLAGS value from the operand instead of
5267  // doing a separate TEST. TEST always sets OF and CF to 0, so unless
5268  // we prove that the arithmetic won't overflow, we can't use OF or CF.
5269  if (Op.getResNo() == 0 && !NeedOF && !NeedCF) {
5270    unsigned Opcode = 0;
5271    unsigned NumOperands = 0;
5272    switch (Op.getNode()->getOpcode()) {
5273    case ISD::ADD:
5274      // Due to an isel shortcoming, be conservative if this add is likely to
5275      // be selected as part of a load-modify-store instruction. When the root
5276      // node in a match is a store, isel doesn't know how to remap non-chain
5277      // non-flag uses of other nodes in the match, such as the ADD in this
5278      // case. This leads to the ADD being left around and reselected, with
5279      // the result being two adds in the output.
5280      for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
5281           UE = Op.getNode()->use_end(); UI != UE; ++UI)
5282        if (UI->getOpcode() == ISD::STORE)
5283          goto default_case;
5284      if (ConstantSDNode *C =
5285            dyn_cast<ConstantSDNode>(Op.getNode()->getOperand(1))) {
5286        // An add of one will be selected as an INC.
5287        if (C->getAPIntValue() == 1) {
5288          Opcode = X86ISD::INC;
5289          NumOperands = 1;
5290          break;
5291        }
5292        // An add of negative one (subtract of one) will be selected as a DEC.
5293        if (C->getAPIntValue().isAllOnesValue()) {
5294          Opcode = X86ISD::DEC;
5295          NumOperands = 1;
5296          break;
5297        }
5298      }
5299      // Otherwise use a regular EFLAGS-setting add.
5300      Opcode = X86ISD::ADD;
5301      NumOperands = 2;
5302      break;
5303    case ISD::SUB:
5304      // Due to the ISEL shortcoming noted above, be conservative if this sub is
5305      // likely to be selected as part of a load-modify-store instruction.
5306      for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
5307           UE = Op.getNode()->use_end(); UI != UE; ++UI)
5308        if (UI->getOpcode() == ISD::STORE)
5309          goto default_case;
5310      // Otherwise use a regular EFLAGS-setting sub.
5311      Opcode = X86ISD::SUB;
5312      NumOperands = 2;
5313      break;
5314    case X86ISD::ADD:
5315    case X86ISD::SUB:
5316    case X86ISD::INC:
5317    case X86ISD::DEC:
5318      return SDValue(Op.getNode(), 1);
5319    default:
5320    default_case:
5321      break;
5322    }
5323    if (Opcode != 0) {
5324      SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
5325      SmallVector<SDValue, 4> Ops;
5326      for (unsigned i = 0; i != NumOperands; ++i)
5327        Ops.push_back(Op.getOperand(i));
5328      SDValue New = DAG.getNode(Opcode, dl, VTs, &Ops[0], NumOperands);
5329      DAG.ReplaceAllUsesWith(Op, New);
5330      return SDValue(New.getNode(), 1);
5331    }
5332  }
5333
5334  // Otherwise just emit a CMP with 0, which is the TEST pattern.
5335  return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
5336                     DAG.getConstant(0, Op.getValueType()));
5337}
5338
5339/// Emit nodes that will be selected as "cmp Op0,Op1", or something
5340/// equivalent.
5341SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
5342                                   SelectionDAG &DAG) {
5343  if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1))
5344    if (C->getAPIntValue() == 0)
5345      return EmitTest(Op0, X86CC, DAG);
5346
5347  DebugLoc dl = Op0.getDebugLoc();
5348  return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
5349}
5350
5351SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) {
5352  assert(Op.getValueType() == MVT::i8 && "SetCC type must be 8-bit integer");
5353  SDValue Op0 = Op.getOperand(0);
5354  SDValue Op1 = Op.getOperand(1);
5355  DebugLoc dl = Op.getDebugLoc();
5356  ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
5357
5358  // Lower (X & (1 << N)) == 0 to BT(X, N).
5359  // Lower ((X >>u N) & 1) != 0 to BT(X, N).
5360  // Lower ((X >>s N) & 1) != 0 to BT(X, N).
5361  if (Op0.getOpcode() == ISD::AND &&
5362      Op0.hasOneUse() &&
5363      Op1.getOpcode() == ISD::Constant &&
5364      cast<ConstantSDNode>(Op1)->getZExtValue() == 0 &&
5365      (CC == ISD::SETEQ || CC == ISD::SETNE)) {
5366    SDValue LHS, RHS;
5367    if (Op0.getOperand(1).getOpcode() == ISD::SHL) {
5368      if (ConstantSDNode *Op010C =
5369            dyn_cast<ConstantSDNode>(Op0.getOperand(1).getOperand(0)))
5370        if (Op010C->getZExtValue() == 1) {
5371          LHS = Op0.getOperand(0);
5372          RHS = Op0.getOperand(1).getOperand(1);
5373        }
5374    } else if (Op0.getOperand(0).getOpcode() == ISD::SHL) {
5375      if (ConstantSDNode *Op000C =
5376            dyn_cast<ConstantSDNode>(Op0.getOperand(0).getOperand(0)))
5377        if (Op000C->getZExtValue() == 1) {
5378          LHS = Op0.getOperand(1);
5379          RHS = Op0.getOperand(0).getOperand(1);
5380        }
5381    } else if (Op0.getOperand(1).getOpcode() == ISD::Constant) {
5382      ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op0.getOperand(1));
5383      SDValue AndLHS = Op0.getOperand(0);
5384      if (AndRHS->getZExtValue() == 1 && AndLHS.getOpcode() == ISD::SRL) {
5385        LHS = AndLHS.getOperand(0);
5386        RHS = AndLHS.getOperand(1);
5387      }
5388    }
5389
5390    if (LHS.getNode()) {
5391      // If LHS is i8, promote it to i16 with any_extend.  There is no i8 BT
5392      // instruction.  Since the shift amount is in-range-or-undefined, we know
5393      // that doing a bittest on the i16 value is ok.  We extend to i32 because
5394      // the encoding for the i16 version is larger than the i32 version.
5395      if (LHS.getValueType() == MVT::i8)
5396        LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
5397
5398      // If the operand types disagree, extend the shift amount to match.  Since
5399      // BT ignores high bits (like shifts) we can use anyextend.
5400      if (LHS.getValueType() != RHS.getValueType())
5401        RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
5402
5403      SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
5404      unsigned Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
5405      return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
5406                         DAG.getConstant(Cond, MVT::i8), BT);
5407    }
5408  }
5409
5410  bool isFP = Op.getOperand(1).getValueType().isFloatingPoint();
5411  unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
5412
5413  SDValue Cond = EmitCmp(Op0, Op1, X86CC, DAG);
5414  return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
5415                     DAG.getConstant(X86CC, MVT::i8), Cond);
5416}
5417
5418SDValue X86TargetLowering::LowerVSETCC(SDValue Op, SelectionDAG &DAG) {
5419  SDValue Cond;
5420  SDValue Op0 = Op.getOperand(0);
5421  SDValue Op1 = Op.getOperand(1);
5422  SDValue CC = Op.getOperand(2);
5423  MVT VT = Op.getValueType();
5424  ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
5425  bool isFP = Op.getOperand(1).getValueType().isFloatingPoint();
5426  DebugLoc dl = Op.getDebugLoc();
5427
5428  if (isFP) {
5429    unsigned SSECC = 8;
5430    MVT VT0 = Op0.getValueType();
5431    assert(VT0 == MVT::v4f32 || VT0 == MVT::v2f64);
5432    unsigned Opc = VT0 == MVT::v4f32 ? X86ISD::CMPPS : X86ISD::CMPPD;
5433    bool Swap = false;
5434
5435    switch (SetCCOpcode) {
5436    default: break;
5437    case ISD::SETOEQ:
5438    case ISD::SETEQ:  SSECC = 0; break;
5439    case ISD::SETOGT:
5440    case ISD::SETGT: Swap = true; // Fallthrough
5441    case ISD::SETLT:
5442    case ISD::SETOLT: SSECC = 1; break;
5443    case ISD::SETOGE:
5444    case ISD::SETGE: Swap = true; // Fallthrough
5445    case ISD::SETLE:
5446    case ISD::SETOLE: SSECC = 2; break;
5447    case ISD::SETUO:  SSECC = 3; break;
5448    case ISD::SETUNE:
5449    case ISD::SETNE:  SSECC = 4; break;
5450    case ISD::SETULE: Swap = true;
5451    case ISD::SETUGE: SSECC = 5; break;
5452    case ISD::SETULT: Swap = true;
5453    case ISD::SETUGT: SSECC = 6; break;
5454    case ISD::SETO:   SSECC = 7; break;
5455    }
5456    if (Swap)
5457      std::swap(Op0, Op1);
5458
5459    // In the two special cases we can't handle, emit two comparisons.
5460    if (SSECC == 8) {
5461      if (SetCCOpcode == ISD::SETUEQ) {
5462        SDValue UNORD, EQ;
5463        UNORD = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(3, MVT::i8));
5464        EQ = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(0, MVT::i8));
5465        return DAG.getNode(ISD::OR, dl, VT, UNORD, EQ);
5466      }
5467      else if (SetCCOpcode == ISD::SETONE) {
5468        SDValue ORD, NEQ;
5469        ORD = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(7, MVT::i8));
5470        NEQ = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(4, MVT::i8));
5471        return DAG.getNode(ISD::AND, dl, VT, ORD, NEQ);
5472      }
5473      assert(0 && "Illegal FP comparison");
5474    }
5475    // Handle all other FP comparisons here.
5476    return DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(SSECC, MVT::i8));
5477  }
5478
5479  // We are handling one of the integer comparisons here.  Since SSE only has
5480  // GT and EQ comparisons for integer, swapping operands and multiple
5481  // operations may be required for some comparisons.
5482  unsigned Opc = 0, EQOpc = 0, GTOpc = 0;
5483  bool Swap = false, Invert = false, FlipSigns = false;
5484
5485  switch (VT.getSimpleVT()) {
5486  default: break;
5487  case MVT::v16i8: EQOpc = X86ISD::PCMPEQB; GTOpc = X86ISD::PCMPGTB; break;
5488  case MVT::v8i16: EQOpc = X86ISD::PCMPEQW; GTOpc = X86ISD::PCMPGTW; break;
5489  case MVT::v4i32: EQOpc = X86ISD::PCMPEQD; GTOpc = X86ISD::PCMPGTD; break;
5490  case MVT::v2i64: EQOpc = X86ISD::PCMPEQQ; GTOpc = X86ISD::PCMPGTQ; break;
5491  }
5492
5493  switch (SetCCOpcode) {
5494  default: break;
5495  case ISD::SETNE:  Invert = true;
5496  case ISD::SETEQ:  Opc = EQOpc; break;
5497  case ISD::SETLT:  Swap = true;
5498  case ISD::SETGT:  Opc = GTOpc; break;
5499  case ISD::SETGE:  Swap = true;
5500  case ISD::SETLE:  Opc = GTOpc; Invert = true; break;
5501  case ISD::SETULT: Swap = true;
5502  case ISD::SETUGT: Opc = GTOpc; FlipSigns = true; break;
5503  case ISD::SETUGE: Swap = true;
5504  case ISD::SETULE: Opc = GTOpc; FlipSigns = true; Invert = true; break;
5505  }
5506  if (Swap)
5507    std::swap(Op0, Op1);
5508
5509  // Since SSE has no unsigned integer comparisons, we need to flip  the sign
5510  // bits of the inputs before performing those operations.
5511  if (FlipSigns) {
5512    MVT EltVT = VT.getVectorElementType();
5513    SDValue SignBit = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()),
5514                                      EltVT);
5515    std::vector<SDValue> SignBits(VT.getVectorNumElements(), SignBit);
5516    SDValue SignVec = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &SignBits[0],
5517                                    SignBits.size());
5518    Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SignVec);
5519    Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SignVec);
5520  }
5521
5522  SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
5523
5524  // If the logical-not of the result is required, perform that now.
5525  if (Invert)
5526    Result = DAG.getNOT(dl, Result, VT);
5527
5528  return Result;
5529}
5530
5531// isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
5532static bool isX86LogicalCmp(SDValue Op) {
5533  unsigned Opc = Op.getNode()->getOpcode();
5534  if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI)
5535    return true;
5536  if (Op.getResNo() == 1 &&
5537      (Opc == X86ISD::ADD ||
5538       Opc == X86ISD::SUB ||
5539       Opc == X86ISD::SMUL ||
5540       Opc == X86ISD::UMUL ||
5541       Opc == X86ISD::INC ||
5542       Opc == X86ISD::DEC))
5543    return true;
5544
5545  return false;
5546}
5547
5548SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) {
5549  bool addTest = true;
5550  SDValue Cond  = Op.getOperand(0);
5551  DebugLoc dl = Op.getDebugLoc();
5552  SDValue CC;
5553
5554  if (Cond.getOpcode() == ISD::SETCC)
5555    Cond = LowerSETCC(Cond, DAG);
5556
5557  // If condition flag is set by a X86ISD::CMP, then use it as the condition
5558  // setting operand in place of the X86ISD::SETCC.
5559  if (Cond.getOpcode() == X86ISD::SETCC) {
5560    CC = Cond.getOperand(0);
5561
5562    SDValue Cmp = Cond.getOperand(1);
5563    unsigned Opc = Cmp.getOpcode();
5564    MVT VT = Op.getValueType();
5565
5566    bool IllegalFPCMov = false;
5567    if (VT.isFloatingPoint() && !VT.isVector() &&
5568        !isScalarFPTypeInSSEReg(VT))  // FPStack?
5569      IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
5570
5571    if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
5572        Opc == X86ISD::BT) { // FIXME
5573      Cond = Cmp;
5574      addTest = false;
5575    }
5576  }
5577
5578  if (addTest) {
5579    CC = DAG.getConstant(X86::COND_NE, MVT::i8);
5580    Cond = EmitTest(Cond, X86::COND_NE, DAG);
5581  }
5582
5583  SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Flag);
5584  SmallVector<SDValue, 4> Ops;
5585  // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
5586  // condition is true.
5587  Ops.push_back(Op.getOperand(2));
5588  Ops.push_back(Op.getOperand(1));
5589  Ops.push_back(CC);
5590  Ops.push_back(Cond);
5591  return DAG.getNode(X86ISD::CMOV, dl, VTs, &Ops[0], Ops.size());
5592}
5593
5594// isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
5595// ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
5596// from the AND / OR.
5597static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
5598  Opc = Op.getOpcode();
5599  if (Opc != ISD::OR && Opc != ISD::AND)
5600    return false;
5601  return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
5602          Op.getOperand(0).hasOneUse() &&
5603          Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
5604          Op.getOperand(1).hasOneUse());
5605}
5606
5607// isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
5608// 1 and that the SETCC node has a single use.
5609static bool isXor1OfSetCC(SDValue Op) {
5610  if (Op.getOpcode() != ISD::XOR)
5611    return false;
5612  ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
5613  if (N1C && N1C->getAPIntValue() == 1) {
5614    return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
5615      Op.getOperand(0).hasOneUse();
5616  }
5617  return false;
5618}
5619
5620SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) {
5621  bool addTest = true;
5622  SDValue Chain = Op.getOperand(0);
5623  SDValue Cond  = Op.getOperand(1);
5624  SDValue Dest  = Op.getOperand(2);
5625  DebugLoc dl = Op.getDebugLoc();
5626  SDValue CC;
5627
5628  if (Cond.getOpcode() == ISD::SETCC)
5629    Cond = LowerSETCC(Cond, DAG);
5630#if 0
5631  // FIXME: LowerXALUO doesn't handle these!!
5632  else if (Cond.getOpcode() == X86ISD::ADD  ||
5633           Cond.getOpcode() == X86ISD::SUB  ||
5634           Cond.getOpcode() == X86ISD::SMUL ||
5635           Cond.getOpcode() == X86ISD::UMUL)
5636    Cond = LowerXALUO(Cond, DAG);
5637#endif
5638
5639  // If condition flag is set by a X86ISD::CMP, then use it as the condition
5640  // setting operand in place of the X86ISD::SETCC.
5641  if (Cond.getOpcode() == X86ISD::SETCC) {
5642    CC = Cond.getOperand(0);
5643
5644    SDValue Cmp = Cond.getOperand(1);
5645    unsigned Opc = Cmp.getOpcode();
5646    // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
5647    if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
5648      Cond = Cmp;
5649      addTest = false;
5650    } else {
5651      switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
5652      default: break;
5653      case X86::COND_O:
5654      case X86::COND_B:
5655        // These can only come from an arithmetic instruction with overflow,
5656        // e.g. SADDO, UADDO.
5657        Cond = Cond.getNode()->getOperand(1);
5658        addTest = false;
5659        break;
5660      }
5661    }
5662  } else {
5663    unsigned CondOpc;
5664    if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
5665      SDValue Cmp = Cond.getOperand(0).getOperand(1);
5666      if (CondOpc == ISD::OR) {
5667        // Also, recognize the pattern generated by an FCMP_UNE. We can emit
5668        // two branches instead of an explicit OR instruction with a
5669        // separate test.
5670        if (Cmp == Cond.getOperand(1).getOperand(1) &&
5671            isX86LogicalCmp(Cmp)) {
5672          CC = Cond.getOperand(0).getOperand(0);
5673          Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
5674                              Chain, Dest, CC, Cmp);
5675          CC = Cond.getOperand(1).getOperand(0);
5676          Cond = Cmp;
5677          addTest = false;
5678        }
5679      } else { // ISD::AND
5680        // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
5681        // two branches instead of an explicit AND instruction with a
5682        // separate test. However, we only do this if this block doesn't
5683        // have a fall-through edge, because this requires an explicit
5684        // jmp when the condition is false.
5685        if (Cmp == Cond.getOperand(1).getOperand(1) &&
5686            isX86LogicalCmp(Cmp) &&
5687            Op.getNode()->hasOneUse()) {
5688          X86::CondCode CCode =
5689            (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
5690          CCode = X86::GetOppositeBranchCondition(CCode);
5691          CC = DAG.getConstant(CCode, MVT::i8);
5692          SDValue User = SDValue(*Op.getNode()->use_begin(), 0);
5693          // Look for an unconditional branch following this conditional branch.
5694          // We need this because we need to reverse the successors in order
5695          // to implement FCMP_OEQ.
5696          if (User.getOpcode() == ISD::BR) {
5697            SDValue FalseBB = User.getOperand(1);
5698            SDValue NewBR =
5699              DAG.UpdateNodeOperands(User, User.getOperand(0), Dest);
5700            assert(NewBR == User);
5701            Dest = FalseBB;
5702
5703            Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
5704                                Chain, Dest, CC, Cmp);
5705            X86::CondCode CCode =
5706              (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
5707            CCode = X86::GetOppositeBranchCondition(CCode);
5708            CC = DAG.getConstant(CCode, MVT::i8);
5709            Cond = Cmp;
5710            addTest = false;
5711          }
5712        }
5713      }
5714    } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
5715      // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
5716      // It should be transformed during dag combiner except when the condition
5717      // is set by a arithmetics with overflow node.
5718      X86::CondCode CCode =
5719        (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
5720      CCode = X86::GetOppositeBranchCondition(CCode);
5721      CC = DAG.getConstant(CCode, MVT::i8);
5722      Cond = Cond.getOperand(0).getOperand(1);
5723      addTest = false;
5724    }
5725  }
5726
5727  if (addTest) {
5728    CC = DAG.getConstant(X86::COND_NE, MVT::i8);
5729    Cond = EmitTest(Cond, X86::COND_NE, DAG);
5730  }
5731  return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
5732                     Chain, Dest, CC, Cond);
5733}
5734
5735
5736// Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
5737// Calls to _alloca is needed to probe the stack when allocating more than 4k
5738// bytes in one go. Touching the stack at 4K increments is necessary to ensure
5739// that the guard pages used by the OS virtual memory manager are allocated in
5740// correct sequence.
5741SDValue
5742X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
5743                                           SelectionDAG &DAG) {
5744  assert(Subtarget->isTargetCygMing() &&
5745         "This should be used only on Cygwin/Mingw targets");
5746  DebugLoc dl = Op.getDebugLoc();
5747
5748  // Get the inputs.
5749  SDValue Chain = Op.getOperand(0);
5750  SDValue Size  = Op.getOperand(1);
5751  // FIXME: Ensure alignment here
5752
5753  SDValue Flag;
5754
5755  MVT IntPtr = getPointerTy();
5756  MVT SPTy = Subtarget->is64Bit() ? MVT::i64 : MVT::i32;
5757
5758  Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(0, true));
5759
5760  Chain = DAG.getCopyToReg(Chain, dl, X86::EAX, Size, Flag);
5761  Flag = Chain.getValue(1);
5762
5763  SDVTList  NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
5764  SDValue Ops[] = { Chain,
5765                      DAG.getTargetExternalSymbol("_alloca", IntPtr),
5766                      DAG.getRegister(X86::EAX, IntPtr),
5767                      DAG.getRegister(X86StackPtr, SPTy),
5768                      Flag };
5769  Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, Ops, 5);
5770  Flag = Chain.getValue(1);
5771
5772  Chain = DAG.getCALLSEQ_END(Chain,
5773                             DAG.getIntPtrConstant(0, true),
5774                             DAG.getIntPtrConstant(0, true),
5775                             Flag);
5776
5777  Chain = DAG.getCopyFromReg(Chain, dl, X86StackPtr, SPTy).getValue(1);
5778
5779  SDValue Ops1[2] = { Chain.getValue(0), Chain };
5780  return DAG.getMergeValues(Ops1, 2, dl);
5781}
5782
5783SDValue
5784X86TargetLowering::EmitTargetCodeForMemset(SelectionDAG &DAG, DebugLoc dl,
5785                                           SDValue Chain,
5786                                           SDValue Dst, SDValue Src,
5787                                           SDValue Size, unsigned Align,
5788                                           const Value *DstSV,
5789                                           uint64_t DstSVOff) {
5790  ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
5791
5792  // If not DWORD aligned or size is more than the threshold, call the library.
5793  // The libc version is likely to be faster for these cases. It can use the
5794  // address value and run time information about the CPU.
5795  if ((Align & 3) != 0 ||
5796      !ConstantSize ||
5797      ConstantSize->getZExtValue() >
5798        getSubtarget()->getMaxInlineSizeThreshold()) {
5799    SDValue InFlag(0, 0);
5800
5801    // Check to see if there is a specialized entry-point for memory zeroing.
5802    ConstantSDNode *V = dyn_cast<ConstantSDNode>(Src);
5803
5804    if (const char *bzeroEntry =  V &&
5805        V->isNullValue() ? Subtarget->getBZeroEntry() : 0) {
5806      MVT IntPtr = getPointerTy();
5807      const Type *IntPtrTy = TD->getIntPtrType();
5808      TargetLowering::ArgListTy Args;
5809      TargetLowering::ArgListEntry Entry;
5810      Entry.Node = Dst;
5811      Entry.Ty = IntPtrTy;
5812      Args.push_back(Entry);
5813      Entry.Node = Size;
5814      Args.push_back(Entry);
5815      std::pair<SDValue,SDValue> CallResult =
5816        LowerCallTo(Chain, Type::VoidTy, false, false, false, false,
5817                    0, CallingConv::C, false,
5818                    DAG.getExternalSymbol(bzeroEntry, IntPtr), Args, DAG, dl);
5819      return CallResult.second;
5820    }
5821
5822    // Otherwise have the target-independent code call memset.
5823    return SDValue();
5824  }
5825
5826  uint64_t SizeVal = ConstantSize->getZExtValue();
5827  SDValue InFlag(0, 0);
5828  MVT AVT;
5829  SDValue Count;
5830  ConstantSDNode *ValC = dyn_cast<ConstantSDNode>(Src);
5831  unsigned BytesLeft = 0;
5832  bool TwoRepStos = false;
5833  if (ValC) {
5834    unsigned ValReg;
5835    uint64_t Val = ValC->getZExtValue() & 255;
5836
5837    // If the value is a constant, then we can potentially use larger sets.
5838    switch (Align & 3) {
5839    case 2:   // WORD aligned
5840      AVT = MVT::i16;
5841      ValReg = X86::AX;
5842      Val = (Val << 8) | Val;
5843      break;
5844    case 0:  // DWORD aligned
5845      AVT = MVT::i32;
5846      ValReg = X86::EAX;
5847      Val = (Val << 8)  | Val;
5848      Val = (Val << 16) | Val;
5849      if (Subtarget->is64Bit() && ((Align & 0x7) == 0)) {  // QWORD aligned
5850        AVT = MVT::i64;
5851        ValReg = X86::RAX;
5852        Val = (Val << 32) | Val;
5853      }
5854      break;
5855    default:  // Byte aligned
5856      AVT = MVT::i8;
5857      ValReg = X86::AL;
5858      Count = DAG.getIntPtrConstant(SizeVal);
5859      break;
5860    }
5861
5862    if (AVT.bitsGT(MVT::i8)) {
5863      unsigned UBytes = AVT.getSizeInBits() / 8;
5864      Count = DAG.getIntPtrConstant(SizeVal / UBytes);
5865      BytesLeft = SizeVal % UBytes;
5866    }
5867
5868    Chain  = DAG.getCopyToReg(Chain, dl, ValReg, DAG.getConstant(Val, AVT),
5869                              InFlag);
5870    InFlag = Chain.getValue(1);
5871  } else {
5872    AVT = MVT::i8;
5873    Count  = DAG.getIntPtrConstant(SizeVal);
5874    Chain  = DAG.getCopyToReg(Chain, dl, X86::AL, Src, InFlag);
5875    InFlag = Chain.getValue(1);
5876  }
5877
5878  Chain  = DAG.getCopyToReg(Chain, dl, Subtarget->is64Bit() ? X86::RCX :
5879                                                              X86::ECX,
5880                            Count, InFlag);
5881  InFlag = Chain.getValue(1);
5882  Chain  = DAG.getCopyToReg(Chain, dl, Subtarget->is64Bit() ? X86::RDI :
5883                                                              X86::EDI,
5884                            Dst, InFlag);
5885  InFlag = Chain.getValue(1);
5886
5887  SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
5888  SmallVector<SDValue, 8> Ops;
5889  Ops.push_back(Chain);
5890  Ops.push_back(DAG.getValueType(AVT));
5891  Ops.push_back(InFlag);
5892  Chain  = DAG.getNode(X86ISD::REP_STOS, dl, Tys, &Ops[0], Ops.size());
5893
5894  if (TwoRepStos) {
5895    InFlag = Chain.getValue(1);
5896    Count  = Size;
5897    MVT CVT = Count.getValueType();
5898    SDValue Left = DAG.getNode(ISD::AND, dl, CVT, Count,
5899                               DAG.getConstant((AVT == MVT::i64) ? 7 : 3, CVT));
5900    Chain  = DAG.getCopyToReg(Chain, dl, (CVT == MVT::i64) ? X86::RCX :
5901                                                             X86::ECX,
5902                              Left, InFlag);
5903    InFlag = Chain.getValue(1);
5904    Tys = DAG.getVTList(MVT::Other, MVT::Flag);
5905    Ops.clear();
5906    Ops.push_back(Chain);
5907    Ops.push_back(DAG.getValueType(MVT::i8));
5908    Ops.push_back(InFlag);
5909    Chain  = DAG.getNode(X86ISD::REP_STOS, dl, Tys, &Ops[0], Ops.size());
5910  } else if (BytesLeft) {
5911    // Handle the last 1 - 7 bytes.
5912    unsigned Offset = SizeVal - BytesLeft;
5913    MVT AddrVT = Dst.getValueType();
5914    MVT SizeVT = Size.getValueType();
5915
5916    Chain = DAG.getMemset(Chain, dl,
5917                          DAG.getNode(ISD::ADD, dl, AddrVT, Dst,
5918                                      DAG.getConstant(Offset, AddrVT)),
5919                          Src,
5920                          DAG.getConstant(BytesLeft, SizeVT),
5921                          Align, DstSV, DstSVOff + Offset);
5922  }
5923
5924  // TODO: Use a Tokenfactor, as in memcpy, instead of a single chain.
5925  return Chain;
5926}
5927
5928SDValue
5929X86TargetLowering::EmitTargetCodeForMemcpy(SelectionDAG &DAG, DebugLoc dl,
5930                                      SDValue Chain, SDValue Dst, SDValue Src,
5931                                      SDValue Size, unsigned Align,
5932                                      bool AlwaysInline,
5933                                      const Value *DstSV, uint64_t DstSVOff,
5934                                      const Value *SrcSV, uint64_t SrcSVOff) {
5935  // This requires the copy size to be a constant, preferrably
5936  // within a subtarget-specific limit.
5937  ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
5938  if (!ConstantSize)
5939    return SDValue();
5940  uint64_t SizeVal = ConstantSize->getZExtValue();
5941  if (!AlwaysInline && SizeVal > getSubtarget()->getMaxInlineSizeThreshold())
5942    return SDValue();
5943
5944  /// If not DWORD aligned, call the library.
5945  if ((Align & 3) != 0)
5946    return SDValue();
5947
5948  // DWORD aligned
5949  MVT AVT = MVT::i32;
5950  if (Subtarget->is64Bit() && ((Align & 0x7) == 0))  // QWORD aligned
5951    AVT = MVT::i64;
5952
5953  unsigned UBytes = AVT.getSizeInBits() / 8;
5954  unsigned CountVal = SizeVal / UBytes;
5955  SDValue Count = DAG.getIntPtrConstant(CountVal);
5956  unsigned BytesLeft = SizeVal % UBytes;
5957
5958  SDValue InFlag(0, 0);
5959  Chain  = DAG.getCopyToReg(Chain, dl, Subtarget->is64Bit() ? X86::RCX :
5960                                                              X86::ECX,
5961                            Count, InFlag);
5962  InFlag = Chain.getValue(1);
5963  Chain  = DAG.getCopyToReg(Chain, dl, Subtarget->is64Bit() ? X86::RDI :
5964                                                             X86::EDI,
5965                            Dst, InFlag);
5966  InFlag = Chain.getValue(1);
5967  Chain  = DAG.getCopyToReg(Chain, dl, Subtarget->is64Bit() ? X86::RSI :
5968                                                              X86::ESI,
5969                            Src, InFlag);
5970  InFlag = Chain.getValue(1);
5971
5972  SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
5973  SmallVector<SDValue, 8> Ops;
5974  Ops.push_back(Chain);
5975  Ops.push_back(DAG.getValueType(AVT));
5976  Ops.push_back(InFlag);
5977  SDValue RepMovs = DAG.getNode(X86ISD::REP_MOVS, dl, Tys, &Ops[0], Ops.size());
5978
5979  SmallVector<SDValue, 4> Results;
5980  Results.push_back(RepMovs);
5981  if (BytesLeft) {
5982    // Handle the last 1 - 7 bytes.
5983    unsigned Offset = SizeVal - BytesLeft;
5984    MVT DstVT = Dst.getValueType();
5985    MVT SrcVT = Src.getValueType();
5986    MVT SizeVT = Size.getValueType();
5987    Results.push_back(DAG.getMemcpy(Chain, dl,
5988                                    DAG.getNode(ISD::ADD, dl, DstVT, Dst,
5989                                                DAG.getConstant(Offset, DstVT)),
5990                                    DAG.getNode(ISD::ADD, dl, SrcVT, Src,
5991                                                DAG.getConstant(Offset, SrcVT)),
5992                                    DAG.getConstant(BytesLeft, SizeVT),
5993                                    Align, AlwaysInline,
5994                                    DstSV, DstSVOff + Offset,
5995                                    SrcSV, SrcSVOff + Offset));
5996  }
5997
5998  return DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
5999                     &Results[0], Results.size());
6000}
6001
6002SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) {
6003  const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
6004  DebugLoc dl = Op.getDebugLoc();
6005
6006  if (!Subtarget->is64Bit()) {
6007    // vastart just stores the address of the VarArgsFrameIndex slot into the
6008    // memory location argument.
6009    SDValue FR = DAG.getFrameIndex(VarArgsFrameIndex, getPointerTy());
6010    return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1), SV, 0);
6011  }
6012
6013  // __va_list_tag:
6014  //   gp_offset         (0 - 6 * 8)
6015  //   fp_offset         (48 - 48 + 8 * 16)
6016  //   overflow_arg_area (point to parameters coming in memory).
6017  //   reg_save_area
6018  SmallVector<SDValue, 8> MemOps;
6019  SDValue FIN = Op.getOperand(1);
6020  // Store gp_offset
6021  SDValue Store = DAG.getStore(Op.getOperand(0), dl,
6022                                 DAG.getConstant(VarArgsGPOffset, MVT::i32),
6023                                 FIN, SV, 0);
6024  MemOps.push_back(Store);
6025
6026  // Store fp_offset
6027  FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(),
6028                    FIN, DAG.getIntPtrConstant(4));
6029  Store = DAG.getStore(Op.getOperand(0), dl,
6030                       DAG.getConstant(VarArgsFPOffset, MVT::i32),
6031                       FIN, SV, 0);
6032  MemOps.push_back(Store);
6033
6034  // Store ptr to overflow_arg_area
6035  FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(),
6036                    FIN, DAG.getIntPtrConstant(4));
6037  SDValue OVFIN = DAG.getFrameIndex(VarArgsFrameIndex, getPointerTy());
6038  Store = DAG.getStore(Op.getOperand(0), dl, OVFIN, FIN, SV, 0);
6039  MemOps.push_back(Store);
6040
6041  // Store ptr to reg_save_area.
6042  FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(),
6043                    FIN, DAG.getIntPtrConstant(8));
6044  SDValue RSFIN = DAG.getFrameIndex(RegSaveFrameIndex, getPointerTy());
6045  Store = DAG.getStore(Op.getOperand(0), dl, RSFIN, FIN, SV, 0);
6046  MemOps.push_back(Store);
6047  return DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
6048                     &MemOps[0], MemOps.size());
6049}
6050
6051SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) {
6052  // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
6053  assert(Subtarget->is64Bit() && "This code only handles 64-bit va_arg!");
6054  SDValue Chain = Op.getOperand(0);
6055  SDValue SrcPtr = Op.getOperand(1);
6056  SDValue SrcSV = Op.getOperand(2);
6057
6058  LLVM_UNREACHABLE("VAArgInst is not yet implemented for x86-64!");
6059  return SDValue();
6060}
6061
6062SDValue X86TargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) {
6063  // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
6064  assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
6065  SDValue Chain = Op.getOperand(0);
6066  SDValue DstPtr = Op.getOperand(1);
6067  SDValue SrcPtr = Op.getOperand(2);
6068  const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
6069  const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
6070  DebugLoc dl = Op.getDebugLoc();
6071
6072  return DAG.getMemcpy(Chain, dl, DstPtr, SrcPtr,
6073                       DAG.getIntPtrConstant(24), 8, false,
6074                       DstSV, 0, SrcSV, 0);
6075}
6076
6077SDValue
6078X86TargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) {
6079  DebugLoc dl = Op.getDebugLoc();
6080  unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
6081  switch (IntNo) {
6082  default: return SDValue();    // Don't custom lower most intrinsics.
6083  // Comparison intrinsics.
6084  case Intrinsic::x86_sse_comieq_ss:
6085  case Intrinsic::x86_sse_comilt_ss:
6086  case Intrinsic::x86_sse_comile_ss:
6087  case Intrinsic::x86_sse_comigt_ss:
6088  case Intrinsic::x86_sse_comige_ss:
6089  case Intrinsic::x86_sse_comineq_ss:
6090  case Intrinsic::x86_sse_ucomieq_ss:
6091  case Intrinsic::x86_sse_ucomilt_ss:
6092  case Intrinsic::x86_sse_ucomile_ss:
6093  case Intrinsic::x86_sse_ucomigt_ss:
6094  case Intrinsic::x86_sse_ucomige_ss:
6095  case Intrinsic::x86_sse_ucomineq_ss:
6096  case Intrinsic::x86_sse2_comieq_sd:
6097  case Intrinsic::x86_sse2_comilt_sd:
6098  case Intrinsic::x86_sse2_comile_sd:
6099  case Intrinsic::x86_sse2_comigt_sd:
6100  case Intrinsic::x86_sse2_comige_sd:
6101  case Intrinsic::x86_sse2_comineq_sd:
6102  case Intrinsic::x86_sse2_ucomieq_sd:
6103  case Intrinsic::x86_sse2_ucomilt_sd:
6104  case Intrinsic::x86_sse2_ucomile_sd:
6105  case Intrinsic::x86_sse2_ucomigt_sd:
6106  case Intrinsic::x86_sse2_ucomige_sd:
6107  case Intrinsic::x86_sse2_ucomineq_sd: {
6108    unsigned Opc = 0;
6109    ISD::CondCode CC = ISD::SETCC_INVALID;
6110    switch (IntNo) {
6111    default: break;
6112    case Intrinsic::x86_sse_comieq_ss:
6113    case Intrinsic::x86_sse2_comieq_sd:
6114      Opc = X86ISD::COMI;
6115      CC = ISD::SETEQ;
6116      break;
6117    case Intrinsic::x86_sse_comilt_ss:
6118    case Intrinsic::x86_sse2_comilt_sd:
6119      Opc = X86ISD::COMI;
6120      CC = ISD::SETLT;
6121      break;
6122    case Intrinsic::x86_sse_comile_ss:
6123    case Intrinsic::x86_sse2_comile_sd:
6124      Opc = X86ISD::COMI;
6125      CC = ISD::SETLE;
6126      break;
6127    case Intrinsic::x86_sse_comigt_ss:
6128    case Intrinsic::x86_sse2_comigt_sd:
6129      Opc = X86ISD::COMI;
6130      CC = ISD::SETGT;
6131      break;
6132    case Intrinsic::x86_sse_comige_ss:
6133    case Intrinsic::x86_sse2_comige_sd:
6134      Opc = X86ISD::COMI;
6135      CC = ISD::SETGE;
6136      break;
6137    case Intrinsic::x86_sse_comineq_ss:
6138    case Intrinsic::x86_sse2_comineq_sd:
6139      Opc = X86ISD::COMI;
6140      CC = ISD::SETNE;
6141      break;
6142    case Intrinsic::x86_sse_ucomieq_ss:
6143    case Intrinsic::x86_sse2_ucomieq_sd:
6144      Opc = X86ISD::UCOMI;
6145      CC = ISD::SETEQ;
6146      break;
6147    case Intrinsic::x86_sse_ucomilt_ss:
6148    case Intrinsic::x86_sse2_ucomilt_sd:
6149      Opc = X86ISD::UCOMI;
6150      CC = ISD::SETLT;
6151      break;
6152    case Intrinsic::x86_sse_ucomile_ss:
6153    case Intrinsic::x86_sse2_ucomile_sd:
6154      Opc = X86ISD::UCOMI;
6155      CC = ISD::SETLE;
6156      break;
6157    case Intrinsic::x86_sse_ucomigt_ss:
6158    case Intrinsic::x86_sse2_ucomigt_sd:
6159      Opc = X86ISD::UCOMI;
6160      CC = ISD::SETGT;
6161      break;
6162    case Intrinsic::x86_sse_ucomige_ss:
6163    case Intrinsic::x86_sse2_ucomige_sd:
6164      Opc = X86ISD::UCOMI;
6165      CC = ISD::SETGE;
6166      break;
6167    case Intrinsic::x86_sse_ucomineq_ss:
6168    case Intrinsic::x86_sse2_ucomineq_sd:
6169      Opc = X86ISD::UCOMI;
6170      CC = ISD::SETNE;
6171      break;
6172    }
6173
6174    SDValue LHS = Op.getOperand(1);
6175    SDValue RHS = Op.getOperand(2);
6176    unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
6177    SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS);
6178    SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
6179                                DAG.getConstant(X86CC, MVT::i8), Cond);
6180    return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
6181  }
6182
6183  // Fix vector shift instructions where the last operand is a non-immediate
6184  // i32 value.
6185  case Intrinsic::x86_sse2_pslli_w:
6186  case Intrinsic::x86_sse2_pslli_d:
6187  case Intrinsic::x86_sse2_pslli_q:
6188  case Intrinsic::x86_sse2_psrli_w:
6189  case Intrinsic::x86_sse2_psrli_d:
6190  case Intrinsic::x86_sse2_psrli_q:
6191  case Intrinsic::x86_sse2_psrai_w:
6192  case Intrinsic::x86_sse2_psrai_d:
6193  case Intrinsic::x86_mmx_pslli_w:
6194  case Intrinsic::x86_mmx_pslli_d:
6195  case Intrinsic::x86_mmx_pslli_q:
6196  case Intrinsic::x86_mmx_psrli_w:
6197  case Intrinsic::x86_mmx_psrli_d:
6198  case Intrinsic::x86_mmx_psrli_q:
6199  case Intrinsic::x86_mmx_psrai_w:
6200  case Intrinsic::x86_mmx_psrai_d: {
6201    SDValue ShAmt = Op.getOperand(2);
6202    if (isa<ConstantSDNode>(ShAmt))
6203      return SDValue();
6204
6205    unsigned NewIntNo = 0;
6206    MVT ShAmtVT = MVT::v4i32;
6207    switch (IntNo) {
6208    case Intrinsic::x86_sse2_pslli_w:
6209      NewIntNo = Intrinsic::x86_sse2_psll_w;
6210      break;
6211    case Intrinsic::x86_sse2_pslli_d:
6212      NewIntNo = Intrinsic::x86_sse2_psll_d;
6213      break;
6214    case Intrinsic::x86_sse2_pslli_q:
6215      NewIntNo = Intrinsic::x86_sse2_psll_q;
6216      break;
6217    case Intrinsic::x86_sse2_psrli_w:
6218      NewIntNo = Intrinsic::x86_sse2_psrl_w;
6219      break;
6220    case Intrinsic::x86_sse2_psrli_d:
6221      NewIntNo = Intrinsic::x86_sse2_psrl_d;
6222      break;
6223    case Intrinsic::x86_sse2_psrli_q:
6224      NewIntNo = Intrinsic::x86_sse2_psrl_q;
6225      break;
6226    case Intrinsic::x86_sse2_psrai_w:
6227      NewIntNo = Intrinsic::x86_sse2_psra_w;
6228      break;
6229    case Intrinsic::x86_sse2_psrai_d:
6230      NewIntNo = Intrinsic::x86_sse2_psra_d;
6231      break;
6232    default: {
6233      ShAmtVT = MVT::v2i32;
6234      switch (IntNo) {
6235      case Intrinsic::x86_mmx_pslli_w:
6236        NewIntNo = Intrinsic::x86_mmx_psll_w;
6237        break;
6238      case Intrinsic::x86_mmx_pslli_d:
6239        NewIntNo = Intrinsic::x86_mmx_psll_d;
6240        break;
6241      case Intrinsic::x86_mmx_pslli_q:
6242        NewIntNo = Intrinsic::x86_mmx_psll_q;
6243        break;
6244      case Intrinsic::x86_mmx_psrli_w:
6245        NewIntNo = Intrinsic::x86_mmx_psrl_w;
6246        break;
6247      case Intrinsic::x86_mmx_psrli_d:
6248        NewIntNo = Intrinsic::x86_mmx_psrl_d;
6249        break;
6250      case Intrinsic::x86_mmx_psrli_q:
6251        NewIntNo = Intrinsic::x86_mmx_psrl_q;
6252        break;
6253      case Intrinsic::x86_mmx_psrai_w:
6254        NewIntNo = Intrinsic::x86_mmx_psra_w;
6255        break;
6256      case Intrinsic::x86_mmx_psrai_d:
6257        NewIntNo = Intrinsic::x86_mmx_psra_d;
6258        break;
6259      default: LLVM_UNREACHABLE("Impossible intrinsic");  // Can't reach here.
6260      }
6261      break;
6262    }
6263    }
6264    MVT VT = Op.getValueType();
6265    ShAmt = DAG.getNode(ISD::BIT_CONVERT, dl, VT,
6266                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, ShAmtVT, ShAmt));
6267    return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
6268                       DAG.getConstant(NewIntNo, MVT::i32),
6269                       Op.getOperand(1), ShAmt);
6270  }
6271  }
6272}
6273
6274SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) {
6275  unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
6276  DebugLoc dl = Op.getDebugLoc();
6277
6278  if (Depth > 0) {
6279    SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
6280    SDValue Offset =
6281      DAG.getConstant(TD->getPointerSize(),
6282                      Subtarget->is64Bit() ? MVT::i64 : MVT::i32);
6283    return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
6284                       DAG.getNode(ISD::ADD, dl, getPointerTy(),
6285                                   FrameAddr, Offset),
6286                       NULL, 0);
6287  }
6288
6289  // Just load the return address.
6290  SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
6291  return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
6292                     RetAddrFI, NULL, 0);
6293}
6294
6295SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) {
6296  MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
6297  MFI->setFrameAddressIsTaken(true);
6298  MVT VT = Op.getValueType();
6299  DebugLoc dl = Op.getDebugLoc();  // FIXME probably not meaningful
6300  unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
6301  unsigned FrameReg = Subtarget->is64Bit() ? X86::RBP : X86::EBP;
6302  SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
6303  while (Depth--)
6304    FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr, NULL, 0);
6305  return FrameAddr;
6306}
6307
6308SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
6309                                                     SelectionDAG &DAG) {
6310  return DAG.getIntPtrConstant(2*TD->getPointerSize());
6311}
6312
6313SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG)
6314{
6315  MachineFunction &MF = DAG.getMachineFunction();
6316  SDValue Chain     = Op.getOperand(0);
6317  SDValue Offset    = Op.getOperand(1);
6318  SDValue Handler   = Op.getOperand(2);
6319  DebugLoc dl       = Op.getDebugLoc();
6320
6321  SDValue Frame = DAG.getRegister(Subtarget->is64Bit() ? X86::RBP : X86::EBP,
6322                                  getPointerTy());
6323  unsigned StoreAddrReg = (Subtarget->is64Bit() ? X86::RCX : X86::ECX);
6324
6325  SDValue StoreAddr = DAG.getNode(ISD::SUB, dl, getPointerTy(), Frame,
6326                                  DAG.getIntPtrConstant(-TD->getPointerSize()));
6327  StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), StoreAddr, Offset);
6328  Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, NULL, 0);
6329  Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
6330  MF.getRegInfo().addLiveOut(StoreAddrReg);
6331
6332  return DAG.getNode(X86ISD::EH_RETURN, dl,
6333                     MVT::Other,
6334                     Chain, DAG.getRegister(StoreAddrReg, getPointerTy()));
6335}
6336
6337SDValue X86TargetLowering::LowerTRAMPOLINE(SDValue Op,
6338                                             SelectionDAG &DAG) {
6339  SDValue Root = Op.getOperand(0);
6340  SDValue Trmp = Op.getOperand(1); // trampoline
6341  SDValue FPtr = Op.getOperand(2); // nested function
6342  SDValue Nest = Op.getOperand(3); // 'nest' parameter value
6343  DebugLoc dl  = Op.getDebugLoc();
6344
6345  const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
6346
6347  const X86InstrInfo *TII =
6348    ((X86TargetMachine&)getTargetMachine()).getInstrInfo();
6349
6350  if (Subtarget->is64Bit()) {
6351    SDValue OutChains[6];
6352
6353    // Large code-model.
6354
6355    const unsigned char JMP64r  = TII->getBaseOpcodeFor(X86::JMP64r);
6356    const unsigned char MOV64ri = TII->getBaseOpcodeFor(X86::MOV64ri);
6357
6358    const unsigned char N86R10 = RegInfo->getX86RegNum(X86::R10);
6359    const unsigned char N86R11 = RegInfo->getX86RegNum(X86::R11);
6360
6361    const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
6362
6363    // Load the pointer to the nested function into R11.
6364    unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
6365    SDValue Addr = Trmp;
6366    OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
6367                                Addr, TrmpAddr, 0);
6368
6369    Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
6370                       DAG.getConstant(2, MVT::i64));
6371    OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr, TrmpAddr, 2, false, 2);
6372
6373    // Load the 'nest' parameter value into R10.
6374    // R10 is specified in X86CallingConv.td
6375    OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
6376    Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
6377                       DAG.getConstant(10, MVT::i64));
6378    OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
6379                                Addr, TrmpAddr, 10);
6380
6381    Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
6382                       DAG.getConstant(12, MVT::i64));
6383    OutChains[3] = DAG.getStore(Root, dl, Nest, Addr, TrmpAddr, 12, false, 2);
6384
6385    // Jump to the nested function.
6386    OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
6387    Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
6388                       DAG.getConstant(20, MVT::i64));
6389    OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
6390                                Addr, TrmpAddr, 20);
6391
6392    unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
6393    Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
6394                       DAG.getConstant(22, MVT::i64));
6395    OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
6396                                TrmpAddr, 22);
6397
6398    SDValue Ops[] =
6399      { Trmp, DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 6) };
6400    return DAG.getMergeValues(Ops, 2, dl);
6401  } else {
6402    const Function *Func =
6403      cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
6404    unsigned CC = Func->getCallingConv();
6405    unsigned NestReg;
6406
6407    switch (CC) {
6408    default:
6409      assert(0 && "Unsupported calling convention");
6410    case CallingConv::C:
6411    case CallingConv::X86_StdCall: {
6412      // Pass 'nest' parameter in ECX.
6413      // Must be kept in sync with X86CallingConv.td
6414      NestReg = X86::ECX;
6415
6416      // Check that ECX wasn't needed by an 'inreg' parameter.
6417      const FunctionType *FTy = Func->getFunctionType();
6418      const AttrListPtr &Attrs = Func->getAttributes();
6419
6420      if (!Attrs.isEmpty() && !Func->isVarArg()) {
6421        unsigned InRegCount = 0;
6422        unsigned Idx = 1;
6423
6424        for (FunctionType::param_iterator I = FTy->param_begin(),
6425             E = FTy->param_end(); I != E; ++I, ++Idx)
6426          if (Attrs.paramHasAttr(Idx, Attribute::InReg))
6427            // FIXME: should only count parameters that are lowered to integers.
6428            InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
6429
6430        if (InRegCount > 2) {
6431          llvm_report_error("Nest register in use - reduce number of inreg parameters!");
6432        }
6433      }
6434      break;
6435    }
6436    case CallingConv::X86_FastCall:
6437    case CallingConv::Fast:
6438      // Pass 'nest' parameter in EAX.
6439      // Must be kept in sync with X86CallingConv.td
6440      NestReg = X86::EAX;
6441      break;
6442    }
6443
6444    SDValue OutChains[4];
6445    SDValue Addr, Disp;
6446
6447    Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
6448                       DAG.getConstant(10, MVT::i32));
6449    Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
6450
6451    const unsigned char MOV32ri = TII->getBaseOpcodeFor(X86::MOV32ri);
6452    const unsigned char N86Reg = RegInfo->getX86RegNum(NestReg);
6453    OutChains[0] = DAG.getStore(Root, dl,
6454                                DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
6455                                Trmp, TrmpAddr, 0);
6456
6457    Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
6458                       DAG.getConstant(1, MVT::i32));
6459    OutChains[1] = DAG.getStore(Root, dl, Nest, Addr, TrmpAddr, 1, false, 1);
6460
6461    const unsigned char JMP = TII->getBaseOpcodeFor(X86::JMP);
6462    Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
6463                       DAG.getConstant(5, MVT::i32));
6464    OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
6465                                TrmpAddr, 5, false, 1);
6466
6467    Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
6468                       DAG.getConstant(6, MVT::i32));
6469    OutChains[3] = DAG.getStore(Root, dl, Disp, Addr, TrmpAddr, 6, false, 1);
6470
6471    SDValue Ops[] =
6472      { Trmp, DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 4) };
6473    return DAG.getMergeValues(Ops, 2, dl);
6474  }
6475}
6476
6477SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op, SelectionDAG &DAG) {
6478  /*
6479   The rounding mode is in bits 11:10 of FPSR, and has the following
6480   settings:
6481     00 Round to nearest
6482     01 Round to -inf
6483     10 Round to +inf
6484     11 Round to 0
6485
6486  FLT_ROUNDS, on the other hand, expects the following:
6487    -1 Undefined
6488     0 Round to 0
6489     1 Round to nearest
6490     2 Round to +inf
6491     3 Round to -inf
6492
6493  To perform the conversion, we do:
6494    (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
6495  */
6496
6497  MachineFunction &MF = DAG.getMachineFunction();
6498  const TargetMachine &TM = MF.getTarget();
6499  const TargetFrameInfo &TFI = *TM.getFrameInfo();
6500  unsigned StackAlignment = TFI.getStackAlignment();
6501  MVT VT = Op.getValueType();
6502  DebugLoc dl = Op.getDebugLoc();
6503
6504  // Save FP Control Word to stack slot
6505  int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment);
6506  SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
6507
6508  SDValue Chain = DAG.getNode(X86ISD::FNSTCW16m, dl, MVT::Other,
6509                              DAG.getEntryNode(), StackSlot);
6510
6511  // Load FP Control Word from stack slot
6512  SDValue CWD = DAG.getLoad(MVT::i16, dl, Chain, StackSlot, NULL, 0);
6513
6514  // Transform as necessary
6515  SDValue CWD1 =
6516    DAG.getNode(ISD::SRL, dl, MVT::i16,
6517                DAG.getNode(ISD::AND, dl, MVT::i16,
6518                            CWD, DAG.getConstant(0x800, MVT::i16)),
6519                DAG.getConstant(11, MVT::i8));
6520  SDValue CWD2 =
6521    DAG.getNode(ISD::SRL, dl, MVT::i16,
6522                DAG.getNode(ISD::AND, dl, MVT::i16,
6523                            CWD, DAG.getConstant(0x400, MVT::i16)),
6524                DAG.getConstant(9, MVT::i8));
6525
6526  SDValue RetVal =
6527    DAG.getNode(ISD::AND, dl, MVT::i16,
6528                DAG.getNode(ISD::ADD, dl, MVT::i16,
6529                            DAG.getNode(ISD::OR, dl, MVT::i16, CWD1, CWD2),
6530                            DAG.getConstant(1, MVT::i16)),
6531                DAG.getConstant(3, MVT::i16));
6532
6533
6534  return DAG.getNode((VT.getSizeInBits() < 16 ?
6535                      ISD::TRUNCATE : ISD::ZERO_EXTEND), dl, VT, RetVal);
6536}
6537
6538SDValue X86TargetLowering::LowerCTLZ(SDValue Op, SelectionDAG &DAG) {
6539  MVT VT = Op.getValueType();
6540  MVT OpVT = VT;
6541  unsigned NumBits = VT.getSizeInBits();
6542  DebugLoc dl = Op.getDebugLoc();
6543
6544  Op = Op.getOperand(0);
6545  if (VT == MVT::i8) {
6546    // Zero extend to i32 since there is not an i8 bsr.
6547    OpVT = MVT::i32;
6548    Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
6549  }
6550
6551  // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
6552  SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
6553  Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
6554
6555  // If src is zero (i.e. bsr sets ZF), returns NumBits.
6556  SmallVector<SDValue, 4> Ops;
6557  Ops.push_back(Op);
6558  Ops.push_back(DAG.getConstant(NumBits+NumBits-1, OpVT));
6559  Ops.push_back(DAG.getConstant(X86::COND_E, MVT::i8));
6560  Ops.push_back(Op.getValue(1));
6561  Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, &Ops[0], 4);
6562
6563  // Finally xor with NumBits-1.
6564  Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
6565
6566  if (VT == MVT::i8)
6567    Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
6568  return Op;
6569}
6570
6571SDValue X86TargetLowering::LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
6572  MVT VT = Op.getValueType();
6573  MVT OpVT = VT;
6574  unsigned NumBits = VT.getSizeInBits();
6575  DebugLoc dl = Op.getDebugLoc();
6576
6577  Op = Op.getOperand(0);
6578  if (VT == MVT::i8) {
6579    OpVT = MVT::i32;
6580    Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
6581  }
6582
6583  // Issue a bsf (scan bits forward) which also sets EFLAGS.
6584  SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
6585  Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
6586
6587  // If src is zero (i.e. bsf sets ZF), returns NumBits.
6588  SmallVector<SDValue, 4> Ops;
6589  Ops.push_back(Op);
6590  Ops.push_back(DAG.getConstant(NumBits, OpVT));
6591  Ops.push_back(DAG.getConstant(X86::COND_E, MVT::i8));
6592  Ops.push_back(Op.getValue(1));
6593  Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, &Ops[0], 4);
6594
6595  if (VT == MVT::i8)
6596    Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
6597  return Op;
6598}
6599
6600SDValue X86TargetLowering::LowerMUL_V2I64(SDValue Op, SelectionDAG &DAG) {
6601  MVT VT = Op.getValueType();
6602  assert(VT == MVT::v2i64 && "Only know how to lower V2I64 multiply");
6603  DebugLoc dl = Op.getDebugLoc();
6604
6605  //  ulong2 Ahi = __builtin_ia32_psrlqi128( a, 32);
6606  //  ulong2 Bhi = __builtin_ia32_psrlqi128( b, 32);
6607  //  ulong2 AloBlo = __builtin_ia32_pmuludq128( a, b );
6608  //  ulong2 AloBhi = __builtin_ia32_pmuludq128( a, Bhi );
6609  //  ulong2 AhiBlo = __builtin_ia32_pmuludq128( Ahi, b );
6610  //
6611  //  AloBhi = __builtin_ia32_psllqi128( AloBhi, 32 );
6612  //  AhiBlo = __builtin_ia32_psllqi128( AhiBlo, 32 );
6613  //  return AloBlo + AloBhi + AhiBlo;
6614
6615  SDValue A = Op.getOperand(0);
6616  SDValue B = Op.getOperand(1);
6617
6618  SDValue Ahi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
6619                       DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
6620                       A, DAG.getConstant(32, MVT::i32));
6621  SDValue Bhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
6622                       DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
6623                       B, DAG.getConstant(32, MVT::i32));
6624  SDValue AloBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
6625                       DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
6626                       A, B);
6627  SDValue AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
6628                       DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
6629                       A, Bhi);
6630  SDValue AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
6631                       DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
6632                       Ahi, B);
6633  AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
6634                       DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
6635                       AloBhi, DAG.getConstant(32, MVT::i32));
6636  AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
6637                       DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
6638                       AhiBlo, DAG.getConstant(32, MVT::i32));
6639  SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
6640  Res = DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
6641  return Res;
6642}
6643
6644
6645SDValue X86TargetLowering::LowerXALUO(SDValue Op, SelectionDAG &DAG) {
6646  // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
6647  // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
6648  // looks for this combo and may remove the "setcc" instruction if the "setcc"
6649  // has only one use.
6650  SDNode *N = Op.getNode();
6651  SDValue LHS = N->getOperand(0);
6652  SDValue RHS = N->getOperand(1);
6653  unsigned BaseOp = 0;
6654  unsigned Cond = 0;
6655  DebugLoc dl = Op.getDebugLoc();
6656
6657  switch (Op.getOpcode()) {
6658  default: assert(0 && "Unknown ovf instruction!");
6659  case ISD::SADDO:
6660    // A subtract of one will be selected as a INC. Note that INC doesn't
6661    // set CF, so we can't do this for UADDO.
6662    if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op))
6663      if (C->getAPIntValue() == 1) {
6664        BaseOp = X86ISD::INC;
6665        Cond = X86::COND_O;
6666        break;
6667      }
6668    BaseOp = X86ISD::ADD;
6669    Cond = X86::COND_O;
6670    break;
6671  case ISD::UADDO:
6672    BaseOp = X86ISD::ADD;
6673    Cond = X86::COND_B;
6674    break;
6675  case ISD::SSUBO:
6676    // A subtract of one will be selected as a DEC. Note that DEC doesn't
6677    // set CF, so we can't do this for USUBO.
6678    if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op))
6679      if (C->getAPIntValue() == 1) {
6680        BaseOp = X86ISD::DEC;
6681        Cond = X86::COND_O;
6682        break;
6683      }
6684    BaseOp = X86ISD::SUB;
6685    Cond = X86::COND_O;
6686    break;
6687  case ISD::USUBO:
6688    BaseOp = X86ISD::SUB;
6689    Cond = X86::COND_B;
6690    break;
6691  case ISD::SMULO:
6692    BaseOp = X86ISD::SMUL;
6693    Cond = X86::COND_O;
6694    break;
6695  case ISD::UMULO:
6696    BaseOp = X86ISD::UMUL;
6697    Cond = X86::COND_B;
6698    break;
6699  }
6700
6701  // Also sets EFLAGS.
6702  SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
6703  SDValue Sum = DAG.getNode(BaseOp, dl, VTs, LHS, RHS);
6704
6705  SDValue SetCC =
6706    DAG.getNode(X86ISD::SETCC, dl, N->getValueType(1),
6707                DAG.getConstant(Cond, MVT::i32), SDValue(Sum.getNode(), 1));
6708
6709  DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), SetCC);
6710  return Sum;
6711}
6712
6713SDValue X86TargetLowering::LowerCMP_SWAP(SDValue Op, SelectionDAG &DAG) {
6714  MVT T = Op.getValueType();
6715  DebugLoc dl = Op.getDebugLoc();
6716  unsigned Reg = 0;
6717  unsigned size = 0;
6718  switch(T.getSimpleVT()) {
6719  default:
6720    assert(false && "Invalid value type!");
6721  case MVT::i8:  Reg = X86::AL;  size = 1; break;
6722  case MVT::i16: Reg = X86::AX;  size = 2; break;
6723  case MVT::i32: Reg = X86::EAX; size = 4; break;
6724  case MVT::i64:
6725    assert(Subtarget->is64Bit() && "Node not type legal!");
6726    Reg = X86::RAX; size = 8;
6727    break;
6728  }
6729  SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), dl, Reg,
6730                                    Op.getOperand(2), SDValue());
6731  SDValue Ops[] = { cpIn.getValue(0),
6732                    Op.getOperand(1),
6733                    Op.getOperand(3),
6734                    DAG.getTargetConstant(size, MVT::i8),
6735                    cpIn.getValue(1) };
6736  SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
6737  SDValue Result = DAG.getNode(X86ISD::LCMPXCHG_DAG, dl, Tys, Ops, 5);
6738  SDValue cpOut =
6739    DAG.getCopyFromReg(Result.getValue(0), dl, Reg, T, Result.getValue(1));
6740  return cpOut;
6741}
6742
6743SDValue X86TargetLowering::LowerREADCYCLECOUNTER(SDValue Op,
6744                                                 SelectionDAG &DAG) {
6745  assert(Subtarget->is64Bit() && "Result not type legalized?");
6746  SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
6747  SDValue TheChain = Op.getOperand(0);
6748  DebugLoc dl = Op.getDebugLoc();
6749  SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
6750  SDValue rax = DAG.getCopyFromReg(rd, dl, X86::RAX, MVT::i64, rd.getValue(1));
6751  SDValue rdx = DAG.getCopyFromReg(rax.getValue(1), dl, X86::RDX, MVT::i64,
6752                                   rax.getValue(2));
6753  SDValue Tmp = DAG.getNode(ISD::SHL, dl, MVT::i64, rdx,
6754                            DAG.getConstant(32, MVT::i8));
6755  SDValue Ops[] = {
6756    DAG.getNode(ISD::OR, dl, MVT::i64, rax, Tmp),
6757    rdx.getValue(1)
6758  };
6759  return DAG.getMergeValues(Ops, 2, dl);
6760}
6761
6762SDValue X86TargetLowering::LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) {
6763  SDNode *Node = Op.getNode();
6764  DebugLoc dl = Node->getDebugLoc();
6765  MVT T = Node->getValueType(0);
6766  SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
6767                              DAG.getConstant(0, T), Node->getOperand(2));
6768  return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
6769                       cast<AtomicSDNode>(Node)->getMemoryVT(),
6770                       Node->getOperand(0),
6771                       Node->getOperand(1), negOp,
6772                       cast<AtomicSDNode>(Node)->getSrcValue(),
6773                       cast<AtomicSDNode>(Node)->getAlignment());
6774}
6775
6776/// LowerOperation - Provide custom lowering hooks for some operations.
6777///
6778SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) {
6779  switch (Op.getOpcode()) {
6780  default: assert(0 && "Should not custom lower this!");
6781  case ISD::ATOMIC_CMP_SWAP:    return LowerCMP_SWAP(Op,DAG);
6782  case ISD::ATOMIC_LOAD_SUB:    return LowerLOAD_SUB(Op,DAG);
6783  case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
6784  case ISD::VECTOR_SHUFFLE:     return LowerVECTOR_SHUFFLE(Op, DAG);
6785  case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
6786  case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
6787  case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
6788  case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
6789  case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
6790  case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
6791  case ISD::ExternalSymbol:     return LowerExternalSymbol(Op, DAG);
6792  case ISD::SHL_PARTS:
6793  case ISD::SRA_PARTS:
6794  case ISD::SRL_PARTS:          return LowerShift(Op, DAG);
6795  case ISD::SINT_TO_FP:         return LowerSINT_TO_FP(Op, DAG);
6796  case ISD::UINT_TO_FP:         return LowerUINT_TO_FP(Op, DAG);
6797  case ISD::FP_TO_SINT:         return LowerFP_TO_SINT(Op, DAG);
6798  case ISD::FP_TO_UINT:         return LowerFP_TO_UINT(Op, DAG);
6799  case ISD::FABS:               return LowerFABS(Op, DAG);
6800  case ISD::FNEG:               return LowerFNEG(Op, DAG);
6801  case ISD::FCOPYSIGN:          return LowerFCOPYSIGN(Op, DAG);
6802  case ISD::SETCC:              return LowerSETCC(Op, DAG);
6803  case ISD::VSETCC:             return LowerVSETCC(Op, DAG);
6804  case ISD::SELECT:             return LowerSELECT(Op, DAG);
6805  case ISD::BRCOND:             return LowerBRCOND(Op, DAG);
6806  case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
6807  case ISD::CALL:               return LowerCALL(Op, DAG);
6808  case ISD::RET:                return LowerRET(Op, DAG);
6809  case ISD::FORMAL_ARGUMENTS:   return LowerFORMAL_ARGUMENTS(Op, DAG);
6810  case ISD::VASTART:            return LowerVASTART(Op, DAG);
6811  case ISD::VAARG:              return LowerVAARG(Op, DAG);
6812  case ISD::VACOPY:             return LowerVACOPY(Op, DAG);
6813  case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
6814  case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
6815  case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
6816  case ISD::FRAME_TO_ARGS_OFFSET:
6817                                return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
6818  case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
6819  case ISD::EH_RETURN:          return LowerEH_RETURN(Op, DAG);
6820  case ISD::TRAMPOLINE:         return LowerTRAMPOLINE(Op, DAG);
6821  case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
6822  case ISD::CTLZ:               return LowerCTLZ(Op, DAG);
6823  case ISD::CTTZ:               return LowerCTTZ(Op, DAG);
6824  case ISD::MUL:                return LowerMUL_V2I64(Op, DAG);
6825  case ISD::SADDO:
6826  case ISD::UADDO:
6827  case ISD::SSUBO:
6828  case ISD::USUBO:
6829  case ISD::SMULO:
6830  case ISD::UMULO:              return LowerXALUO(Op, DAG);
6831  case ISD::READCYCLECOUNTER:   return LowerREADCYCLECOUNTER(Op, DAG);
6832  }
6833}
6834
6835void X86TargetLowering::
6836ReplaceATOMIC_BINARY_64(SDNode *Node, SmallVectorImpl<SDValue>&Results,
6837                        SelectionDAG &DAG, unsigned NewOp) {
6838  MVT T = Node->getValueType(0);
6839  DebugLoc dl = Node->getDebugLoc();
6840  assert (T == MVT::i64 && "Only know how to expand i64 atomics");
6841
6842  SDValue Chain = Node->getOperand(0);
6843  SDValue In1 = Node->getOperand(1);
6844  SDValue In2L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
6845                             Node->getOperand(2), DAG.getIntPtrConstant(0));
6846  SDValue In2H = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
6847                             Node->getOperand(2), DAG.getIntPtrConstant(1));
6848  // This is a generalized SDNode, not an AtomicSDNode, so it doesn't
6849  // have a MemOperand.  Pass the info through as a normal operand.
6850  SDValue LSI = DAG.getMemOperand(cast<MemSDNode>(Node)->getMemOperand());
6851  SDValue Ops[] = { Chain, In1, In2L, In2H, LSI };
6852  SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
6853  SDValue Result = DAG.getNode(NewOp, dl, Tys, Ops, 5);
6854  SDValue OpsF[] = { Result.getValue(0), Result.getValue(1)};
6855  Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
6856  Results.push_back(Result.getValue(2));
6857}
6858
6859/// ReplaceNodeResults - Replace a node with an illegal result type
6860/// with a new node built out of custom code.
6861void X86TargetLowering::ReplaceNodeResults(SDNode *N,
6862                                           SmallVectorImpl<SDValue>&Results,
6863                                           SelectionDAG &DAG) {
6864  DebugLoc dl = N->getDebugLoc();
6865  switch (N->getOpcode()) {
6866  default:
6867    assert(false && "Do not know how to custom type legalize this operation!");
6868    return;
6869  case ISD::FP_TO_SINT: {
6870    std::pair<SDValue,SDValue> Vals =
6871        FP_TO_INTHelper(SDValue(N, 0), DAG, true);
6872    SDValue FIST = Vals.first, StackSlot = Vals.second;
6873    if (FIST.getNode() != 0) {
6874      MVT VT = N->getValueType(0);
6875      // Return a load from the stack slot.
6876      Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot, NULL, 0));
6877    }
6878    return;
6879  }
6880  case ISD::READCYCLECOUNTER: {
6881    SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
6882    SDValue TheChain = N->getOperand(0);
6883    SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
6884    SDValue eax = DAG.getCopyFromReg(rd, dl, X86::EAX, MVT::i32,
6885                                     rd.getValue(1));
6886    SDValue edx = DAG.getCopyFromReg(eax.getValue(1), dl, X86::EDX, MVT::i32,
6887                                     eax.getValue(2));
6888    // Use a buildpair to merge the two 32-bit values into a 64-bit one.
6889    SDValue Ops[] = { eax, edx };
6890    Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Ops, 2));
6891    Results.push_back(edx.getValue(1));
6892    return;
6893  }
6894  case ISD::ATOMIC_CMP_SWAP: {
6895    MVT T = N->getValueType(0);
6896    assert (T == MVT::i64 && "Only know how to expand i64 Cmp and Swap");
6897    SDValue cpInL, cpInH;
6898    cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(2),
6899                        DAG.getConstant(0, MVT::i32));
6900    cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(2),
6901                        DAG.getConstant(1, MVT::i32));
6902    cpInL = DAG.getCopyToReg(N->getOperand(0), dl, X86::EAX, cpInL, SDValue());
6903    cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl, X86::EDX, cpInH,
6904                             cpInL.getValue(1));
6905    SDValue swapInL, swapInH;
6906    swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(3),
6907                          DAG.getConstant(0, MVT::i32));
6908    swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(3),
6909                          DAG.getConstant(1, MVT::i32));
6910    swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl, X86::EBX, swapInL,
6911                               cpInH.getValue(1));
6912    swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl, X86::ECX, swapInH,
6913                               swapInL.getValue(1));
6914    SDValue Ops[] = { swapInH.getValue(0),
6915                      N->getOperand(1),
6916                      swapInH.getValue(1) };
6917    SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
6918    SDValue Result = DAG.getNode(X86ISD::LCMPXCHG8_DAG, dl, Tys, Ops, 3);
6919    SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl, X86::EAX,
6920                                        MVT::i32, Result.getValue(1));
6921    SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl, X86::EDX,
6922                                        MVT::i32, cpOutL.getValue(2));
6923    SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
6924    Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
6925    Results.push_back(cpOutH.getValue(1));
6926    return;
6927  }
6928  case ISD::ATOMIC_LOAD_ADD:
6929    ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMADD64_DAG);
6930    return;
6931  case ISD::ATOMIC_LOAD_AND:
6932    ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMAND64_DAG);
6933    return;
6934  case ISD::ATOMIC_LOAD_NAND:
6935    ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMNAND64_DAG);
6936    return;
6937  case ISD::ATOMIC_LOAD_OR:
6938    ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMOR64_DAG);
6939    return;
6940  case ISD::ATOMIC_LOAD_SUB:
6941    ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSUB64_DAG);
6942    return;
6943  case ISD::ATOMIC_LOAD_XOR:
6944    ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMXOR64_DAG);
6945    return;
6946  case ISD::ATOMIC_SWAP:
6947    ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSWAP64_DAG);
6948    return;
6949  }
6950}
6951
6952const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
6953  switch (Opcode) {
6954  default: return NULL;
6955  case X86ISD::BSF:                return "X86ISD::BSF";
6956  case X86ISD::BSR:                return "X86ISD::BSR";
6957  case X86ISD::SHLD:               return "X86ISD::SHLD";
6958  case X86ISD::SHRD:               return "X86ISD::SHRD";
6959  case X86ISD::FAND:               return "X86ISD::FAND";
6960  case X86ISD::FOR:                return "X86ISD::FOR";
6961  case X86ISD::FXOR:               return "X86ISD::FXOR";
6962  case X86ISD::FSRL:               return "X86ISD::FSRL";
6963  case X86ISD::FILD:               return "X86ISD::FILD";
6964  case X86ISD::FILD_FLAG:          return "X86ISD::FILD_FLAG";
6965  case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
6966  case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
6967  case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
6968  case X86ISD::FLD:                return "X86ISD::FLD";
6969  case X86ISD::FST:                return "X86ISD::FST";
6970  case X86ISD::CALL:               return "X86ISD::CALL";
6971  case X86ISD::TAILCALL:           return "X86ISD::TAILCALL";
6972  case X86ISD::RDTSC_DAG:          return "X86ISD::RDTSC_DAG";
6973  case X86ISD::BT:                 return "X86ISD::BT";
6974  case X86ISD::CMP:                return "X86ISD::CMP";
6975  case X86ISD::COMI:               return "X86ISD::COMI";
6976  case X86ISD::UCOMI:              return "X86ISD::UCOMI";
6977  case X86ISD::SETCC:              return "X86ISD::SETCC";
6978  case X86ISD::CMOV:               return "X86ISD::CMOV";
6979  case X86ISD::BRCOND:             return "X86ISD::BRCOND";
6980  case X86ISD::RET_FLAG:           return "X86ISD::RET_FLAG";
6981  case X86ISD::REP_STOS:           return "X86ISD::REP_STOS";
6982  case X86ISD::REP_MOVS:           return "X86ISD::REP_MOVS";
6983  case X86ISD::GlobalBaseReg:      return "X86ISD::GlobalBaseReg";
6984  case X86ISD::Wrapper:            return "X86ISD::Wrapper";
6985  case X86ISD::WrapperRIP:         return "X86ISD::WrapperRIP";
6986  case X86ISD::PEXTRB:             return "X86ISD::PEXTRB";
6987  case X86ISD::PEXTRW:             return "X86ISD::PEXTRW";
6988  case X86ISD::INSERTPS:           return "X86ISD::INSERTPS";
6989  case X86ISD::PINSRB:             return "X86ISD::PINSRB";
6990  case X86ISD::PINSRW:             return "X86ISD::PINSRW";
6991  case X86ISD::PSHUFB:             return "X86ISD::PSHUFB";
6992  case X86ISD::FMAX:               return "X86ISD::FMAX";
6993  case X86ISD::FMIN:               return "X86ISD::FMIN";
6994  case X86ISD::FRSQRT:             return "X86ISD::FRSQRT";
6995  case X86ISD::FRCP:               return "X86ISD::FRCP";
6996  case X86ISD::TLSADDR:            return "X86ISD::TLSADDR";
6997  case X86ISD::SegmentBaseAddress: return "X86ISD::SegmentBaseAddress";
6998  case X86ISD::EH_RETURN:          return "X86ISD::EH_RETURN";
6999  case X86ISD::TC_RETURN:          return "X86ISD::TC_RETURN";
7000  case X86ISD::FNSTCW16m:          return "X86ISD::FNSTCW16m";
7001  case X86ISD::LCMPXCHG_DAG:       return "X86ISD::LCMPXCHG_DAG";
7002  case X86ISD::LCMPXCHG8_DAG:      return "X86ISD::LCMPXCHG8_DAG";
7003  case X86ISD::ATOMADD64_DAG:      return "X86ISD::ATOMADD64_DAG";
7004  case X86ISD::ATOMSUB64_DAG:      return "X86ISD::ATOMSUB64_DAG";
7005  case X86ISD::ATOMOR64_DAG:       return "X86ISD::ATOMOR64_DAG";
7006  case X86ISD::ATOMXOR64_DAG:      return "X86ISD::ATOMXOR64_DAG";
7007  case X86ISD::ATOMAND64_DAG:      return "X86ISD::ATOMAND64_DAG";
7008  case X86ISD::ATOMNAND64_DAG:     return "X86ISD::ATOMNAND64_DAG";
7009  case X86ISD::VZEXT_MOVL:         return "X86ISD::VZEXT_MOVL";
7010  case X86ISD::VZEXT_LOAD:         return "X86ISD::VZEXT_LOAD";
7011  case X86ISD::VSHL:               return "X86ISD::VSHL";
7012  case X86ISD::VSRL:               return "X86ISD::VSRL";
7013  case X86ISD::CMPPD:              return "X86ISD::CMPPD";
7014  case X86ISD::CMPPS:              return "X86ISD::CMPPS";
7015  case X86ISD::PCMPEQB:            return "X86ISD::PCMPEQB";
7016  case X86ISD::PCMPEQW:            return "X86ISD::PCMPEQW";
7017  case X86ISD::PCMPEQD:            return "X86ISD::PCMPEQD";
7018  case X86ISD::PCMPEQQ:            return "X86ISD::PCMPEQQ";
7019  case X86ISD::PCMPGTB:            return "X86ISD::PCMPGTB";
7020  case X86ISD::PCMPGTW:            return "X86ISD::PCMPGTW";
7021  case X86ISD::PCMPGTD:            return "X86ISD::PCMPGTD";
7022  case X86ISD::PCMPGTQ:            return "X86ISD::PCMPGTQ";
7023  case X86ISD::ADD:                return "X86ISD::ADD";
7024  case X86ISD::SUB:                return "X86ISD::SUB";
7025  case X86ISD::SMUL:               return "X86ISD::SMUL";
7026  case X86ISD::UMUL:               return "X86ISD::UMUL";
7027  case X86ISD::INC:                return "X86ISD::INC";
7028  case X86ISD::DEC:                return "X86ISD::DEC";
7029  case X86ISD::MUL_IMM:            return "X86ISD::MUL_IMM";
7030  }
7031}
7032
7033// isLegalAddressingMode - Return true if the addressing mode represented
7034// by AM is legal for this target, for a load/store of the specified type.
7035bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
7036                                              const Type *Ty) const {
7037  // X86 supports extremely general addressing modes.
7038
7039  // X86 allows a sign-extended 32-bit immediate field as a displacement.
7040  if (AM.BaseOffs <= -(1LL << 32) || AM.BaseOffs >= (1LL << 32)-1)
7041    return false;
7042
7043  if (AM.BaseGV) {
7044    // We can only fold this if we don't need an extra load.
7045    if (Subtarget->GVRequiresExtraLoad(AM.BaseGV, getTargetMachine(), false))
7046      return false;
7047    // If BaseGV requires a register, we cannot also have a BaseReg.
7048    if (Subtarget->GVRequiresRegister(AM.BaseGV, getTargetMachine(), false) &&
7049        AM.HasBaseReg)
7050      return false;
7051
7052    // X86-64 only supports addr of globals in small code model.
7053    if (Subtarget->is64Bit()) {
7054      if (getTargetMachine().getCodeModel() != CodeModel::Small)
7055        return false;
7056      // If lower 4G is not available, then we must use rip-relative addressing.
7057      if (AM.BaseOffs || AM.Scale > 1)
7058        return false;
7059    }
7060  }
7061
7062  switch (AM.Scale) {
7063  case 0:
7064  case 1:
7065  case 2:
7066  case 4:
7067  case 8:
7068    // These scales always work.
7069    break;
7070  case 3:
7071  case 5:
7072  case 9:
7073    // These scales are formed with basereg+scalereg.  Only accept if there is
7074    // no basereg yet.
7075    if (AM.HasBaseReg)
7076      return false;
7077    break;
7078  default:  // Other stuff never works.
7079    return false;
7080  }
7081
7082  return true;
7083}
7084
7085
7086bool X86TargetLowering::isTruncateFree(const Type *Ty1, const Type *Ty2) const {
7087  if (!Ty1->isInteger() || !Ty2->isInteger())
7088    return false;
7089  unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
7090  unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
7091  if (NumBits1 <= NumBits2)
7092    return false;
7093  return Subtarget->is64Bit() || NumBits1 < 64;
7094}
7095
7096bool X86TargetLowering::isTruncateFree(MVT VT1, MVT VT2) const {
7097  if (!VT1.isInteger() || !VT2.isInteger())
7098    return false;
7099  unsigned NumBits1 = VT1.getSizeInBits();
7100  unsigned NumBits2 = VT2.getSizeInBits();
7101  if (NumBits1 <= NumBits2)
7102    return false;
7103  return Subtarget->is64Bit() || NumBits1 < 64;
7104}
7105
7106bool X86TargetLowering::isZExtFree(const Type *Ty1, const Type *Ty2) const {
7107  // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
7108  return Ty1 == Type::Int32Ty && Ty2 == Type::Int64Ty && Subtarget->is64Bit();
7109}
7110
7111bool X86TargetLowering::isZExtFree(MVT VT1, MVT VT2) const {
7112  // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
7113  return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
7114}
7115
7116bool X86TargetLowering::isNarrowingProfitable(MVT VT1, MVT VT2) const {
7117  // i16 instructions are longer (0x66 prefix) and potentially slower.
7118  return !(VT1 == MVT::i32 && VT2 == MVT::i16);
7119}
7120
7121/// isShuffleMaskLegal - Targets can use this to indicate that they only
7122/// support *some* VECTOR_SHUFFLE operations, those with specific masks.
7123/// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
7124/// are assumed to be legal.
7125bool
7126X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
7127                                      MVT VT) const {
7128  // Only do shuffles on 128-bit vector types for now.
7129  if (VT.getSizeInBits() == 64)
7130    return false;
7131
7132  // FIXME: pshufb, blends, palignr, shifts.
7133  return (VT.getVectorNumElements() == 2 ||
7134          ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
7135          isMOVLMask(M, VT) ||
7136          isSHUFPMask(M, VT) ||
7137          isPSHUFDMask(M, VT) ||
7138          isPSHUFHWMask(M, VT) ||
7139          isPSHUFLWMask(M, VT) ||
7140          isUNPCKLMask(M, VT) ||
7141          isUNPCKHMask(M, VT) ||
7142          isUNPCKL_v_undef_Mask(M, VT) ||
7143          isUNPCKH_v_undef_Mask(M, VT));
7144}
7145
7146bool
7147X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
7148                                          MVT VT) const {
7149  unsigned NumElts = VT.getVectorNumElements();
7150  // FIXME: This collection of masks seems suspect.
7151  if (NumElts == 2)
7152    return true;
7153  if (NumElts == 4 && VT.getSizeInBits() == 128) {
7154    return (isMOVLMask(Mask, VT)  ||
7155            isCommutedMOVLMask(Mask, VT, true) ||
7156            isSHUFPMask(Mask, VT) ||
7157            isCommutedSHUFPMask(Mask, VT));
7158  }
7159  return false;
7160}
7161
7162//===----------------------------------------------------------------------===//
7163//                           X86 Scheduler Hooks
7164//===----------------------------------------------------------------------===//
7165
7166// private utility function
7167MachineBasicBlock *
7168X86TargetLowering::EmitAtomicBitwiseWithCustomInserter(MachineInstr *bInstr,
7169                                                       MachineBasicBlock *MBB,
7170                                                       unsigned regOpc,
7171                                                       unsigned immOpc,
7172                                                       unsigned LoadOpc,
7173                                                       unsigned CXchgOpc,
7174                                                       unsigned copyOpc,
7175                                                       unsigned notOpc,
7176                                                       unsigned EAXreg,
7177                                                       TargetRegisterClass *RC,
7178                                                       bool invSrc) const {
7179  // For the atomic bitwise operator, we generate
7180  //   thisMBB:
7181  //   newMBB:
7182  //     ld  t1 = [bitinstr.addr]
7183  //     op  t2 = t1, [bitinstr.val]
7184  //     mov EAX = t1
7185  //     lcs dest = [bitinstr.addr], t2  [EAX is implicit]
7186  //     bz  newMBB
7187  //     fallthrough -->nextMBB
7188  const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
7189  const BasicBlock *LLVM_BB = MBB->getBasicBlock();
7190  MachineFunction::iterator MBBIter = MBB;
7191  ++MBBIter;
7192
7193  /// First build the CFG
7194  MachineFunction *F = MBB->getParent();
7195  MachineBasicBlock *thisMBB = MBB;
7196  MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
7197  MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
7198  F->insert(MBBIter, newMBB);
7199  F->insert(MBBIter, nextMBB);
7200
7201  // Move all successors to thisMBB to nextMBB
7202  nextMBB->transferSuccessors(thisMBB);
7203
7204  // Update thisMBB to fall through to newMBB
7205  thisMBB->addSuccessor(newMBB);
7206
7207  // newMBB jumps to itself and fall through to nextMBB
7208  newMBB->addSuccessor(nextMBB);
7209  newMBB->addSuccessor(newMBB);
7210
7211  // Insert instructions into newMBB based on incoming instruction
7212  assert(bInstr->getNumOperands() < X86AddrNumOperands + 4 &&
7213         "unexpected number of operands");
7214  DebugLoc dl = bInstr->getDebugLoc();
7215  MachineOperand& destOper = bInstr->getOperand(0);
7216  MachineOperand* argOpers[2 + X86AddrNumOperands];
7217  int numArgs = bInstr->getNumOperands() - 1;
7218  for (int i=0; i < numArgs; ++i)
7219    argOpers[i] = &bInstr->getOperand(i+1);
7220
7221  // x86 address has 4 operands: base, index, scale, and displacement
7222  int lastAddrIndx = X86AddrNumOperands - 1; // [0,3]
7223  int valArgIndx = lastAddrIndx + 1;
7224
7225  unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
7226  MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(LoadOpc), t1);
7227  for (int i=0; i <= lastAddrIndx; ++i)
7228    (*MIB).addOperand(*argOpers[i]);
7229
7230  unsigned tt = F->getRegInfo().createVirtualRegister(RC);
7231  if (invSrc) {
7232    MIB = BuildMI(newMBB, dl, TII->get(notOpc), tt).addReg(t1);
7233  }
7234  else
7235    tt = t1;
7236
7237  unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
7238  assert((argOpers[valArgIndx]->isReg() ||
7239          argOpers[valArgIndx]->isImm()) &&
7240         "invalid operand");
7241  if (argOpers[valArgIndx]->isReg())
7242    MIB = BuildMI(newMBB, dl, TII->get(regOpc), t2);
7243  else
7244    MIB = BuildMI(newMBB, dl, TII->get(immOpc), t2);
7245  MIB.addReg(tt);
7246  (*MIB).addOperand(*argOpers[valArgIndx]);
7247
7248  MIB = BuildMI(newMBB, dl, TII->get(copyOpc), EAXreg);
7249  MIB.addReg(t1);
7250
7251  MIB = BuildMI(newMBB, dl, TII->get(CXchgOpc));
7252  for (int i=0; i <= lastAddrIndx; ++i)
7253    (*MIB).addOperand(*argOpers[i]);
7254  MIB.addReg(t2);
7255  assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
7256  (*MIB).addMemOperand(*F, *bInstr->memoperands_begin());
7257
7258  MIB = BuildMI(newMBB, dl, TII->get(copyOpc), destOper.getReg());
7259  MIB.addReg(EAXreg);
7260
7261  // insert branch
7262  BuildMI(newMBB, dl, TII->get(X86::JNE)).addMBB(newMBB);
7263
7264  F->DeleteMachineInstr(bInstr);   // The pseudo instruction is gone now.
7265  return nextMBB;
7266}
7267
7268// private utility function:  64 bit atomics on 32 bit host.
7269MachineBasicBlock *
7270X86TargetLowering::EmitAtomicBit6432WithCustomInserter(MachineInstr *bInstr,
7271                                                       MachineBasicBlock *MBB,
7272                                                       unsigned regOpcL,
7273                                                       unsigned regOpcH,
7274                                                       unsigned immOpcL,
7275                                                       unsigned immOpcH,
7276                                                       bool invSrc) const {
7277  // For the atomic bitwise operator, we generate
7278  //   thisMBB (instructions are in pairs, except cmpxchg8b)
7279  //     ld t1,t2 = [bitinstr.addr]
7280  //   newMBB:
7281  //     out1, out2 = phi (thisMBB, t1/t2) (newMBB, t3/t4)
7282  //     op  t5, t6 <- out1, out2, [bitinstr.val]
7283  //      (for SWAP, substitute:  mov t5, t6 <- [bitinstr.val])
7284  //     mov ECX, EBX <- t5, t6
7285  //     mov EAX, EDX <- t1, t2
7286  //     cmpxchg8b [bitinstr.addr]  [EAX, EDX, EBX, ECX implicit]
7287  //     mov t3, t4 <- EAX, EDX
7288  //     bz  newMBB
7289  //     result in out1, out2
7290  //     fallthrough -->nextMBB
7291
7292  const TargetRegisterClass *RC = X86::GR32RegisterClass;
7293  const unsigned LoadOpc = X86::MOV32rm;
7294  const unsigned copyOpc = X86::MOV32rr;
7295  const unsigned NotOpc = X86::NOT32r;
7296  const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
7297  const BasicBlock *LLVM_BB = MBB->getBasicBlock();
7298  MachineFunction::iterator MBBIter = MBB;
7299  ++MBBIter;
7300
7301  /// First build the CFG
7302  MachineFunction *F = MBB->getParent();
7303  MachineBasicBlock *thisMBB = MBB;
7304  MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
7305  MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
7306  F->insert(MBBIter, newMBB);
7307  F->insert(MBBIter, nextMBB);
7308
7309  // Move all successors to thisMBB to nextMBB
7310  nextMBB->transferSuccessors(thisMBB);
7311
7312  // Update thisMBB to fall through to newMBB
7313  thisMBB->addSuccessor(newMBB);
7314
7315  // newMBB jumps to itself and fall through to nextMBB
7316  newMBB->addSuccessor(nextMBB);
7317  newMBB->addSuccessor(newMBB);
7318
7319  DebugLoc dl = bInstr->getDebugLoc();
7320  // Insert instructions into newMBB based on incoming instruction
7321  // There are 8 "real" operands plus 9 implicit def/uses, ignored here.
7322  assert(bInstr->getNumOperands() < X86AddrNumOperands + 14 &&
7323         "unexpected number of operands");
7324  MachineOperand& dest1Oper = bInstr->getOperand(0);
7325  MachineOperand& dest2Oper = bInstr->getOperand(1);
7326  MachineOperand* argOpers[2 + X86AddrNumOperands];
7327  for (int i=0; i < 2 + X86AddrNumOperands; ++i)
7328    argOpers[i] = &bInstr->getOperand(i+2);
7329
7330  // x86 address has 4 operands: base, index, scale, and displacement
7331  int lastAddrIndx = X86AddrNumOperands - 1; // [0,3]
7332
7333  unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
7334  MachineInstrBuilder MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t1);
7335  for (int i=0; i <= lastAddrIndx; ++i)
7336    (*MIB).addOperand(*argOpers[i]);
7337  unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
7338  MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t2);
7339  // add 4 to displacement.
7340  for (int i=0; i <= lastAddrIndx-2; ++i)
7341    (*MIB).addOperand(*argOpers[i]);
7342  MachineOperand newOp3 = *(argOpers[3]);
7343  if (newOp3.isImm())
7344    newOp3.setImm(newOp3.getImm()+4);
7345  else
7346    newOp3.setOffset(newOp3.getOffset()+4);
7347  (*MIB).addOperand(newOp3);
7348  (*MIB).addOperand(*argOpers[lastAddrIndx]);
7349
7350  // t3/4 are defined later, at the bottom of the loop
7351  unsigned t3 = F->getRegInfo().createVirtualRegister(RC);
7352  unsigned t4 = F->getRegInfo().createVirtualRegister(RC);
7353  BuildMI(newMBB, dl, TII->get(X86::PHI), dest1Oper.getReg())
7354    .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(newMBB);
7355  BuildMI(newMBB, dl, TII->get(X86::PHI), dest2Oper.getReg())
7356    .addReg(t2).addMBB(thisMBB).addReg(t4).addMBB(newMBB);
7357
7358  unsigned tt1 = F->getRegInfo().createVirtualRegister(RC);
7359  unsigned tt2 = F->getRegInfo().createVirtualRegister(RC);
7360  if (invSrc) {
7361    MIB = BuildMI(newMBB, dl, TII->get(NotOpc), tt1).addReg(t1);
7362    MIB = BuildMI(newMBB, dl, TII->get(NotOpc), tt2).addReg(t2);
7363  } else {
7364    tt1 = t1;
7365    tt2 = t2;
7366  }
7367
7368  int valArgIndx = lastAddrIndx + 1;
7369  assert((argOpers[valArgIndx]->isReg() ||
7370          argOpers[valArgIndx]->isImm()) &&
7371         "invalid operand");
7372  unsigned t5 = F->getRegInfo().createVirtualRegister(RC);
7373  unsigned t6 = F->getRegInfo().createVirtualRegister(RC);
7374  if (argOpers[valArgIndx]->isReg())
7375    MIB = BuildMI(newMBB, dl, TII->get(regOpcL), t5);
7376  else
7377    MIB = BuildMI(newMBB, dl, TII->get(immOpcL), t5);
7378  if (regOpcL != X86::MOV32rr)
7379    MIB.addReg(tt1);
7380  (*MIB).addOperand(*argOpers[valArgIndx]);
7381  assert(argOpers[valArgIndx + 1]->isReg() ==
7382         argOpers[valArgIndx]->isReg());
7383  assert(argOpers[valArgIndx + 1]->isImm() ==
7384         argOpers[valArgIndx]->isImm());
7385  if (argOpers[valArgIndx + 1]->isReg())
7386    MIB = BuildMI(newMBB, dl, TII->get(regOpcH), t6);
7387  else
7388    MIB = BuildMI(newMBB, dl, TII->get(immOpcH), t6);
7389  if (regOpcH != X86::MOV32rr)
7390    MIB.addReg(tt2);
7391  (*MIB).addOperand(*argOpers[valArgIndx + 1]);
7392
7393  MIB = BuildMI(newMBB, dl, TII->get(copyOpc), X86::EAX);
7394  MIB.addReg(t1);
7395  MIB = BuildMI(newMBB, dl, TII->get(copyOpc), X86::EDX);
7396  MIB.addReg(t2);
7397
7398  MIB = BuildMI(newMBB, dl, TII->get(copyOpc), X86::EBX);
7399  MIB.addReg(t5);
7400  MIB = BuildMI(newMBB, dl, TII->get(copyOpc), X86::ECX);
7401  MIB.addReg(t6);
7402
7403  MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG8B));
7404  for (int i=0; i <= lastAddrIndx; ++i)
7405    (*MIB).addOperand(*argOpers[i]);
7406
7407  assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
7408  (*MIB).addMemOperand(*F, *bInstr->memoperands_begin());
7409
7410  MIB = BuildMI(newMBB, dl, TII->get(copyOpc), t3);
7411  MIB.addReg(X86::EAX);
7412  MIB = BuildMI(newMBB, dl, TII->get(copyOpc), t4);
7413  MIB.addReg(X86::EDX);
7414
7415  // insert branch
7416  BuildMI(newMBB, dl, TII->get(X86::JNE)).addMBB(newMBB);
7417
7418  F->DeleteMachineInstr(bInstr);   // The pseudo instruction is gone now.
7419  return nextMBB;
7420}
7421
7422// private utility function
7423MachineBasicBlock *
7424X86TargetLowering::EmitAtomicMinMaxWithCustomInserter(MachineInstr *mInstr,
7425                                                      MachineBasicBlock *MBB,
7426                                                      unsigned cmovOpc) const {
7427  // For the atomic min/max operator, we generate
7428  //   thisMBB:
7429  //   newMBB:
7430  //     ld t1 = [min/max.addr]
7431  //     mov t2 = [min/max.val]
7432  //     cmp  t1, t2
7433  //     cmov[cond] t2 = t1
7434  //     mov EAX = t1
7435  //     lcs dest = [bitinstr.addr], t2  [EAX is implicit]
7436  //     bz   newMBB
7437  //     fallthrough -->nextMBB
7438  //
7439  const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
7440  const BasicBlock *LLVM_BB = MBB->getBasicBlock();
7441  MachineFunction::iterator MBBIter = MBB;
7442  ++MBBIter;
7443
7444  /// First build the CFG
7445  MachineFunction *F = MBB->getParent();
7446  MachineBasicBlock *thisMBB = MBB;
7447  MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
7448  MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
7449  F->insert(MBBIter, newMBB);
7450  F->insert(MBBIter, nextMBB);
7451
7452  // Move all successors to thisMBB to nextMBB
7453  nextMBB->transferSuccessors(thisMBB);
7454
7455  // Update thisMBB to fall through to newMBB
7456  thisMBB->addSuccessor(newMBB);
7457
7458  // newMBB jumps to newMBB and fall through to nextMBB
7459  newMBB->addSuccessor(nextMBB);
7460  newMBB->addSuccessor(newMBB);
7461
7462  DebugLoc dl = mInstr->getDebugLoc();
7463  // Insert instructions into newMBB based on incoming instruction
7464  assert(mInstr->getNumOperands() < X86AddrNumOperands + 4 &&
7465         "unexpected number of operands");
7466  MachineOperand& destOper = mInstr->getOperand(0);
7467  MachineOperand* argOpers[2 + X86AddrNumOperands];
7468  int numArgs = mInstr->getNumOperands() - 1;
7469  for (int i=0; i < numArgs; ++i)
7470    argOpers[i] = &mInstr->getOperand(i+1);
7471
7472  // x86 address has 4 operands: base, index, scale, and displacement
7473  int lastAddrIndx = X86AddrNumOperands - 1; // [0,3]
7474  int valArgIndx = lastAddrIndx + 1;
7475
7476  unsigned t1 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
7477  MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rm), t1);
7478  for (int i=0; i <= lastAddrIndx; ++i)
7479    (*MIB).addOperand(*argOpers[i]);
7480
7481  // We only support register and immediate values
7482  assert((argOpers[valArgIndx]->isReg() ||
7483          argOpers[valArgIndx]->isImm()) &&
7484         "invalid operand");
7485
7486  unsigned t2 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
7487  if (argOpers[valArgIndx]->isReg())
7488    MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rr), t2);
7489  else
7490    MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rr), t2);
7491  (*MIB).addOperand(*argOpers[valArgIndx]);
7492
7493  MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rr), X86::EAX);
7494  MIB.addReg(t1);
7495
7496  MIB = BuildMI(newMBB, dl, TII->get(X86::CMP32rr));
7497  MIB.addReg(t1);
7498  MIB.addReg(t2);
7499
7500  // Generate movc
7501  unsigned t3 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
7502  MIB = BuildMI(newMBB, dl, TII->get(cmovOpc),t3);
7503  MIB.addReg(t2);
7504  MIB.addReg(t1);
7505
7506  // Cmp and exchange if none has modified the memory location
7507  MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG32));
7508  for (int i=0; i <= lastAddrIndx; ++i)
7509    (*MIB).addOperand(*argOpers[i]);
7510  MIB.addReg(t3);
7511  assert(mInstr->hasOneMemOperand() && "Unexpected number of memoperand");
7512  (*MIB).addMemOperand(*F, *mInstr->memoperands_begin());
7513
7514  MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rr), destOper.getReg());
7515  MIB.addReg(X86::EAX);
7516
7517  // insert branch
7518  BuildMI(newMBB, dl, TII->get(X86::JNE)).addMBB(newMBB);
7519
7520  F->DeleteMachineInstr(mInstr);   // The pseudo instruction is gone now.
7521  return nextMBB;
7522}
7523
7524
7525MachineBasicBlock *
7526X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
7527                                               MachineBasicBlock *BB) const {
7528  DebugLoc dl = MI->getDebugLoc();
7529  const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
7530  switch (MI->getOpcode()) {
7531  default: assert(false && "Unexpected instr type to insert");
7532  case X86::CMOV_V1I64:
7533  case X86::CMOV_FR32:
7534  case X86::CMOV_FR64:
7535  case X86::CMOV_V4F32:
7536  case X86::CMOV_V2F64:
7537  case X86::CMOV_V2I64: {
7538    // To "insert" a SELECT_CC instruction, we actually have to insert the
7539    // diamond control-flow pattern.  The incoming instruction knows the
7540    // destination vreg to set, the condition code register to branch on, the
7541    // true/false values to select between, and a branch opcode to use.
7542    const BasicBlock *LLVM_BB = BB->getBasicBlock();
7543    MachineFunction::iterator It = BB;
7544    ++It;
7545
7546    //  thisMBB:
7547    //  ...
7548    //   TrueVal = ...
7549    //   cmpTY ccX, r1, r2
7550    //   bCC copy1MBB
7551    //   fallthrough --> copy0MBB
7552    MachineBasicBlock *thisMBB = BB;
7553    MachineFunction *F = BB->getParent();
7554    MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
7555    MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
7556    unsigned Opc =
7557      X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
7558    BuildMI(BB, dl, TII->get(Opc)).addMBB(sinkMBB);
7559    F->insert(It, copy0MBB);
7560    F->insert(It, sinkMBB);
7561    // Update machine-CFG edges by transferring all successors of the current
7562    // block to the new block which will contain the Phi node for the select.
7563    sinkMBB->transferSuccessors(BB);
7564
7565    // Add the true and fallthrough blocks as its successors.
7566    BB->addSuccessor(copy0MBB);
7567    BB->addSuccessor(sinkMBB);
7568
7569    //  copy0MBB:
7570    //   %FalseValue = ...
7571    //   # fallthrough to sinkMBB
7572    BB = copy0MBB;
7573
7574    // Update machine-CFG edges
7575    BB->addSuccessor(sinkMBB);
7576
7577    //  sinkMBB:
7578    //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
7579    //  ...
7580    BB = sinkMBB;
7581    BuildMI(BB, dl, TII->get(X86::PHI), MI->getOperand(0).getReg())
7582      .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
7583      .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
7584
7585    F->DeleteMachineInstr(MI);   // The pseudo instruction is gone now.
7586    return BB;
7587  }
7588
7589  case X86::FP32_TO_INT16_IN_MEM:
7590  case X86::FP32_TO_INT32_IN_MEM:
7591  case X86::FP32_TO_INT64_IN_MEM:
7592  case X86::FP64_TO_INT16_IN_MEM:
7593  case X86::FP64_TO_INT32_IN_MEM:
7594  case X86::FP64_TO_INT64_IN_MEM:
7595  case X86::FP80_TO_INT16_IN_MEM:
7596  case X86::FP80_TO_INT32_IN_MEM:
7597  case X86::FP80_TO_INT64_IN_MEM: {
7598    // Change the floating point control register to use "round towards zero"
7599    // mode when truncating to an integer value.
7600    MachineFunction *F = BB->getParent();
7601    int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2);
7602    addFrameReference(BuildMI(BB, dl, TII->get(X86::FNSTCW16m)), CWFrameIdx);
7603
7604    // Load the old value of the high byte of the control word...
7605    unsigned OldCW =
7606      F->getRegInfo().createVirtualRegister(X86::GR16RegisterClass);
7607    addFrameReference(BuildMI(BB, dl, TII->get(X86::MOV16rm), OldCW),
7608                      CWFrameIdx);
7609
7610    // Set the high part to be round to zero...
7611    addFrameReference(BuildMI(BB, dl, TII->get(X86::MOV16mi)), CWFrameIdx)
7612      .addImm(0xC7F);
7613
7614    // Reload the modified control word now...
7615    addFrameReference(BuildMI(BB, dl, TII->get(X86::FLDCW16m)), CWFrameIdx);
7616
7617    // Restore the memory image of control word to original value
7618    addFrameReference(BuildMI(BB, dl, TII->get(X86::MOV16mr)), CWFrameIdx)
7619      .addReg(OldCW);
7620
7621    // Get the X86 opcode to use.
7622    unsigned Opc;
7623    switch (MI->getOpcode()) {
7624    default: assert(0 && "illegal opcode!");
7625    case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
7626    case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
7627    case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
7628    case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
7629    case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
7630    case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
7631    case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
7632    case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
7633    case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
7634    }
7635
7636    X86AddressMode AM;
7637    MachineOperand &Op = MI->getOperand(0);
7638    if (Op.isReg()) {
7639      AM.BaseType = X86AddressMode::RegBase;
7640      AM.Base.Reg = Op.getReg();
7641    } else {
7642      AM.BaseType = X86AddressMode::FrameIndexBase;
7643      AM.Base.FrameIndex = Op.getIndex();
7644    }
7645    Op = MI->getOperand(1);
7646    if (Op.isImm())
7647      AM.Scale = Op.getImm();
7648    Op = MI->getOperand(2);
7649    if (Op.isImm())
7650      AM.IndexReg = Op.getImm();
7651    Op = MI->getOperand(3);
7652    if (Op.isGlobal()) {
7653      AM.GV = Op.getGlobal();
7654    } else {
7655      AM.Disp = Op.getImm();
7656    }
7657    addFullAddress(BuildMI(BB, dl, TII->get(Opc)), AM)
7658                      .addReg(MI->getOperand(X86AddrNumOperands).getReg());
7659
7660    // Reload the original control word now.
7661    addFrameReference(BuildMI(BB, dl, TII->get(X86::FLDCW16m)), CWFrameIdx);
7662
7663    F->DeleteMachineInstr(MI);   // The pseudo instruction is gone now.
7664    return BB;
7665  }
7666  case X86::ATOMAND32:
7667    return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
7668                                               X86::AND32ri, X86::MOV32rm,
7669                                               X86::LCMPXCHG32, X86::MOV32rr,
7670                                               X86::NOT32r, X86::EAX,
7671                                               X86::GR32RegisterClass);
7672  case X86::ATOMOR32:
7673    return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR32rr,
7674                                               X86::OR32ri, X86::MOV32rm,
7675                                               X86::LCMPXCHG32, X86::MOV32rr,
7676                                               X86::NOT32r, X86::EAX,
7677                                               X86::GR32RegisterClass);
7678  case X86::ATOMXOR32:
7679    return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR32rr,
7680                                               X86::XOR32ri, X86::MOV32rm,
7681                                               X86::LCMPXCHG32, X86::MOV32rr,
7682                                               X86::NOT32r, X86::EAX,
7683                                               X86::GR32RegisterClass);
7684  case X86::ATOMNAND32:
7685    return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
7686                                               X86::AND32ri, X86::MOV32rm,
7687                                               X86::LCMPXCHG32, X86::MOV32rr,
7688                                               X86::NOT32r, X86::EAX,
7689                                               X86::GR32RegisterClass, true);
7690  case X86::ATOMMIN32:
7691    return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL32rr);
7692  case X86::ATOMMAX32:
7693    return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG32rr);
7694  case X86::ATOMUMIN32:
7695    return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB32rr);
7696  case X86::ATOMUMAX32:
7697    return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA32rr);
7698
7699  case X86::ATOMAND16:
7700    return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
7701                                               X86::AND16ri, X86::MOV16rm,
7702                                               X86::LCMPXCHG16, X86::MOV16rr,
7703                                               X86::NOT16r, X86::AX,
7704                                               X86::GR16RegisterClass);
7705  case X86::ATOMOR16:
7706    return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR16rr,
7707                                               X86::OR16ri, X86::MOV16rm,
7708                                               X86::LCMPXCHG16, X86::MOV16rr,
7709                                               X86::NOT16r, X86::AX,
7710                                               X86::GR16RegisterClass);
7711  case X86::ATOMXOR16:
7712    return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR16rr,
7713                                               X86::XOR16ri, X86::MOV16rm,
7714                                               X86::LCMPXCHG16, X86::MOV16rr,
7715                                               X86::NOT16r, X86::AX,
7716                                               X86::GR16RegisterClass);
7717  case X86::ATOMNAND16:
7718    return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
7719                                               X86::AND16ri, X86::MOV16rm,
7720                                               X86::LCMPXCHG16, X86::MOV16rr,
7721                                               X86::NOT16r, X86::AX,
7722                                               X86::GR16RegisterClass, true);
7723  case X86::ATOMMIN16:
7724    return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL16rr);
7725  case X86::ATOMMAX16:
7726    return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG16rr);
7727  case X86::ATOMUMIN16:
7728    return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB16rr);
7729  case X86::ATOMUMAX16:
7730    return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA16rr);
7731
7732  case X86::ATOMAND8:
7733    return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
7734                                               X86::AND8ri, X86::MOV8rm,
7735                                               X86::LCMPXCHG8, X86::MOV8rr,
7736                                               X86::NOT8r, X86::AL,
7737                                               X86::GR8RegisterClass);
7738  case X86::ATOMOR8:
7739    return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR8rr,
7740                                               X86::OR8ri, X86::MOV8rm,
7741                                               X86::LCMPXCHG8, X86::MOV8rr,
7742                                               X86::NOT8r, X86::AL,
7743                                               X86::GR8RegisterClass);
7744  case X86::ATOMXOR8:
7745    return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR8rr,
7746                                               X86::XOR8ri, X86::MOV8rm,
7747                                               X86::LCMPXCHG8, X86::MOV8rr,
7748                                               X86::NOT8r, X86::AL,
7749                                               X86::GR8RegisterClass);
7750  case X86::ATOMNAND8:
7751    return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
7752                                               X86::AND8ri, X86::MOV8rm,
7753                                               X86::LCMPXCHG8, X86::MOV8rr,
7754                                               X86::NOT8r, X86::AL,
7755                                               X86::GR8RegisterClass, true);
7756  // FIXME: There are no CMOV8 instructions; MIN/MAX need some other way.
7757  // This group is for 64-bit host.
7758  case X86::ATOMAND64:
7759    return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
7760                                               X86::AND64ri32, X86::MOV64rm,
7761                                               X86::LCMPXCHG64, X86::MOV64rr,
7762                                               X86::NOT64r, X86::RAX,
7763                                               X86::GR64RegisterClass);
7764  case X86::ATOMOR64:
7765    return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR64rr,
7766                                               X86::OR64ri32, X86::MOV64rm,
7767                                               X86::LCMPXCHG64, X86::MOV64rr,
7768                                               X86::NOT64r, X86::RAX,
7769                                               X86::GR64RegisterClass);
7770  case X86::ATOMXOR64:
7771    return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR64rr,
7772                                               X86::XOR64ri32, X86::MOV64rm,
7773                                               X86::LCMPXCHG64, X86::MOV64rr,
7774                                               X86::NOT64r, X86::RAX,
7775                                               X86::GR64RegisterClass);
7776  case X86::ATOMNAND64:
7777    return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
7778                                               X86::AND64ri32, X86::MOV64rm,
7779                                               X86::LCMPXCHG64, X86::MOV64rr,
7780                                               X86::NOT64r, X86::RAX,
7781                                               X86::GR64RegisterClass, true);
7782  case X86::ATOMMIN64:
7783    return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL64rr);
7784  case X86::ATOMMAX64:
7785    return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG64rr);
7786  case X86::ATOMUMIN64:
7787    return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB64rr);
7788  case X86::ATOMUMAX64:
7789    return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA64rr);
7790
7791  // This group does 64-bit operations on a 32-bit host.
7792  case X86::ATOMAND6432:
7793    return EmitAtomicBit6432WithCustomInserter(MI, BB,
7794                                               X86::AND32rr, X86::AND32rr,
7795                                               X86::AND32ri, X86::AND32ri,
7796                                               false);
7797  case X86::ATOMOR6432:
7798    return EmitAtomicBit6432WithCustomInserter(MI, BB,
7799                                               X86::OR32rr, X86::OR32rr,
7800                                               X86::OR32ri, X86::OR32ri,
7801                                               false);
7802  case X86::ATOMXOR6432:
7803    return EmitAtomicBit6432WithCustomInserter(MI, BB,
7804                                               X86::XOR32rr, X86::XOR32rr,
7805                                               X86::XOR32ri, X86::XOR32ri,
7806                                               false);
7807  case X86::ATOMNAND6432:
7808    return EmitAtomicBit6432WithCustomInserter(MI, BB,
7809                                               X86::AND32rr, X86::AND32rr,
7810                                               X86::AND32ri, X86::AND32ri,
7811                                               true);
7812  case X86::ATOMADD6432:
7813    return EmitAtomicBit6432WithCustomInserter(MI, BB,
7814                                               X86::ADD32rr, X86::ADC32rr,
7815                                               X86::ADD32ri, X86::ADC32ri,
7816                                               false);
7817  case X86::ATOMSUB6432:
7818    return EmitAtomicBit6432WithCustomInserter(MI, BB,
7819                                               X86::SUB32rr, X86::SBB32rr,
7820                                               X86::SUB32ri, X86::SBB32ri,
7821                                               false);
7822  case X86::ATOMSWAP6432:
7823    return EmitAtomicBit6432WithCustomInserter(MI, BB,
7824                                               X86::MOV32rr, X86::MOV32rr,
7825                                               X86::MOV32ri, X86::MOV32ri,
7826                                               false);
7827  }
7828}
7829
7830//===----------------------------------------------------------------------===//
7831//                           X86 Optimization Hooks
7832//===----------------------------------------------------------------------===//
7833
7834void X86TargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
7835                                                       const APInt &Mask,
7836                                                       APInt &KnownZero,
7837                                                       APInt &KnownOne,
7838                                                       const SelectionDAG &DAG,
7839                                                       unsigned Depth) const {
7840  unsigned Opc = Op.getOpcode();
7841  assert((Opc >= ISD::BUILTIN_OP_END ||
7842          Opc == ISD::INTRINSIC_WO_CHAIN ||
7843          Opc == ISD::INTRINSIC_W_CHAIN ||
7844          Opc == ISD::INTRINSIC_VOID) &&
7845         "Should use MaskedValueIsZero if you don't know whether Op"
7846         " is a target node!");
7847
7848  KnownZero = KnownOne = APInt(Mask.getBitWidth(), 0);   // Don't know anything.
7849  switch (Opc) {
7850  default: break;
7851  case X86ISD::ADD:
7852  case X86ISD::SUB:
7853  case X86ISD::SMUL:
7854  case X86ISD::UMUL:
7855  case X86ISD::INC:
7856  case X86ISD::DEC:
7857    // These nodes' second result is a boolean.
7858    if (Op.getResNo() == 0)
7859      break;
7860    // Fallthrough
7861  case X86ISD::SETCC:
7862    KnownZero |= APInt::getHighBitsSet(Mask.getBitWidth(),
7863                                       Mask.getBitWidth() - 1);
7864    break;
7865  }
7866}
7867
7868/// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
7869/// node is a GlobalAddress + offset.
7870bool X86TargetLowering::isGAPlusOffset(SDNode *N,
7871                                       GlobalValue* &GA, int64_t &Offset) const{
7872  if (N->getOpcode() == X86ISD::Wrapper) {
7873    if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
7874      GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
7875      Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
7876      return true;
7877    }
7878  }
7879  return TargetLowering::isGAPlusOffset(N, GA, Offset);
7880}
7881
7882static bool isBaseAlignmentOfN(unsigned N, SDNode *Base,
7883                               const TargetLowering &TLI) {
7884  GlobalValue *GV;
7885  int64_t Offset = 0;
7886  if (TLI.isGAPlusOffset(Base, GV, Offset))
7887    return (GV->getAlignment() >= N && (Offset % N) == 0);
7888  // DAG combine handles the stack object case.
7889  return false;
7890}
7891
7892static bool EltsFromConsecutiveLoads(ShuffleVectorSDNode *N, unsigned NumElems,
7893                                     MVT EVT, LoadSDNode *&LDBase,
7894                                     unsigned &LastLoadedElt,
7895                                     SelectionDAG &DAG, MachineFrameInfo *MFI,
7896                                     const TargetLowering &TLI) {
7897  LDBase = NULL;
7898  LastLoadedElt = -1U;
7899  for (unsigned i = 0; i < NumElems; ++i) {
7900    if (N->getMaskElt(i) < 0) {
7901      if (!LDBase)
7902        return false;
7903      continue;
7904    }
7905
7906    SDValue Elt = DAG.getShuffleScalarElt(N, i);
7907    if (!Elt.getNode() ||
7908        (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
7909      return false;
7910    if (!LDBase) {
7911      if (Elt.getNode()->getOpcode() == ISD::UNDEF)
7912        return false;
7913      LDBase = cast<LoadSDNode>(Elt.getNode());
7914      LastLoadedElt = i;
7915      continue;
7916    }
7917    if (Elt.getOpcode() == ISD::UNDEF)
7918      continue;
7919
7920    LoadSDNode *LD = cast<LoadSDNode>(Elt);
7921    if (!TLI.isConsecutiveLoad(LD, LDBase, EVT.getSizeInBits()/8, i, MFI))
7922      return false;
7923    LastLoadedElt = i;
7924  }
7925  return true;
7926}
7927
7928/// PerformShuffleCombine - Combine a vector_shuffle that is equal to
7929/// build_vector load1, load2, load3, load4, <0, 1, 2, 3> into a 128-bit load
7930/// if the load addresses are consecutive, non-overlapping, and in the right
7931/// order.  In the case of v2i64, it will see if it can rewrite the
7932/// shuffle to be an appropriate build vector so it can take advantage of
7933// performBuildVectorCombine.
7934static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
7935                                     const TargetLowering &TLI) {
7936  DebugLoc dl = N->getDebugLoc();
7937  MVT VT = N->getValueType(0);
7938  MVT EVT = VT.getVectorElementType();
7939  ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
7940  unsigned NumElems = VT.getVectorNumElements();
7941
7942  if (VT.getSizeInBits() != 128)
7943    return SDValue();
7944
7945  // Try to combine a vector_shuffle into a 128-bit load.
7946  MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7947  LoadSDNode *LD = NULL;
7948  unsigned LastLoadedElt;
7949  if (!EltsFromConsecutiveLoads(SVN, NumElems, EVT, LD, LastLoadedElt, DAG,
7950                                MFI, TLI))
7951    return SDValue();
7952
7953  if (LastLoadedElt == NumElems - 1) {
7954    if (isBaseAlignmentOfN(16, LD->getBasePtr().getNode(), TLI))
7955      return DAG.getLoad(VT, dl, LD->getChain(), LD->getBasePtr(),
7956                         LD->getSrcValue(), LD->getSrcValueOffset(),
7957                         LD->isVolatile());
7958    return DAG.getLoad(VT, dl, LD->getChain(), LD->getBasePtr(),
7959                       LD->getSrcValue(), LD->getSrcValueOffset(),
7960                       LD->isVolatile(), LD->getAlignment());
7961  } else if (NumElems == 4 && LastLoadedElt == 1) {
7962    SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
7963    SDValue Ops[] = { LD->getChain(), LD->getBasePtr() };
7964    SDValue ResNode = DAG.getNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops, 2);
7965    return DAG.getNode(ISD::BIT_CONVERT, dl, VT, ResNode);
7966  }
7967  return SDValue();
7968}
7969
7970/// PerformSELECTCombine - Do target-specific dag combines on SELECT nodes.
7971static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
7972                                    const X86Subtarget *Subtarget) {
7973  DebugLoc DL = N->getDebugLoc();
7974  SDValue Cond = N->getOperand(0);
7975  // Get the LHS/RHS of the select.
7976  SDValue LHS = N->getOperand(1);
7977  SDValue RHS = N->getOperand(2);
7978
7979  // If we have SSE[12] support, try to form min/max nodes.
7980  if (Subtarget->hasSSE2() &&
7981      (LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64) &&
7982      Cond.getOpcode() == ISD::SETCC) {
7983    ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
7984
7985    unsigned Opcode = 0;
7986    if (LHS == Cond.getOperand(0) && RHS == Cond.getOperand(1)) {
7987      switch (CC) {
7988      default: break;
7989      case ISD::SETOLE: // (X <= Y) ? X : Y -> min
7990      case ISD::SETULE:
7991      case ISD::SETLE:
7992        if (!UnsafeFPMath) break;
7993        // FALL THROUGH.
7994      case ISD::SETOLT:  // (X olt/lt Y) ? X : Y -> min
7995      case ISD::SETLT:
7996        Opcode = X86ISD::FMIN;
7997        break;
7998
7999      case ISD::SETOGT: // (X > Y) ? X : Y -> max
8000      case ISD::SETUGT:
8001      case ISD::SETGT:
8002        if (!UnsafeFPMath) break;
8003        // FALL THROUGH.
8004      case ISD::SETUGE:  // (X uge/ge Y) ? X : Y -> max
8005      case ISD::SETGE:
8006        Opcode = X86ISD::FMAX;
8007        break;
8008      }
8009    } else if (LHS == Cond.getOperand(1) && RHS == Cond.getOperand(0)) {
8010      switch (CC) {
8011      default: break;
8012      case ISD::SETOGT: // (X > Y) ? Y : X -> min
8013      case ISD::SETUGT:
8014      case ISD::SETGT:
8015        if (!UnsafeFPMath) break;
8016        // FALL THROUGH.
8017      case ISD::SETUGE:  // (X uge/ge Y) ? Y : X -> min
8018      case ISD::SETGE:
8019        Opcode = X86ISD::FMIN;
8020        break;
8021
8022      case ISD::SETOLE:   // (X <= Y) ? Y : X -> max
8023      case ISD::SETULE:
8024      case ISD::SETLE:
8025        if (!UnsafeFPMath) break;
8026        // FALL THROUGH.
8027      case ISD::SETOLT:   // (X olt/lt Y) ? Y : X -> max
8028      case ISD::SETLT:
8029        Opcode = X86ISD::FMAX;
8030        break;
8031      }
8032    }
8033
8034    if (Opcode)
8035      return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
8036  }
8037
8038  // If this is a select between two integer constants, try to do some
8039  // optimizations.
8040  if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
8041    if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
8042      // Don't do this for crazy integer types.
8043      if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
8044        // If this is efficiently invertible, canonicalize the LHSC/RHSC values
8045        // so that TrueC (the true value) is larger than FalseC.
8046        bool NeedsCondInvert = false;
8047
8048        if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
8049            // Efficiently invertible.
8050            (Cond.getOpcode() == ISD::SETCC ||  // setcc -> invertible.
8051             (Cond.getOpcode() == ISD::XOR &&   // xor(X, C) -> invertible.
8052              isa<ConstantSDNode>(Cond.getOperand(1))))) {
8053          NeedsCondInvert = true;
8054          std::swap(TrueC, FalseC);
8055        }
8056
8057        // Optimize C ? 8 : 0 -> zext(C) << 3.  Likewise for any pow2/0.
8058        if (FalseC->getAPIntValue() == 0 &&
8059            TrueC->getAPIntValue().isPowerOf2()) {
8060          if (NeedsCondInvert) // Invert the condition if needed.
8061            Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
8062                               DAG.getConstant(1, Cond.getValueType()));
8063
8064          // Zero extend the condition if needed.
8065          Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
8066
8067          unsigned ShAmt = TrueC->getAPIntValue().logBase2();
8068          return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
8069                             DAG.getConstant(ShAmt, MVT::i8));
8070        }
8071
8072        // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
8073        if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
8074          if (NeedsCondInvert) // Invert the condition if needed.
8075            Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
8076                               DAG.getConstant(1, Cond.getValueType()));
8077
8078          // Zero extend the condition if needed.
8079          Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
8080                             FalseC->getValueType(0), Cond);
8081          return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
8082                             SDValue(FalseC, 0));
8083        }
8084
8085        // Optimize cases that will turn into an LEA instruction.  This requires
8086        // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
8087        if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
8088          uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
8089          if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
8090
8091          bool isFastMultiplier = false;
8092          if (Diff < 10) {
8093            switch ((unsigned char)Diff) {
8094              default: break;
8095              case 1:  // result = add base, cond
8096              case 2:  // result = lea base(    , cond*2)
8097              case 3:  // result = lea base(cond, cond*2)
8098              case 4:  // result = lea base(    , cond*4)
8099              case 5:  // result = lea base(cond, cond*4)
8100              case 8:  // result = lea base(    , cond*8)
8101              case 9:  // result = lea base(cond, cond*8)
8102                isFastMultiplier = true;
8103                break;
8104            }
8105          }
8106
8107          if (isFastMultiplier) {
8108            APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
8109            if (NeedsCondInvert) // Invert the condition if needed.
8110              Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
8111                                 DAG.getConstant(1, Cond.getValueType()));
8112
8113            // Zero extend the condition if needed.
8114            Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
8115                               Cond);
8116            // Scale the condition by the difference.
8117            if (Diff != 1)
8118              Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
8119                                 DAG.getConstant(Diff, Cond.getValueType()));
8120
8121            // Add the base if non-zero.
8122            if (FalseC->getAPIntValue() != 0)
8123              Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
8124                                 SDValue(FalseC, 0));
8125            return Cond;
8126          }
8127        }
8128      }
8129  }
8130
8131  return SDValue();
8132}
8133
8134/// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
8135static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
8136                                  TargetLowering::DAGCombinerInfo &DCI) {
8137  DebugLoc DL = N->getDebugLoc();
8138
8139  // If the flag operand isn't dead, don't touch this CMOV.
8140  if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
8141    return SDValue();
8142
8143  // If this is a select between two integer constants, try to do some
8144  // optimizations.  Note that the operands are ordered the opposite of SELECT
8145  // operands.
8146  if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(N->getOperand(1))) {
8147    if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
8148      // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
8149      // larger than FalseC (the false value).
8150      X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
8151
8152      if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
8153        CC = X86::GetOppositeBranchCondition(CC);
8154        std::swap(TrueC, FalseC);
8155      }
8156
8157      // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3.  Likewise for any pow2/0.
8158      // This is efficient for any integer data type (including i8/i16) and
8159      // shift amount.
8160      if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
8161        SDValue Cond = N->getOperand(3);
8162        Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
8163                           DAG.getConstant(CC, MVT::i8), Cond);
8164
8165        // Zero extend the condition if needed.
8166        Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
8167
8168        unsigned ShAmt = TrueC->getAPIntValue().logBase2();
8169        Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
8170                           DAG.getConstant(ShAmt, MVT::i8));
8171        if (N->getNumValues() == 2)  // Dead flag value?
8172          return DCI.CombineTo(N, Cond, SDValue());
8173        return Cond;
8174      }
8175
8176      // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.  This is efficient
8177      // for any integer data type, including i8/i16.
8178      if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
8179        SDValue Cond = N->getOperand(3);
8180        Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
8181                           DAG.getConstant(CC, MVT::i8), Cond);
8182
8183        // Zero extend the condition if needed.
8184        Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
8185                           FalseC->getValueType(0), Cond);
8186        Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
8187                           SDValue(FalseC, 0));
8188
8189        if (N->getNumValues() == 2)  // Dead flag value?
8190          return DCI.CombineTo(N, Cond, SDValue());
8191        return Cond;
8192      }
8193
8194      // Optimize cases that will turn into an LEA instruction.  This requires
8195      // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
8196      if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
8197        uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
8198        if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
8199
8200        bool isFastMultiplier = false;
8201        if (Diff < 10) {
8202          switch ((unsigned char)Diff) {
8203          default: break;
8204          case 1:  // result = add base, cond
8205          case 2:  // result = lea base(    , cond*2)
8206          case 3:  // result = lea base(cond, cond*2)
8207          case 4:  // result = lea base(    , cond*4)
8208          case 5:  // result = lea base(cond, cond*4)
8209          case 8:  // result = lea base(    , cond*8)
8210          case 9:  // result = lea base(cond, cond*8)
8211            isFastMultiplier = true;
8212            break;
8213          }
8214        }
8215
8216        if (isFastMultiplier) {
8217          APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
8218          SDValue Cond = N->getOperand(3);
8219          Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
8220                             DAG.getConstant(CC, MVT::i8), Cond);
8221          // Zero extend the condition if needed.
8222          Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
8223                             Cond);
8224          // Scale the condition by the difference.
8225          if (Diff != 1)
8226            Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
8227                               DAG.getConstant(Diff, Cond.getValueType()));
8228
8229          // Add the base if non-zero.
8230          if (FalseC->getAPIntValue() != 0)
8231            Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
8232                               SDValue(FalseC, 0));
8233          if (N->getNumValues() == 2)  // Dead flag value?
8234            return DCI.CombineTo(N, Cond, SDValue());
8235          return Cond;
8236        }
8237      }
8238    }
8239  }
8240  return SDValue();
8241}
8242
8243
8244/// PerformMulCombine - Optimize a single multiply with constant into two
8245/// in order to implement it with two cheaper instructions, e.g.
8246/// LEA + SHL, LEA + LEA.
8247static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
8248                                 TargetLowering::DAGCombinerInfo &DCI) {
8249  if (DAG.getMachineFunction().
8250      getFunction()->hasFnAttr(Attribute::OptimizeForSize))
8251    return SDValue();
8252
8253  if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
8254    return SDValue();
8255
8256  MVT VT = N->getValueType(0);
8257  if (VT != MVT::i64)
8258    return SDValue();
8259
8260  ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
8261  if (!C)
8262    return SDValue();
8263  uint64_t MulAmt = C->getZExtValue();
8264  if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
8265    return SDValue();
8266
8267  uint64_t MulAmt1 = 0;
8268  uint64_t MulAmt2 = 0;
8269  if ((MulAmt % 9) == 0) {
8270    MulAmt1 = 9;
8271    MulAmt2 = MulAmt / 9;
8272  } else if ((MulAmt % 5) == 0) {
8273    MulAmt1 = 5;
8274    MulAmt2 = MulAmt / 5;
8275  } else if ((MulAmt % 3) == 0) {
8276    MulAmt1 = 3;
8277    MulAmt2 = MulAmt / 3;
8278  }
8279  if (MulAmt2 &&
8280      (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
8281    DebugLoc DL = N->getDebugLoc();
8282
8283    if (isPowerOf2_64(MulAmt2) &&
8284        !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
8285      // If second multiplifer is pow2, issue it first. We want the multiply by
8286      // 3, 5, or 9 to be folded into the addressing mode unless the lone use
8287      // is an add.
8288      std::swap(MulAmt1, MulAmt2);
8289
8290    SDValue NewMul;
8291    if (isPowerOf2_64(MulAmt1))
8292      NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
8293                           DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
8294    else
8295      NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
8296                           DAG.getConstant(MulAmt1, VT));
8297
8298    if (isPowerOf2_64(MulAmt2))
8299      NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
8300                           DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
8301    else
8302      NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
8303                           DAG.getConstant(MulAmt2, VT));
8304
8305    // Do not add new nodes to DAG combiner worklist.
8306    DCI.CombineTo(N, NewMul, false);
8307  }
8308  return SDValue();
8309}
8310
8311
8312/// PerformShiftCombine - Transforms vector shift nodes to use vector shifts
8313///                       when possible.
8314static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
8315                                   const X86Subtarget *Subtarget) {
8316  // On X86 with SSE2 support, we can transform this to a vector shift if
8317  // all elements are shifted by the same amount.  We can't do this in legalize
8318  // because the a constant vector is typically transformed to a constant pool
8319  // so we have no knowledge of the shift amount.
8320  if (!Subtarget->hasSSE2())
8321    return SDValue();
8322
8323  MVT VT = N->getValueType(0);
8324  if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16)
8325    return SDValue();
8326
8327  SDValue ShAmtOp = N->getOperand(1);
8328  MVT EltVT = VT.getVectorElementType();
8329  DebugLoc DL = N->getDebugLoc();
8330  SDValue BaseShAmt;
8331  if (ShAmtOp.getOpcode() == ISD::BUILD_VECTOR) {
8332    unsigned NumElts = VT.getVectorNumElements();
8333    unsigned i = 0;
8334    for (; i != NumElts; ++i) {
8335      SDValue Arg = ShAmtOp.getOperand(i);
8336      if (Arg.getOpcode() == ISD::UNDEF) continue;
8337      BaseShAmt = Arg;
8338      break;
8339    }
8340    for (; i != NumElts; ++i) {
8341      SDValue Arg = ShAmtOp.getOperand(i);
8342      if (Arg.getOpcode() == ISD::UNDEF) continue;
8343      if (Arg != BaseShAmt) {
8344        return SDValue();
8345      }
8346    }
8347  } else if (ShAmtOp.getOpcode() == ISD::VECTOR_SHUFFLE &&
8348             cast<ShuffleVectorSDNode>(ShAmtOp)->isSplat()) {
8349    BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, ShAmtOp,
8350                            DAG.getIntPtrConstant(0));
8351  } else
8352    return SDValue();
8353
8354  if (EltVT.bitsGT(MVT::i32))
8355    BaseShAmt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, BaseShAmt);
8356  else if (EltVT.bitsLT(MVT::i32))
8357    BaseShAmt = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, BaseShAmt);
8358
8359  // The shift amount is identical so we can do a vector shift.
8360  SDValue  ValOp = N->getOperand(0);
8361  switch (N->getOpcode()) {
8362  default:
8363    assert(0 && "Unknown shift opcode!");
8364    break;
8365  case ISD::SHL:
8366    if (VT == MVT::v2i64)
8367      return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
8368                         DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
8369                         ValOp, BaseShAmt);
8370    if (VT == MVT::v4i32)
8371      return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
8372                         DAG.getConstant(Intrinsic::x86_sse2_pslli_d, MVT::i32),
8373                         ValOp, BaseShAmt);
8374    if (VT == MVT::v8i16)
8375      return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
8376                         DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32),
8377                         ValOp, BaseShAmt);
8378    break;
8379  case ISD::SRA:
8380    if (VT == MVT::v4i32)
8381      return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
8382                         DAG.getConstant(Intrinsic::x86_sse2_psrai_d, MVT::i32),
8383                         ValOp, BaseShAmt);
8384    if (VT == MVT::v8i16)
8385      return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
8386                         DAG.getConstant(Intrinsic::x86_sse2_psrai_w, MVT::i32),
8387                         ValOp, BaseShAmt);
8388    break;
8389  case ISD::SRL:
8390    if (VT == MVT::v2i64)
8391      return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
8392                         DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
8393                         ValOp, BaseShAmt);
8394    if (VT == MVT::v4i32)
8395      return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
8396                         DAG.getConstant(Intrinsic::x86_sse2_psrli_d, MVT::i32),
8397                         ValOp, BaseShAmt);
8398    if (VT ==  MVT::v8i16)
8399      return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
8400                         DAG.getConstant(Intrinsic::x86_sse2_psrli_w, MVT::i32),
8401                         ValOp, BaseShAmt);
8402    break;
8403  }
8404  return SDValue();
8405}
8406
8407/// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
8408static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
8409                                   const X86Subtarget *Subtarget) {
8410  // Turn load->store of MMX types into GPR load/stores.  This avoids clobbering
8411  // the FP state in cases where an emms may be missing.
8412  // A preferable solution to the general problem is to figure out the right
8413  // places to insert EMMS.  This qualifies as a quick hack.
8414
8415  // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
8416  StoreSDNode *St = cast<StoreSDNode>(N);
8417  MVT VT = St->getValue().getValueType();
8418  if (VT.getSizeInBits() != 64)
8419    return SDValue();
8420
8421  const Function *F = DAG.getMachineFunction().getFunction();
8422  bool NoImplicitFloatOps = F->hasFnAttr(Attribute::NoImplicitFloat);
8423  bool F64IsLegal = !UseSoftFloat && !NoImplicitFloatOps
8424    && Subtarget->hasSSE2();
8425  if ((VT.isVector() ||
8426       (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
8427      isa<LoadSDNode>(St->getValue()) &&
8428      !cast<LoadSDNode>(St->getValue())->isVolatile() &&
8429      St->getChain().hasOneUse() && !St->isVolatile()) {
8430    SDNode* LdVal = St->getValue().getNode();
8431    LoadSDNode *Ld = 0;
8432    int TokenFactorIndex = -1;
8433    SmallVector<SDValue, 8> Ops;
8434    SDNode* ChainVal = St->getChain().getNode();
8435    // Must be a store of a load.  We currently handle two cases:  the load
8436    // is a direct child, and it's under an intervening TokenFactor.  It is
8437    // possible to dig deeper under nested TokenFactors.
8438    if (ChainVal == LdVal)
8439      Ld = cast<LoadSDNode>(St->getChain());
8440    else if (St->getValue().hasOneUse() &&
8441             ChainVal->getOpcode() == ISD::TokenFactor) {
8442      for (unsigned i=0, e = ChainVal->getNumOperands(); i != e; ++i) {
8443        if (ChainVal->getOperand(i).getNode() == LdVal) {
8444          TokenFactorIndex = i;
8445          Ld = cast<LoadSDNode>(St->getValue());
8446        } else
8447          Ops.push_back(ChainVal->getOperand(i));
8448      }
8449    }
8450
8451    if (!Ld || !ISD::isNormalLoad(Ld))
8452      return SDValue();
8453
8454    // If this is not the MMX case, i.e. we are just turning i64 load/store
8455    // into f64 load/store, avoid the transformation if there are multiple
8456    // uses of the loaded value.
8457    if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
8458      return SDValue();
8459
8460    DebugLoc LdDL = Ld->getDebugLoc();
8461    DebugLoc StDL = N->getDebugLoc();
8462    // If we are a 64-bit capable x86, lower to a single movq load/store pair.
8463    // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
8464    // pair instead.
8465    if (Subtarget->is64Bit() || F64IsLegal) {
8466      MVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
8467      SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(),
8468                                  Ld->getBasePtr(), Ld->getSrcValue(),
8469                                  Ld->getSrcValueOffset(), Ld->isVolatile(),
8470                                  Ld->getAlignment());
8471      SDValue NewChain = NewLd.getValue(1);
8472      if (TokenFactorIndex != -1) {
8473        Ops.push_back(NewChain);
8474        NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
8475                               Ops.size());
8476      }
8477      return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
8478                          St->getSrcValue(), St->getSrcValueOffset(),
8479                          St->isVolatile(), St->getAlignment());
8480    }
8481
8482    // Otherwise, lower to two pairs of 32-bit loads / stores.
8483    SDValue LoAddr = Ld->getBasePtr();
8484    SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
8485                                 DAG.getConstant(4, MVT::i32));
8486
8487    SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
8488                               Ld->getSrcValue(), Ld->getSrcValueOffset(),
8489                               Ld->isVolatile(), Ld->getAlignment());
8490    SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
8491                               Ld->getSrcValue(), Ld->getSrcValueOffset()+4,
8492                               Ld->isVolatile(),
8493                               MinAlign(Ld->getAlignment(), 4));
8494
8495    SDValue NewChain = LoLd.getValue(1);
8496    if (TokenFactorIndex != -1) {
8497      Ops.push_back(LoLd);
8498      Ops.push_back(HiLd);
8499      NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
8500                             Ops.size());
8501    }
8502
8503    LoAddr = St->getBasePtr();
8504    HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
8505                         DAG.getConstant(4, MVT::i32));
8506
8507    SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
8508                                St->getSrcValue(), St->getSrcValueOffset(),
8509                                St->isVolatile(), St->getAlignment());
8510    SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
8511                                St->getSrcValue(),
8512                                St->getSrcValueOffset() + 4,
8513                                St->isVolatile(),
8514                                MinAlign(St->getAlignment(), 4));
8515    return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
8516  }
8517  return SDValue();
8518}
8519
8520/// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
8521/// X86ISD::FXOR nodes.
8522static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
8523  assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
8524  // F[X]OR(0.0, x) -> x
8525  // F[X]OR(x, 0.0) -> x
8526  if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
8527    if (C->getValueAPF().isPosZero())
8528      return N->getOperand(1);
8529  if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
8530    if (C->getValueAPF().isPosZero())
8531      return N->getOperand(0);
8532  return SDValue();
8533}
8534
8535/// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
8536static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
8537  // FAND(0.0, x) -> 0.0
8538  // FAND(x, 0.0) -> 0.0
8539  if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
8540    if (C->getValueAPF().isPosZero())
8541      return N->getOperand(0);
8542  if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
8543    if (C->getValueAPF().isPosZero())
8544      return N->getOperand(1);
8545  return SDValue();
8546}
8547
8548static SDValue PerformBTCombine(SDNode *N,
8549                                SelectionDAG &DAG,
8550                                TargetLowering::DAGCombinerInfo &DCI) {
8551  // BT ignores high bits in the bit index operand.
8552  SDValue Op1 = N->getOperand(1);
8553  if (Op1.hasOneUse()) {
8554    unsigned BitWidth = Op1.getValueSizeInBits();
8555    APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
8556    APInt KnownZero, KnownOne;
8557    TargetLowering::TargetLoweringOpt TLO(DAG);
8558    TargetLowering &TLI = DAG.getTargetLoweringInfo();
8559    if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
8560        TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
8561      DCI.CommitTargetLoweringOpt(TLO);
8562  }
8563  return SDValue();
8564}
8565
8566static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
8567  SDValue Op = N->getOperand(0);
8568  if (Op.getOpcode() == ISD::BIT_CONVERT)
8569    Op = Op.getOperand(0);
8570  MVT VT = N->getValueType(0), OpVT = Op.getValueType();
8571  if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
8572      VT.getVectorElementType().getSizeInBits() ==
8573      OpVT.getVectorElementType().getSizeInBits()) {
8574    return DAG.getNode(ISD::BIT_CONVERT, N->getDebugLoc(), VT, Op);
8575  }
8576  return SDValue();
8577}
8578
8579// On X86 and X86-64, atomic operations are lowered to locked instructions.
8580// Locked instructions, in turn, have implicit fence semantics (all memory
8581// operations are flushed before issuing the locked instruction, and the
8582// are not buffered), so we can fold away the common pattern of
8583// fence-atomic-fence.
8584static SDValue PerformMEMBARRIERCombine(SDNode* N, SelectionDAG &DAG) {
8585  SDValue atomic = N->getOperand(0);
8586  switch (atomic.getOpcode()) {
8587    case ISD::ATOMIC_CMP_SWAP:
8588    case ISD::ATOMIC_SWAP:
8589    case ISD::ATOMIC_LOAD_ADD:
8590    case ISD::ATOMIC_LOAD_SUB:
8591    case ISD::ATOMIC_LOAD_AND:
8592    case ISD::ATOMIC_LOAD_OR:
8593    case ISD::ATOMIC_LOAD_XOR:
8594    case ISD::ATOMIC_LOAD_NAND:
8595    case ISD::ATOMIC_LOAD_MIN:
8596    case ISD::ATOMIC_LOAD_MAX:
8597    case ISD::ATOMIC_LOAD_UMIN:
8598    case ISD::ATOMIC_LOAD_UMAX:
8599      break;
8600    default:
8601      return SDValue();
8602  }
8603
8604  SDValue fence = atomic.getOperand(0);
8605  if (fence.getOpcode() != ISD::MEMBARRIER)
8606    return SDValue();
8607
8608  switch (atomic.getOpcode()) {
8609    case ISD::ATOMIC_CMP_SWAP:
8610      return DAG.UpdateNodeOperands(atomic, fence.getOperand(0),
8611                                    atomic.getOperand(1), atomic.getOperand(2),
8612                                    atomic.getOperand(3));
8613    case ISD::ATOMIC_SWAP:
8614    case ISD::ATOMIC_LOAD_ADD:
8615    case ISD::ATOMIC_LOAD_SUB:
8616    case ISD::ATOMIC_LOAD_AND:
8617    case ISD::ATOMIC_LOAD_OR:
8618    case ISD::ATOMIC_LOAD_XOR:
8619    case ISD::ATOMIC_LOAD_NAND:
8620    case ISD::ATOMIC_LOAD_MIN:
8621    case ISD::ATOMIC_LOAD_MAX:
8622    case ISD::ATOMIC_LOAD_UMIN:
8623    case ISD::ATOMIC_LOAD_UMAX:
8624      return DAG.UpdateNodeOperands(atomic, fence.getOperand(0),
8625                                    atomic.getOperand(1), atomic.getOperand(2));
8626    default:
8627      return SDValue();
8628  }
8629}
8630
8631SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
8632                                             DAGCombinerInfo &DCI) const {
8633  SelectionDAG &DAG = DCI.DAG;
8634  switch (N->getOpcode()) {
8635  default: break;
8636  case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, *this);
8637  case ISD::SELECT:         return PerformSELECTCombine(N, DAG, Subtarget);
8638  case X86ISD::CMOV:        return PerformCMOVCombine(N, DAG, DCI);
8639  case ISD::MUL:            return PerformMulCombine(N, DAG, DCI);
8640  case ISD::SHL:
8641  case ISD::SRA:
8642  case ISD::SRL:            return PerformShiftCombine(N, DAG, Subtarget);
8643  case ISD::STORE:          return PerformSTORECombine(N, DAG, Subtarget);
8644  case X86ISD::FXOR:
8645  case X86ISD::FOR:         return PerformFORCombine(N, DAG);
8646  case X86ISD::FAND:        return PerformFANDCombine(N, DAG);
8647  case X86ISD::BT:          return PerformBTCombine(N, DAG, DCI);
8648  case X86ISD::VZEXT_MOVL:  return PerformVZEXT_MOVLCombine(N, DAG);
8649  case ISD::MEMBARRIER:     return PerformMEMBARRIERCombine(N, DAG);
8650  }
8651
8652  return SDValue();
8653}
8654
8655//===----------------------------------------------------------------------===//
8656//                           X86 Inline Assembly Support
8657//===----------------------------------------------------------------------===//
8658
8659/// getConstraintType - Given a constraint letter, return the type of
8660/// constraint it is for this target.
8661X86TargetLowering::ConstraintType
8662X86TargetLowering::getConstraintType(const std::string &Constraint) const {
8663  if (Constraint.size() == 1) {
8664    switch (Constraint[0]) {
8665    case 'A':
8666      return C_Register;
8667    case 'f':
8668    case 'r':
8669    case 'R':
8670    case 'l':
8671    case 'q':
8672    case 'Q':
8673    case 'x':
8674    case 'y':
8675    case 'Y':
8676      return C_RegisterClass;
8677    case 'e':
8678    case 'Z':
8679      return C_Other;
8680    default:
8681      break;
8682    }
8683  }
8684  return TargetLowering::getConstraintType(Constraint);
8685}
8686
8687/// LowerXConstraint - try to replace an X constraint, which matches anything,
8688/// with another that has more specific requirements based on the type of the
8689/// corresponding operand.
8690const char *X86TargetLowering::
8691LowerXConstraint(MVT ConstraintVT) const {
8692  // FP X constraints get lowered to SSE1/2 registers if available, otherwise
8693  // 'f' like normal targets.
8694  if (ConstraintVT.isFloatingPoint()) {
8695    if (Subtarget->hasSSE2())
8696      return "Y";
8697    if (Subtarget->hasSSE1())
8698      return "x";
8699  }
8700
8701  return TargetLowering::LowerXConstraint(ConstraintVT);
8702}
8703
8704/// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
8705/// vector.  If it is invalid, don't add anything to Ops.
8706void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
8707                                                     char Constraint,
8708                                                     bool hasMemory,
8709                                                     std::vector<SDValue>&Ops,
8710                                                     SelectionDAG &DAG) const {
8711  SDValue Result(0, 0);
8712
8713  switch (Constraint) {
8714  default: break;
8715  case 'I':
8716    if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
8717      if (C->getZExtValue() <= 31) {
8718        Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
8719        break;
8720      }
8721    }
8722    return;
8723  case 'J':
8724    if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
8725      if (C->getZExtValue() <= 63) {
8726        Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
8727        break;
8728      }
8729    }
8730    return;
8731  case 'K':
8732    if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
8733      if ((int8_t)C->getSExtValue() == C->getSExtValue()) {
8734        Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
8735        break;
8736      }
8737    }
8738    return;
8739  case 'N':
8740    if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
8741      if (C->getZExtValue() <= 255) {
8742        Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
8743        break;
8744      }
8745    }
8746    return;
8747  case 'e': {
8748    // 32-bit signed value
8749    if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
8750      const ConstantInt *CI = C->getConstantIntValue();
8751      if (CI->isValueValidForType(Type::Int32Ty, C->getSExtValue())) {
8752        // Widen to 64 bits here to get it sign extended.
8753        Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
8754        break;
8755      }
8756    // FIXME gcc accepts some relocatable values here too, but only in certain
8757    // memory models; it's complicated.
8758    }
8759    return;
8760  }
8761  case 'Z': {
8762    // 32-bit unsigned value
8763    if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
8764      const ConstantInt *CI = C->getConstantIntValue();
8765      if (CI->isValueValidForType(Type::Int32Ty, C->getZExtValue())) {
8766        Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
8767        break;
8768      }
8769    }
8770    // FIXME gcc accepts some relocatable values here too, but only in certain
8771    // memory models; it's complicated.
8772    return;
8773  }
8774  case 'i': {
8775    // Literal immediates are always ok.
8776    if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
8777      // Widen to 64 bits here to get it sign extended.
8778      Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
8779      break;
8780    }
8781
8782    // If we are in non-pic codegen mode, we allow the address of a global (with
8783    // an optional displacement) to be used with 'i'.
8784    GlobalAddressSDNode *GA = 0;
8785    int64_t Offset = 0;
8786
8787    // Match either (GA), (GA+C), (GA+C1+C2), etc.
8788    while (1) {
8789      if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
8790        Offset += GA->getOffset();
8791        break;
8792      } else if (Op.getOpcode() == ISD::ADD) {
8793        if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
8794          Offset += C->getZExtValue();
8795          Op = Op.getOperand(0);
8796          continue;
8797        }
8798      } else if (Op.getOpcode() == ISD::SUB) {
8799        if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
8800          Offset += -C->getZExtValue();
8801          Op = Op.getOperand(0);
8802          continue;
8803        }
8804      }
8805
8806      // Otherwise, this isn't something we can handle, reject it.
8807      return;
8808    }
8809    // If we require an extra load to get this address, as in PIC mode, we
8810    // can't accept it.
8811    if (Subtarget->GVRequiresExtraLoad(GA->getGlobal(),
8812                                       getTargetMachine(), false))
8813      return;
8814
8815    if (hasMemory)
8816      Op = LowerGlobalAddress(GA->getGlobal(), Op.getDebugLoc(), Offset, DAG);
8817    else
8818      Op = DAG.getTargetGlobalAddress(GA->getGlobal(), GA->getValueType(0),
8819                                      Offset);
8820    Result = Op;
8821    break;
8822  }
8823  }
8824
8825  if (Result.getNode()) {
8826    Ops.push_back(Result);
8827    return;
8828  }
8829  return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, hasMemory,
8830                                                      Ops, DAG);
8831}
8832
8833std::vector<unsigned> X86TargetLowering::
8834getRegClassForInlineAsmConstraint(const std::string &Constraint,
8835                                  MVT VT) const {
8836  if (Constraint.size() == 1) {
8837    // FIXME: not handling fp-stack yet!
8838    switch (Constraint[0]) {      // GCC X86 Constraint Letters
8839    default: break;  // Unknown constraint letter
8840    case 'q':   // Q_REGS (GENERAL_REGS in 64-bit mode)
8841    case 'Q':   // Q_REGS
8842      if (VT == MVT::i32)
8843        return make_vector<unsigned>(X86::EAX, X86::EDX, X86::ECX, X86::EBX, 0);
8844      else if (VT == MVT::i16)
8845        return make_vector<unsigned>(X86::AX, X86::DX, X86::CX, X86::BX, 0);
8846      else if (VT == MVT::i8)
8847        return make_vector<unsigned>(X86::AL, X86::DL, X86::CL, X86::BL, 0);
8848      else if (VT == MVT::i64)
8849        return make_vector<unsigned>(X86::RAX, X86::RDX, X86::RCX, X86::RBX, 0);
8850      break;
8851    }
8852  }
8853
8854  return std::vector<unsigned>();
8855}
8856
8857std::pair<unsigned, const TargetRegisterClass*>
8858X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
8859                                                MVT VT) const {
8860  // First, see if this is a constraint that directly corresponds to an LLVM
8861  // register class.
8862  if (Constraint.size() == 1) {
8863    // GCC Constraint Letters
8864    switch (Constraint[0]) {
8865    default: break;
8866    case 'r':   // GENERAL_REGS
8867    case 'R':   // LEGACY_REGS
8868    case 'l':   // INDEX_REGS
8869      if (VT == MVT::i8)
8870        return std::make_pair(0U, X86::GR8RegisterClass);
8871      if (VT == MVT::i16)
8872        return std::make_pair(0U, X86::GR16RegisterClass);
8873      if (VT == MVT::i32 || !Subtarget->is64Bit())
8874        return std::make_pair(0U, X86::GR32RegisterClass);
8875      return std::make_pair(0U, X86::GR64RegisterClass);
8876    case 'f':  // FP Stack registers.
8877      // If SSE is enabled for this VT, use f80 to ensure the isel moves the
8878      // value to the correct fpstack register class.
8879      if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
8880        return std::make_pair(0U, X86::RFP32RegisterClass);
8881      if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
8882        return std::make_pair(0U, X86::RFP64RegisterClass);
8883      return std::make_pair(0U, X86::RFP80RegisterClass);
8884    case 'y':   // MMX_REGS if MMX allowed.
8885      if (!Subtarget->hasMMX()) break;
8886      return std::make_pair(0U, X86::VR64RegisterClass);
8887    case 'Y':   // SSE_REGS if SSE2 allowed
8888      if (!Subtarget->hasSSE2()) break;
8889      // FALL THROUGH.
8890    case 'x':   // SSE_REGS if SSE1 allowed
8891      if (!Subtarget->hasSSE1()) break;
8892
8893      switch (VT.getSimpleVT()) {
8894      default: break;
8895      // Scalar SSE types.
8896      case MVT::f32:
8897      case MVT::i32:
8898        return std::make_pair(0U, X86::FR32RegisterClass);
8899      case MVT::f64:
8900      case MVT::i64:
8901        return std::make_pair(0U, X86::FR64RegisterClass);
8902      // Vector types.
8903      case MVT::v16i8:
8904      case MVT::v8i16:
8905      case MVT::v4i32:
8906      case MVT::v2i64:
8907      case MVT::v4f32:
8908      case MVT::v2f64:
8909        return std::make_pair(0U, X86::VR128RegisterClass);
8910      }
8911      break;
8912    }
8913  }
8914
8915  // Use the default implementation in TargetLowering to convert the register
8916  // constraint into a member of a register class.
8917  std::pair<unsigned, const TargetRegisterClass*> Res;
8918  Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
8919
8920  // Not found as a standard register?
8921  if (Res.second == 0) {
8922    // GCC calls "st(0)" just plain "st".
8923    if (StringsEqualNoCase("{st}", Constraint)) {
8924      Res.first = X86::ST0;
8925      Res.second = X86::RFP80RegisterClass;
8926    }
8927    // 'A' means EAX + EDX.
8928    if (Constraint == "A") {
8929      Res.first = X86::EAX;
8930      Res.second = X86::GRADRegisterClass;
8931    }
8932    return Res;
8933  }
8934
8935  // Otherwise, check to see if this is a register class of the wrong value
8936  // type.  For example, we want to map "{ax},i32" -> {eax}, we don't want it to
8937  // turn into {ax},{dx}.
8938  if (Res.second->hasType(VT))
8939    return Res;   // Correct type already, nothing to do.
8940
8941  // All of the single-register GCC register classes map their values onto
8942  // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp".  If we
8943  // really want an 8-bit or 32-bit register, map to the appropriate register
8944  // class and return the appropriate register.
8945  if (Res.second == X86::GR16RegisterClass) {
8946    if (VT == MVT::i8) {
8947      unsigned DestReg = 0;
8948      switch (Res.first) {
8949      default: break;
8950      case X86::AX: DestReg = X86::AL; break;
8951      case X86::DX: DestReg = X86::DL; break;
8952      case X86::CX: DestReg = X86::CL; break;
8953      case X86::BX: DestReg = X86::BL; break;
8954      }
8955      if (DestReg) {
8956        Res.first = DestReg;
8957        Res.second = X86::GR8RegisterClass;
8958      }
8959    } else if (VT == MVT::i32) {
8960      unsigned DestReg = 0;
8961      switch (Res.first) {
8962      default: break;
8963      case X86::AX: DestReg = X86::EAX; break;
8964      case X86::DX: DestReg = X86::EDX; break;
8965      case X86::CX: DestReg = X86::ECX; break;
8966      case X86::BX: DestReg = X86::EBX; break;
8967      case X86::SI: DestReg = X86::ESI; break;
8968      case X86::DI: DestReg = X86::EDI; break;
8969      case X86::BP: DestReg = X86::EBP; break;
8970      case X86::SP: DestReg = X86::ESP; break;
8971      }
8972      if (DestReg) {
8973        Res.first = DestReg;
8974        Res.second = X86::GR32RegisterClass;
8975      }
8976    } else if (VT == MVT::i64) {
8977      unsigned DestReg = 0;
8978      switch (Res.first) {
8979      default: break;
8980      case X86::AX: DestReg = X86::RAX; break;
8981      case X86::DX: DestReg = X86::RDX; break;
8982      case X86::CX: DestReg = X86::RCX; break;
8983      case X86::BX: DestReg = X86::RBX; break;
8984      case X86::SI: DestReg = X86::RSI; break;
8985      case X86::DI: DestReg = X86::RDI; break;
8986      case X86::BP: DestReg = X86::RBP; break;
8987      case X86::SP: DestReg = X86::RSP; break;
8988      }
8989      if (DestReg) {
8990        Res.first = DestReg;
8991        Res.second = X86::GR64RegisterClass;
8992      }
8993    }
8994  } else if (Res.second == X86::FR32RegisterClass ||
8995             Res.second == X86::FR64RegisterClass ||
8996             Res.second == X86::VR128RegisterClass) {
8997    // Handle references to XMM physical registers that got mapped into the
8998    // wrong class.  This can happen with constraints like {xmm0} where the
8999    // target independent register mapper will just pick the first match it can
9000    // find, ignoring the required type.
9001    if (VT == MVT::f32)
9002      Res.second = X86::FR32RegisterClass;
9003    else if (VT == MVT::f64)
9004      Res.second = X86::FR64RegisterClass;
9005    else if (X86::VR128RegisterClass->hasType(VT))
9006      Res.second = X86::VR128RegisterClass;
9007  }
9008
9009  return Res;
9010}
9011
9012//===----------------------------------------------------------------------===//
9013//                           X86 Widen vector type
9014//===----------------------------------------------------------------------===//
9015
9016/// getWidenVectorType: given a vector type, returns the type to widen
9017/// to (e.g., v7i8 to v8i8). If the vector type is legal, it returns itself.
9018/// If there is no vector type that we want to widen to, returns MVT::Other
9019/// When and where to widen is target dependent based on the cost of
9020/// scalarizing vs using the wider vector type.
9021
9022MVT X86TargetLowering::getWidenVectorType(MVT VT) const {
9023  assert(VT.isVector());
9024  if (isTypeLegal(VT))
9025    return VT;
9026
9027  // TODO: In computeRegisterProperty, we can compute the list of legal vector
9028  //       type based on element type.  This would speed up our search (though
9029  //       it may not be worth it since the size of the list is relatively
9030  //       small).
9031  MVT EltVT = VT.getVectorElementType();
9032  unsigned NElts = VT.getVectorNumElements();
9033
9034  // On X86, it make sense to widen any vector wider than 1
9035  if (NElts <= 1)
9036    return MVT::Other;
9037
9038  for (unsigned nVT = MVT::FIRST_VECTOR_VALUETYPE;
9039       nVT <= MVT::LAST_VECTOR_VALUETYPE; ++nVT) {
9040    MVT SVT = (MVT::SimpleValueType)nVT;
9041
9042    if (isTypeLegal(SVT) &&
9043        SVT.getVectorElementType() == EltVT &&
9044        SVT.getVectorNumElements() > NElts)
9045      return SVT;
9046  }
9047  return MVT::Other;
9048}
9049