X86ISelLowering.cpp revision c0573b13a119e1e504225542bddd85db7d4bd29f
1//===-- X86ISelLowering.cpp - X86 DAG Lowering Implementation -------------===//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file defines the interfaces that X86 uses to lower LLVM code into a
11// selection DAG.
12//
13//===----------------------------------------------------------------------===//
14
15#include "X86.h"
16#include "X86InstrBuilder.h"
17#include "X86ISelLowering.h"
18#include "X86MachineFunctionInfo.h"
19#include "X86TargetMachine.h"
20#include "llvm/CallingConv.h"
21#include "llvm/Constants.h"
22#include "llvm/DerivedTypes.h"
23#include "llvm/GlobalVariable.h"
24#include "llvm/Function.h"
25#include "llvm/Intrinsics.h"
26#include "llvm/ADT/BitVector.h"
27#include "llvm/ADT/VectorExtras.h"
28#include "llvm/CodeGen/CallingConvLower.h"
29#include "llvm/CodeGen/MachineFrameInfo.h"
30#include "llvm/CodeGen/MachineFunction.h"
31#include "llvm/CodeGen/MachineInstrBuilder.h"
32#include "llvm/CodeGen/MachineModuleInfo.h"
33#include "llvm/CodeGen/MachineRegisterInfo.h"
34#include "llvm/CodeGen/PseudoSourceValue.h"
35#include "llvm/CodeGen/SelectionDAG.h"
36#include "llvm/Support/MathExtras.h"
37#include "llvm/Support/Debug.h"
38#include "llvm/Target/TargetOptions.h"
39#include "llvm/ADT/SmallSet.h"
40#include "llvm/ADT/StringExtras.h"
41using namespace llvm;
42
43// Forward declarations.
44static SDValue getMOVLMask(unsigned NumElems, SelectionDAG &DAG);
45
46X86TargetLowering::X86TargetLowering(X86TargetMachine &TM)
47  : TargetLowering(TM) {
48  Subtarget = &TM.getSubtarget<X86Subtarget>();
49  X86ScalarSSEf64 = Subtarget->hasSSE2();
50  X86ScalarSSEf32 = Subtarget->hasSSE1();
51  X86StackPtr = Subtarget->is64Bit() ? X86::RSP : X86::ESP;
52
53  bool Fast = false;
54
55  RegInfo = TM.getRegisterInfo();
56
57  // Set up the TargetLowering object.
58
59  // X86 is weird, it always uses i8 for shift amounts and setcc results.
60  setShiftAmountType(MVT::i8);
61  setSetCCResultContents(ZeroOrOneSetCCResult);
62  setSchedulingPreference(SchedulingForRegPressure);
63  setShiftAmountFlavor(Mask);   // shl X, 32 == shl X, 0
64  setStackPointerRegisterToSaveRestore(X86StackPtr);
65
66  if (Subtarget->isTargetDarwin()) {
67    // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
68    setUseUnderscoreSetJmp(false);
69    setUseUnderscoreLongJmp(false);
70  } else if (Subtarget->isTargetMingw()) {
71    // MS runtime is weird: it exports _setjmp, but longjmp!
72    setUseUnderscoreSetJmp(true);
73    setUseUnderscoreLongJmp(false);
74  } else {
75    setUseUnderscoreSetJmp(true);
76    setUseUnderscoreLongJmp(true);
77  }
78
79  // Set up the register classes.
80  addRegisterClass(MVT::i8, X86::GR8RegisterClass);
81  addRegisterClass(MVT::i16, X86::GR16RegisterClass);
82  addRegisterClass(MVT::i32, X86::GR32RegisterClass);
83  if (Subtarget->is64Bit())
84    addRegisterClass(MVT::i64, X86::GR64RegisterClass);
85
86  setLoadXAction(ISD::SEXTLOAD, MVT::i1, Promote);
87
88  // We don't accept any truncstore of integer registers.
89  setTruncStoreAction(MVT::i64, MVT::i32, Expand);
90  setTruncStoreAction(MVT::i64, MVT::i16, Expand);
91  setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
92  setTruncStoreAction(MVT::i32, MVT::i16, Expand);
93  setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
94  setTruncStoreAction(MVT::i16, MVT::i8, Expand);
95
96  // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
97  // operation.
98  setOperationAction(ISD::UINT_TO_FP       , MVT::i1   , Promote);
99  setOperationAction(ISD::UINT_TO_FP       , MVT::i8   , Promote);
100  setOperationAction(ISD::UINT_TO_FP       , MVT::i16  , Promote);
101
102  if (Subtarget->is64Bit()) {
103    setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Expand);
104    setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Promote);
105  } else {
106    if (X86ScalarSSEf64)
107      // If SSE i64 SINT_TO_FP is not available, expand i32 UINT_TO_FP.
108      setOperationAction(ISD::UINT_TO_FP   , MVT::i32  , Expand);
109    else
110      setOperationAction(ISD::UINT_TO_FP   , MVT::i32  , Promote);
111  }
112
113  // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
114  // this operation.
115  setOperationAction(ISD::SINT_TO_FP       , MVT::i1   , Promote);
116  setOperationAction(ISD::SINT_TO_FP       , MVT::i8   , Promote);
117  // SSE has no i16 to fp conversion, only i32
118  if (X86ScalarSSEf32) {
119    setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
120    // f32 and f64 cases are Legal, f80 case is not
121    setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
122  } else {
123    setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Custom);
124    setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
125  }
126
127  // In 32-bit mode these are custom lowered.  In 64-bit mode F32 and F64
128  // are Legal, f80 is custom lowered.
129  setOperationAction(ISD::FP_TO_SINT     , MVT::i64  , Custom);
130  setOperationAction(ISD::SINT_TO_FP     , MVT::i64  , Custom);
131
132  // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
133  // this operation.
134  setOperationAction(ISD::FP_TO_SINT       , MVT::i1   , Promote);
135  setOperationAction(ISD::FP_TO_SINT       , MVT::i8   , Promote);
136
137  if (X86ScalarSSEf32) {
138    setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Promote);
139    // f32 and f64 cases are Legal, f80 case is not
140    setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
141  } else {
142    setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Custom);
143    setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
144  }
145
146  // Handle FP_TO_UINT by promoting the destination to a larger signed
147  // conversion.
148  setOperationAction(ISD::FP_TO_UINT       , MVT::i1   , Promote);
149  setOperationAction(ISD::FP_TO_UINT       , MVT::i8   , Promote);
150  setOperationAction(ISD::FP_TO_UINT       , MVT::i16  , Promote);
151
152  if (Subtarget->is64Bit()) {
153    setOperationAction(ISD::FP_TO_UINT     , MVT::i64  , Expand);
154    setOperationAction(ISD::FP_TO_UINT     , MVT::i32  , Promote);
155  } else {
156    if (X86ScalarSSEf32 && !Subtarget->hasSSE3())
157      // Expand FP_TO_UINT into a select.
158      // FIXME: We would like to use a Custom expander here eventually to do
159      // the optimal thing for SSE vs. the default expansion in the legalizer.
160      setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Expand);
161    else
162      // With SSE3 we can use fisttpll to convert to a signed i64.
163      setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Promote);
164  }
165
166  // TODO: when we have SSE, these could be more efficient, by using movd/movq.
167  if (!X86ScalarSSEf64) {
168    setOperationAction(ISD::BIT_CONVERT      , MVT::f32  , Expand);
169    setOperationAction(ISD::BIT_CONVERT      , MVT::i32  , Expand);
170  }
171
172  // Scalar integer divide and remainder are lowered to use operations that
173  // produce two results, to match the available instructions. This exposes
174  // the two-result form to trivial CSE, which is able to combine x/y and x%y
175  // into a single instruction.
176  //
177  // Scalar integer multiply-high is also lowered to use two-result
178  // operations, to match the available instructions. However, plain multiply
179  // (low) operations are left as Legal, as there are single-result
180  // instructions for this in x86. Using the two-result multiply instructions
181  // when both high and low results are needed must be arranged by dagcombine.
182  setOperationAction(ISD::MULHS           , MVT::i8    , Expand);
183  setOperationAction(ISD::MULHU           , MVT::i8    , Expand);
184  setOperationAction(ISD::SDIV            , MVT::i8    , Expand);
185  setOperationAction(ISD::UDIV            , MVT::i8    , Expand);
186  setOperationAction(ISD::SREM            , MVT::i8    , Expand);
187  setOperationAction(ISD::UREM            , MVT::i8    , Expand);
188  setOperationAction(ISD::MULHS           , MVT::i16   , Expand);
189  setOperationAction(ISD::MULHU           , MVT::i16   , Expand);
190  setOperationAction(ISD::SDIV            , MVT::i16   , Expand);
191  setOperationAction(ISD::UDIV            , MVT::i16   , Expand);
192  setOperationAction(ISD::SREM            , MVT::i16   , Expand);
193  setOperationAction(ISD::UREM            , MVT::i16   , Expand);
194  setOperationAction(ISD::MULHS           , MVT::i32   , Expand);
195  setOperationAction(ISD::MULHU           , MVT::i32   , Expand);
196  setOperationAction(ISD::SDIV            , MVT::i32   , Expand);
197  setOperationAction(ISD::UDIV            , MVT::i32   , Expand);
198  setOperationAction(ISD::SREM            , MVT::i32   , Expand);
199  setOperationAction(ISD::UREM            , MVT::i32   , Expand);
200  setOperationAction(ISD::MULHS           , MVT::i64   , Expand);
201  setOperationAction(ISD::MULHU           , MVT::i64   , Expand);
202  setOperationAction(ISD::SDIV            , MVT::i64   , Expand);
203  setOperationAction(ISD::UDIV            , MVT::i64   , Expand);
204  setOperationAction(ISD::SREM            , MVT::i64   , Expand);
205  setOperationAction(ISD::UREM            , MVT::i64   , Expand);
206
207  setOperationAction(ISD::BR_JT            , MVT::Other, Expand);
208  setOperationAction(ISD::BRCOND           , MVT::Other, Custom);
209  setOperationAction(ISD::BR_CC            , MVT::Other, Expand);
210  setOperationAction(ISD::SELECT_CC        , MVT::Other, Expand);
211  if (Subtarget->is64Bit())
212    setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
213  setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16  , Legal);
214  setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8   , Legal);
215  setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1   , Expand);
216  setOperationAction(ISD::FP_ROUND_INREG   , MVT::f32  , Expand);
217  setOperationAction(ISD::FREM             , MVT::f32  , Expand);
218  setOperationAction(ISD::FREM             , MVT::f64  , Expand);
219  setOperationAction(ISD::FREM             , MVT::f80  , Expand);
220  setOperationAction(ISD::FLT_ROUNDS_      , MVT::i32  , Custom);
221
222  setOperationAction(ISD::CTPOP            , MVT::i8   , Expand);
223  setOperationAction(ISD::CTTZ             , MVT::i8   , Custom);
224  setOperationAction(ISD::CTLZ             , MVT::i8   , Custom);
225  setOperationAction(ISD::CTPOP            , MVT::i16  , Expand);
226  setOperationAction(ISD::CTTZ             , MVT::i16  , Custom);
227  setOperationAction(ISD::CTLZ             , MVT::i16  , Custom);
228  setOperationAction(ISD::CTPOP            , MVT::i32  , Expand);
229  setOperationAction(ISD::CTTZ             , MVT::i32  , Custom);
230  setOperationAction(ISD::CTLZ             , MVT::i32  , Custom);
231  if (Subtarget->is64Bit()) {
232    setOperationAction(ISD::CTPOP          , MVT::i64  , Expand);
233    setOperationAction(ISD::CTTZ           , MVT::i64  , Custom);
234    setOperationAction(ISD::CTLZ           , MVT::i64  , Custom);
235  }
236
237  setOperationAction(ISD::READCYCLECOUNTER , MVT::i64  , Custom);
238  setOperationAction(ISD::BSWAP            , MVT::i16  , Expand);
239
240  // These should be promoted to a larger select which is supported.
241  setOperationAction(ISD::SELECT           , MVT::i1   , Promote);
242  setOperationAction(ISD::SELECT           , MVT::i8   , Promote);
243  // X86 wants to expand cmov itself.
244  setOperationAction(ISD::SELECT          , MVT::i16  , Custom);
245  setOperationAction(ISD::SELECT          , MVT::i32  , Custom);
246  setOperationAction(ISD::SELECT          , MVT::f32  , Custom);
247  setOperationAction(ISD::SELECT          , MVT::f64  , Custom);
248  setOperationAction(ISD::SELECT          , MVT::f80  , Custom);
249  setOperationAction(ISD::SETCC           , MVT::i8   , Custom);
250  setOperationAction(ISD::SETCC           , MVT::i16  , Custom);
251  setOperationAction(ISD::SETCC           , MVT::i32  , Custom);
252  setOperationAction(ISD::SETCC           , MVT::f32  , Custom);
253  setOperationAction(ISD::SETCC           , MVT::f64  , Custom);
254  setOperationAction(ISD::SETCC           , MVT::f80  , Custom);
255  if (Subtarget->is64Bit()) {
256    setOperationAction(ISD::SELECT        , MVT::i64  , Custom);
257    setOperationAction(ISD::SETCC         , MVT::i64  , Custom);
258  }
259  // X86 ret instruction may pop stack.
260  setOperationAction(ISD::RET             , MVT::Other, Custom);
261  if (!Subtarget->is64Bit())
262    setOperationAction(ISD::EH_RETURN       , MVT::Other, Custom);
263
264  // Darwin ABI issue.
265  setOperationAction(ISD::ConstantPool    , MVT::i32  , Custom);
266  setOperationAction(ISD::JumpTable       , MVT::i32  , Custom);
267  setOperationAction(ISD::GlobalAddress   , MVT::i32  , Custom);
268  setOperationAction(ISD::GlobalTLSAddress, MVT::i32  , Custom);
269  if (Subtarget->is64Bit())
270    setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
271  setOperationAction(ISD::ExternalSymbol  , MVT::i32  , Custom);
272  if (Subtarget->is64Bit()) {
273    setOperationAction(ISD::ConstantPool  , MVT::i64  , Custom);
274    setOperationAction(ISD::JumpTable     , MVT::i64  , Custom);
275    setOperationAction(ISD::GlobalAddress , MVT::i64  , Custom);
276    setOperationAction(ISD::ExternalSymbol, MVT::i64  , Custom);
277  }
278  // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
279  setOperationAction(ISD::SHL_PARTS       , MVT::i32  , Custom);
280  setOperationAction(ISD::SRA_PARTS       , MVT::i32  , Custom);
281  setOperationAction(ISD::SRL_PARTS       , MVT::i32  , Custom);
282  if (Subtarget->is64Bit()) {
283    setOperationAction(ISD::SHL_PARTS     , MVT::i64  , Custom);
284    setOperationAction(ISD::SRA_PARTS     , MVT::i64  , Custom);
285    setOperationAction(ISD::SRL_PARTS     , MVT::i64  , Custom);
286  }
287
288  if (Subtarget->hasSSE1())
289    setOperationAction(ISD::PREFETCH      , MVT::Other, Legal);
290
291  if (!Subtarget->hasSSE2())
292    setOperationAction(ISD::MEMBARRIER    , MVT::Other, Expand);
293
294  // Expand certain atomics
295  setOperationAction(ISD::ATOMIC_CMP_SWAP , MVT::i8, Custom);
296  setOperationAction(ISD::ATOMIC_CMP_SWAP , MVT::i16, Custom);
297  setOperationAction(ISD::ATOMIC_CMP_SWAP , MVT::i32, Custom);
298  setOperationAction(ISD::ATOMIC_CMP_SWAP , MVT::i64, Custom);
299  setOperationAction(ISD::ATOMIC_LOAD_SUB , MVT::i8, Expand);
300  setOperationAction(ISD::ATOMIC_LOAD_SUB , MVT::i16, Expand);
301  setOperationAction(ISD::ATOMIC_LOAD_SUB , MVT::i32, Expand);
302
303  // Use the default ISD::DBG_STOPPOINT, ISD::DECLARE expansion.
304  setOperationAction(ISD::DBG_STOPPOINT, MVT::Other, Expand);
305  // FIXME - use subtarget debug flags
306  if (!Subtarget->isTargetDarwin() &&
307      !Subtarget->isTargetELF() &&
308      !Subtarget->isTargetCygMing()) {
309    setOperationAction(ISD::DBG_LABEL, MVT::Other, Expand);
310    setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
311  }
312
313  setOperationAction(ISD::EXCEPTIONADDR, MVT::i64, Expand);
314  setOperationAction(ISD::EHSELECTION,   MVT::i64, Expand);
315  setOperationAction(ISD::EXCEPTIONADDR, MVT::i32, Expand);
316  setOperationAction(ISD::EHSELECTION,   MVT::i32, Expand);
317  if (Subtarget->is64Bit()) {
318    // FIXME: Verify
319    setExceptionPointerRegister(X86::RAX);
320    setExceptionSelectorRegister(X86::RDX);
321  } else {
322    setExceptionPointerRegister(X86::EAX);
323    setExceptionSelectorRegister(X86::EDX);
324  }
325  setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
326
327  setOperationAction(ISD::TRAMPOLINE, MVT::Other, Custom);
328
329  setOperationAction(ISD::TRAP, MVT::Other, Legal);
330
331  // VASTART needs to be custom lowered to use the VarArgsFrameIndex
332  setOperationAction(ISD::VASTART           , MVT::Other, Custom);
333  setOperationAction(ISD::VAEND             , MVT::Other, Expand);
334  if (Subtarget->is64Bit()) {
335    setOperationAction(ISD::VAARG           , MVT::Other, Custom);
336    setOperationAction(ISD::VACOPY          , MVT::Other, Custom);
337  } else {
338    setOperationAction(ISD::VAARG           , MVT::Other, Expand);
339    setOperationAction(ISD::VACOPY          , MVT::Other, Expand);
340  }
341
342  setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
343  setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
344  if (Subtarget->is64Bit())
345    setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64, Expand);
346  if (Subtarget->isTargetCygMing())
347    setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Custom);
348  else
349    setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
350
351  if (X86ScalarSSEf64) {
352    // f32 and f64 use SSE.
353    // Set up the FP register classes.
354    addRegisterClass(MVT::f32, X86::FR32RegisterClass);
355    addRegisterClass(MVT::f64, X86::FR64RegisterClass);
356
357    // Use ANDPD to simulate FABS.
358    setOperationAction(ISD::FABS , MVT::f64, Custom);
359    setOperationAction(ISD::FABS , MVT::f32, Custom);
360
361    // Use XORP to simulate FNEG.
362    setOperationAction(ISD::FNEG , MVT::f64, Custom);
363    setOperationAction(ISD::FNEG , MVT::f32, Custom);
364
365    // Use ANDPD and ORPD to simulate FCOPYSIGN.
366    setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
367    setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
368
369    // We don't support sin/cos/fmod
370    setOperationAction(ISD::FSIN , MVT::f64, Expand);
371    setOperationAction(ISD::FCOS , MVT::f64, Expand);
372    setOperationAction(ISD::FSIN , MVT::f32, Expand);
373    setOperationAction(ISD::FCOS , MVT::f32, Expand);
374
375    // Expand FP immediates into loads from the stack, except for the special
376    // cases we handle.
377    addLegalFPImmediate(APFloat(+0.0)); // xorpd
378    addLegalFPImmediate(APFloat(+0.0f)); // xorps
379
380    // Floating truncations from f80 and extensions to f80 go through memory.
381    // If optimizing, we lie about this though and handle it in
382    // InstructionSelectPreprocess so that dagcombine2 can hack on these.
383    if (Fast) {
384      setConvertAction(MVT::f32, MVT::f80, Expand);
385      setConvertAction(MVT::f64, MVT::f80, Expand);
386      setConvertAction(MVT::f80, MVT::f32, Expand);
387      setConvertAction(MVT::f80, MVT::f64, Expand);
388    }
389  } else if (X86ScalarSSEf32) {
390    // Use SSE for f32, x87 for f64.
391    // Set up the FP register classes.
392    addRegisterClass(MVT::f32, X86::FR32RegisterClass);
393    addRegisterClass(MVT::f64, X86::RFP64RegisterClass);
394
395    // Use ANDPS to simulate FABS.
396    setOperationAction(ISD::FABS , MVT::f32, Custom);
397
398    // Use XORP to simulate FNEG.
399    setOperationAction(ISD::FNEG , MVT::f32, Custom);
400
401    setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
402
403    // Use ANDPS and ORPS to simulate FCOPYSIGN.
404    setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
405    setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
406
407    // We don't support sin/cos/fmod
408    setOperationAction(ISD::FSIN , MVT::f32, Expand);
409    setOperationAction(ISD::FCOS , MVT::f32, Expand);
410
411    // Special cases we handle for FP constants.
412    addLegalFPImmediate(APFloat(+0.0f)); // xorps
413    addLegalFPImmediate(APFloat(+0.0)); // FLD0
414    addLegalFPImmediate(APFloat(+1.0)); // FLD1
415    addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
416    addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
417
418    // SSE <-> X87 conversions go through memory.  If optimizing, we lie about
419    // this though and handle it in InstructionSelectPreprocess so that
420    // dagcombine2 can hack on these.
421    if (Fast) {
422      setConvertAction(MVT::f32, MVT::f64, Expand);
423      setConvertAction(MVT::f32, MVT::f80, Expand);
424      setConvertAction(MVT::f80, MVT::f32, Expand);
425      setConvertAction(MVT::f64, MVT::f32, Expand);
426      // And x87->x87 truncations also.
427      setConvertAction(MVT::f80, MVT::f64, Expand);
428    }
429
430    if (!UnsafeFPMath) {
431      setOperationAction(ISD::FSIN           , MVT::f64  , Expand);
432      setOperationAction(ISD::FCOS           , MVT::f64  , Expand);
433    }
434  } else {
435    // f32 and f64 in x87.
436    // Set up the FP register classes.
437    addRegisterClass(MVT::f64, X86::RFP64RegisterClass);
438    addRegisterClass(MVT::f32, X86::RFP32RegisterClass);
439
440    setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
441    setOperationAction(ISD::UNDEF,     MVT::f32, Expand);
442    setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
443    setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
444
445    // Floating truncations go through memory.  If optimizing, we lie about
446    // this though and handle it in InstructionSelectPreprocess so that
447    // dagcombine2 can hack on these.
448    if (Fast) {
449      setConvertAction(MVT::f80, MVT::f32, Expand);
450      setConvertAction(MVT::f64, MVT::f32, Expand);
451      setConvertAction(MVT::f80, MVT::f64, Expand);
452    }
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  addRegisterClass(MVT::f80, X86::RFP80RegisterClass);
470  setOperationAction(ISD::UNDEF,     MVT::f80, Expand);
471  setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
472  {
473    APFloat TmpFlt(+0.0);
474    TmpFlt.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven);
475    addLegalFPImmediate(TmpFlt);  // FLD0
476    TmpFlt.changeSign();
477    addLegalFPImmediate(TmpFlt);  // FLD0/FCHS
478    APFloat TmpFlt2(+1.0);
479    TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven);
480    addLegalFPImmediate(TmpFlt2);  // FLD1
481    TmpFlt2.changeSign();
482    addLegalFPImmediate(TmpFlt2);  // FLD1/FCHS
483  }
484
485  if (!UnsafeFPMath) {
486    setOperationAction(ISD::FSIN           , MVT::f80  , Expand);
487    setOperationAction(ISD::FCOS           , MVT::f80  , Expand);
488  }
489
490  // Always use a library call for pow.
491  setOperationAction(ISD::FPOW             , MVT::f32  , Expand);
492  setOperationAction(ISD::FPOW             , MVT::f64  , Expand);
493  setOperationAction(ISD::FPOW             , MVT::f80  , Expand);
494
495  // First set operation action for all vector types to expand. Then we
496  // will selectively turn on ones that can be effectively codegen'd.
497  for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
498       VT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++VT) {
499    setOperationAction(ISD::ADD , (MVT::SimpleValueType)VT, Expand);
500    setOperationAction(ISD::SUB , (MVT::SimpleValueType)VT, Expand);
501    setOperationAction(ISD::FADD, (MVT::SimpleValueType)VT, Expand);
502    setOperationAction(ISD::FNEG, (MVT::SimpleValueType)VT, Expand);
503    setOperationAction(ISD::FSUB, (MVT::SimpleValueType)VT, Expand);
504    setOperationAction(ISD::MUL , (MVT::SimpleValueType)VT, Expand);
505    setOperationAction(ISD::FMUL, (MVT::SimpleValueType)VT, Expand);
506    setOperationAction(ISD::SDIV, (MVT::SimpleValueType)VT, Expand);
507    setOperationAction(ISD::UDIV, (MVT::SimpleValueType)VT, Expand);
508    setOperationAction(ISD::FDIV, (MVT::SimpleValueType)VT, Expand);
509    setOperationAction(ISD::SREM, (MVT::SimpleValueType)VT, Expand);
510    setOperationAction(ISD::UREM, (MVT::SimpleValueType)VT, Expand);
511    setOperationAction(ISD::LOAD, (MVT::SimpleValueType)VT, Expand);
512    setOperationAction(ISD::VECTOR_SHUFFLE,     (MVT::SimpleValueType)VT, Expand);
513    setOperationAction(ISD::EXTRACT_VECTOR_ELT, (MVT::SimpleValueType)VT, Expand);
514    setOperationAction(ISD::INSERT_VECTOR_ELT,  (MVT::SimpleValueType)VT, Expand);
515    setOperationAction(ISD::FABS, (MVT::SimpleValueType)VT, Expand);
516    setOperationAction(ISD::FSIN, (MVT::SimpleValueType)VT, Expand);
517    setOperationAction(ISD::FCOS, (MVT::SimpleValueType)VT, Expand);
518    setOperationAction(ISD::FREM, (MVT::SimpleValueType)VT, Expand);
519    setOperationAction(ISD::FPOWI, (MVT::SimpleValueType)VT, Expand);
520    setOperationAction(ISD::FSQRT, (MVT::SimpleValueType)VT, Expand);
521    setOperationAction(ISD::FCOPYSIGN, (MVT::SimpleValueType)VT, Expand);
522    setOperationAction(ISD::SMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
523    setOperationAction(ISD::UMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
524    setOperationAction(ISD::SDIVREM, (MVT::SimpleValueType)VT, Expand);
525    setOperationAction(ISD::UDIVREM, (MVT::SimpleValueType)VT, Expand);
526    setOperationAction(ISD::FPOW, (MVT::SimpleValueType)VT, Expand);
527    setOperationAction(ISD::CTPOP, (MVT::SimpleValueType)VT, Expand);
528    setOperationAction(ISD::CTTZ, (MVT::SimpleValueType)VT, Expand);
529    setOperationAction(ISD::CTLZ, (MVT::SimpleValueType)VT, Expand);
530    setOperationAction(ISD::SHL, (MVT::SimpleValueType)VT, Expand);
531    setOperationAction(ISD::SRA, (MVT::SimpleValueType)VT, Expand);
532    setOperationAction(ISD::SRL, (MVT::SimpleValueType)VT, Expand);
533    setOperationAction(ISD::ROTL, (MVT::SimpleValueType)VT, Expand);
534    setOperationAction(ISD::ROTR, (MVT::SimpleValueType)VT, Expand);
535    setOperationAction(ISD::BSWAP, (MVT::SimpleValueType)VT, Expand);
536    setOperationAction(ISD::VSETCC, (MVT::SimpleValueType)VT, Expand);
537  }
538
539  if (Subtarget->hasMMX()) {
540    addRegisterClass(MVT::v8i8,  X86::VR64RegisterClass);
541    addRegisterClass(MVT::v4i16, X86::VR64RegisterClass);
542    addRegisterClass(MVT::v2i32, X86::VR64RegisterClass);
543    addRegisterClass(MVT::v2f32, X86::VR64RegisterClass);
544    addRegisterClass(MVT::v1i64, X86::VR64RegisterClass);
545
546    // FIXME: add MMX packed arithmetics
547
548    setOperationAction(ISD::ADD,                MVT::v8i8,  Legal);
549    setOperationAction(ISD::ADD,                MVT::v4i16, Legal);
550    setOperationAction(ISD::ADD,                MVT::v2i32, Legal);
551    setOperationAction(ISD::ADD,                MVT::v1i64, Legal);
552
553    setOperationAction(ISD::SUB,                MVT::v8i8,  Legal);
554    setOperationAction(ISD::SUB,                MVT::v4i16, Legal);
555    setOperationAction(ISD::SUB,                MVT::v2i32, Legal);
556    setOperationAction(ISD::SUB,                MVT::v1i64, Legal);
557
558    setOperationAction(ISD::MULHS,              MVT::v4i16, Legal);
559    setOperationAction(ISD::MUL,                MVT::v4i16, Legal);
560
561    setOperationAction(ISD::AND,                MVT::v8i8,  Promote);
562    AddPromotedToType (ISD::AND,                MVT::v8i8,  MVT::v1i64);
563    setOperationAction(ISD::AND,                MVT::v4i16, Promote);
564    AddPromotedToType (ISD::AND,                MVT::v4i16, MVT::v1i64);
565    setOperationAction(ISD::AND,                MVT::v2i32, Promote);
566    AddPromotedToType (ISD::AND,                MVT::v2i32, MVT::v1i64);
567    setOperationAction(ISD::AND,                MVT::v1i64, Legal);
568
569    setOperationAction(ISD::OR,                 MVT::v8i8,  Promote);
570    AddPromotedToType (ISD::OR,                 MVT::v8i8,  MVT::v1i64);
571    setOperationAction(ISD::OR,                 MVT::v4i16, Promote);
572    AddPromotedToType (ISD::OR,                 MVT::v4i16, MVT::v1i64);
573    setOperationAction(ISD::OR,                 MVT::v2i32, Promote);
574    AddPromotedToType (ISD::OR,                 MVT::v2i32, MVT::v1i64);
575    setOperationAction(ISD::OR,                 MVT::v1i64, Legal);
576
577    setOperationAction(ISD::XOR,                MVT::v8i8,  Promote);
578    AddPromotedToType (ISD::XOR,                MVT::v8i8,  MVT::v1i64);
579    setOperationAction(ISD::XOR,                MVT::v4i16, Promote);
580    AddPromotedToType (ISD::XOR,                MVT::v4i16, MVT::v1i64);
581    setOperationAction(ISD::XOR,                MVT::v2i32, Promote);
582    AddPromotedToType (ISD::XOR,                MVT::v2i32, MVT::v1i64);
583    setOperationAction(ISD::XOR,                MVT::v1i64, Legal);
584
585    setOperationAction(ISD::LOAD,               MVT::v8i8,  Promote);
586    AddPromotedToType (ISD::LOAD,               MVT::v8i8,  MVT::v1i64);
587    setOperationAction(ISD::LOAD,               MVT::v4i16, Promote);
588    AddPromotedToType (ISD::LOAD,               MVT::v4i16, MVT::v1i64);
589    setOperationAction(ISD::LOAD,               MVT::v2i32, Promote);
590    AddPromotedToType (ISD::LOAD,               MVT::v2i32, MVT::v1i64);
591    setOperationAction(ISD::LOAD,               MVT::v2f32, Promote);
592    AddPromotedToType (ISD::LOAD,               MVT::v2f32, MVT::v1i64);
593    setOperationAction(ISD::LOAD,               MVT::v1i64, Legal);
594
595    setOperationAction(ISD::BUILD_VECTOR,       MVT::v8i8,  Custom);
596    setOperationAction(ISD::BUILD_VECTOR,       MVT::v4i16, Custom);
597    setOperationAction(ISD::BUILD_VECTOR,       MVT::v2i32, Custom);
598    setOperationAction(ISD::BUILD_VECTOR,       MVT::v2f32, Custom);
599    setOperationAction(ISD::BUILD_VECTOR,       MVT::v1i64, Custom);
600
601    setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v8i8,  Custom);
602    setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4i16, Custom);
603    setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2i32, Custom);
604    setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v1i64, Custom);
605
606    setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v2f32, Custom);
607    setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i8,  Custom);
608    setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v4i16, Custom);
609    setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v1i64, Custom);
610
611    setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i16, Custom);
612  }
613
614  if (Subtarget->hasSSE1()) {
615    addRegisterClass(MVT::v4f32, X86::VR128RegisterClass);
616
617    setOperationAction(ISD::FADD,               MVT::v4f32, Legal);
618    setOperationAction(ISD::FSUB,               MVT::v4f32, Legal);
619    setOperationAction(ISD::FMUL,               MVT::v4f32, Legal);
620    setOperationAction(ISD::FDIV,               MVT::v4f32, Legal);
621    setOperationAction(ISD::FSQRT,              MVT::v4f32, Legal);
622    setOperationAction(ISD::FNEG,               MVT::v4f32, Custom);
623    setOperationAction(ISD::LOAD,               MVT::v4f32, Legal);
624    setOperationAction(ISD::BUILD_VECTOR,       MVT::v4f32, Custom);
625    setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4f32, Custom);
626    setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
627    setOperationAction(ISD::SELECT,             MVT::v4f32, Custom);
628    setOperationAction(ISD::VSETCC,             MVT::v4f32, Custom);
629  }
630
631  if (Subtarget->hasSSE2()) {
632    addRegisterClass(MVT::v2f64, X86::VR128RegisterClass);
633    addRegisterClass(MVT::v16i8, X86::VR128RegisterClass);
634    addRegisterClass(MVT::v8i16, X86::VR128RegisterClass);
635    addRegisterClass(MVT::v4i32, X86::VR128RegisterClass);
636    addRegisterClass(MVT::v2i64, X86::VR128RegisterClass);
637
638    setOperationAction(ISD::ADD,                MVT::v16i8, Legal);
639    setOperationAction(ISD::ADD,                MVT::v8i16, Legal);
640    setOperationAction(ISD::ADD,                MVT::v4i32, Legal);
641    setOperationAction(ISD::ADD,                MVT::v2i64, Legal);
642    setOperationAction(ISD::SUB,                MVT::v16i8, Legal);
643    setOperationAction(ISD::SUB,                MVT::v8i16, Legal);
644    setOperationAction(ISD::SUB,                MVT::v4i32, Legal);
645    setOperationAction(ISD::SUB,                MVT::v2i64, Legal);
646    setOperationAction(ISD::MUL,                MVT::v8i16, Legal);
647    setOperationAction(ISD::FADD,               MVT::v2f64, Legal);
648    setOperationAction(ISD::FSUB,               MVT::v2f64, Legal);
649    setOperationAction(ISD::FMUL,               MVT::v2f64, Legal);
650    setOperationAction(ISD::FDIV,               MVT::v2f64, Legal);
651    setOperationAction(ISD::FSQRT,              MVT::v2f64, Legal);
652    setOperationAction(ISD::FNEG,               MVT::v2f64, Custom);
653
654    setOperationAction(ISD::VSETCC,             MVT::v2f64, Custom);
655    setOperationAction(ISD::VSETCC,             MVT::v16i8, Custom);
656    setOperationAction(ISD::VSETCC,             MVT::v8i16, Custom);
657    setOperationAction(ISD::VSETCC,             MVT::v4i32, Custom);
658
659    setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v16i8, Custom);
660    setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i16, Custom);
661    setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
662    setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
663    setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
664
665    // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
666    for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v2i64; ++i) {
667      MVT VT = (MVT::SimpleValueType)i;
668      // Do not attempt to custom lower non-power-of-2 vectors
669      if (!isPowerOf2_32(VT.getVectorNumElements()))
670        continue;
671      setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
672      setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
673      setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
674    }
675    setOperationAction(ISD::BUILD_VECTOR,       MVT::v2f64, Custom);
676    setOperationAction(ISD::BUILD_VECTOR,       MVT::v2i64, Custom);
677    setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2f64, Custom);
678    setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2i64, Custom);
679    setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2f64, Custom);
680    setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
681    if (Subtarget->is64Bit()) {
682      setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
683      setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
684    }
685
686    // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
687    for (unsigned VT = (unsigned)MVT::v16i8; VT != (unsigned)MVT::v2i64; VT++) {
688      setOperationAction(ISD::AND,    (MVT::SimpleValueType)VT, Promote);
689      AddPromotedToType (ISD::AND,    (MVT::SimpleValueType)VT, MVT::v2i64);
690      setOperationAction(ISD::OR,     (MVT::SimpleValueType)VT, Promote);
691      AddPromotedToType (ISD::OR,     (MVT::SimpleValueType)VT, MVT::v2i64);
692      setOperationAction(ISD::XOR,    (MVT::SimpleValueType)VT, Promote);
693      AddPromotedToType (ISD::XOR,    (MVT::SimpleValueType)VT, MVT::v2i64);
694      setOperationAction(ISD::LOAD,   (MVT::SimpleValueType)VT, Promote);
695      AddPromotedToType (ISD::LOAD,   (MVT::SimpleValueType)VT, MVT::v2i64);
696      setOperationAction(ISD::SELECT, (MVT::SimpleValueType)VT, Promote);
697      AddPromotedToType (ISD::SELECT, (MVT::SimpleValueType)VT, MVT::v2i64);
698    }
699
700    setTruncStoreAction(MVT::f64, MVT::f32, Expand);
701
702    // Custom lower v2i64 and v2f64 selects.
703    setOperationAction(ISD::LOAD,               MVT::v2f64, Legal);
704    setOperationAction(ISD::LOAD,               MVT::v2i64, Legal);
705    setOperationAction(ISD::SELECT,             MVT::v2f64, Custom);
706    setOperationAction(ISD::SELECT,             MVT::v2i64, Custom);
707
708  }
709
710  if (Subtarget->hasSSE41()) {
711    // FIXME: Do we need to handle scalar-to-vector here?
712    setOperationAction(ISD::MUL,                MVT::v4i32, Legal);
713    setOperationAction(ISD::MUL,                MVT::v2i64, Legal);
714
715    // i8 and i16 vectors are custom , because the source register and source
716    // source memory operand types are not the same width.  f32 vectors are
717    // custom since the immediate controlling the insert encodes additional
718    // information.
719    setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i8, Custom);
720    setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
721    setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Legal);
722    setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
723
724    setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
725    setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
726    setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Legal);
727    setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
728
729    if (Subtarget->is64Bit()) {
730      setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Legal);
731      setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Legal);
732    }
733  }
734
735  if (Subtarget->hasSSE42()) {
736    setOperationAction(ISD::VSETCC,             MVT::v2i64, Custom);
737  }
738
739  // We want to custom lower some of our intrinsics.
740  setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
741
742  // We have target-specific dag combine patterns for the following nodes:
743  setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
744  setTargetDAGCombine(ISD::BUILD_VECTOR);
745  setTargetDAGCombine(ISD::SELECT);
746  setTargetDAGCombine(ISD::STORE);
747
748  computeRegisterProperties();
749
750  // FIXME: These should be based on subtarget info. Plus, the values should
751  // be smaller when we are in optimizing for size mode.
752  maxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
753  maxStoresPerMemcpy = 16; // For @llvm.memcpy -> sequence of stores
754  maxStoresPerMemmove = 3; // For @llvm.memmove -> sequence of stores
755  allowUnalignedMemoryAccesses = true; // x86 supports it!
756  setPrefLoopAlignment(16);
757}
758
759
760MVT X86TargetLowering::getSetCCResultType(const SDValue &) const {
761  return MVT::i8;
762}
763
764
765/// getMaxByValAlign - Helper for getByValTypeAlignment to determine
766/// the desired ByVal argument alignment.
767static void getMaxByValAlign(const Type *Ty, unsigned &MaxAlign) {
768  if (MaxAlign == 16)
769    return;
770  if (const VectorType *VTy = dyn_cast<VectorType>(Ty)) {
771    if (VTy->getBitWidth() == 128)
772      MaxAlign = 16;
773  } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
774    unsigned EltAlign = 0;
775    getMaxByValAlign(ATy->getElementType(), EltAlign);
776    if (EltAlign > MaxAlign)
777      MaxAlign = EltAlign;
778  } else if (const StructType *STy = dyn_cast<StructType>(Ty)) {
779    for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
780      unsigned EltAlign = 0;
781      getMaxByValAlign(STy->getElementType(i), EltAlign);
782      if (EltAlign > MaxAlign)
783        MaxAlign = EltAlign;
784      if (MaxAlign == 16)
785        break;
786    }
787  }
788  return;
789}
790
791/// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
792/// function arguments in the caller parameter area. For X86, aggregates
793/// that contain SSE vectors are placed at 16-byte boundaries while the rest
794/// are at 4-byte boundaries.
795unsigned X86TargetLowering::getByValTypeAlignment(const Type *Ty) const {
796  if (Subtarget->is64Bit())
797    return getTargetData()->getABITypeAlignment(Ty);
798  unsigned Align = 4;
799  if (Subtarget->hasSSE1())
800    getMaxByValAlign(Ty, Align);
801  return Align;
802}
803
804/// getOptimalMemOpType - Returns the target specific optimal type for load
805/// and store operations as a result of memset, memcpy, and memmove
806/// lowering. It returns MVT::iAny if SelectionDAG should be responsible for
807/// determining it.
808MVT
809X86TargetLowering::getOptimalMemOpType(uint64_t Size, unsigned Align,
810                                       bool isSrcConst, bool isSrcStr) const {
811  if ((isSrcConst || isSrcStr) && Subtarget->hasSSE2() && Size >= 16)
812    return MVT::v4i32;
813  if ((isSrcConst || isSrcStr) && Subtarget->hasSSE1() && Size >= 16)
814    return MVT::v4f32;
815  if (Subtarget->is64Bit() && Size >= 8)
816    return MVT::i64;
817  return MVT::i32;
818}
819
820
821/// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
822/// jumptable.
823SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
824                                                      SelectionDAG &DAG) const {
825  if (usesGlobalOffsetTable())
826    return DAG.getNode(ISD::GLOBAL_OFFSET_TABLE, getPointerTy());
827  if (!Subtarget->isPICStyleRIPRel())
828    return DAG.getNode(X86ISD::GlobalBaseReg, getPointerTy());
829  return Table;
830}
831
832//===----------------------------------------------------------------------===//
833//               Return Value Calling Convention Implementation
834//===----------------------------------------------------------------------===//
835
836#include "X86GenCallingConv.inc"
837
838/// LowerRET - Lower an ISD::RET node.
839SDValue X86TargetLowering::LowerRET(SDValue Op, SelectionDAG &DAG) {
840  assert((Op.getNumOperands() & 1) == 1 && "ISD::RET should have odd # args");
841
842  SmallVector<CCValAssign, 16> RVLocs;
843  unsigned CC = DAG.getMachineFunction().getFunction()->getCallingConv();
844  bool isVarArg = DAG.getMachineFunction().getFunction()->isVarArg();
845  CCState CCInfo(CC, isVarArg, getTargetMachine(), RVLocs);
846  CCInfo.AnalyzeReturn(Op.Val, RetCC_X86);
847
848  // If this is the first return lowered for this function, add the regs to the
849  // liveout set for the function.
850  if (DAG.getMachineFunction().getRegInfo().liveout_empty()) {
851    for (unsigned i = 0; i != RVLocs.size(); ++i)
852      if (RVLocs[i].isRegLoc())
853        DAG.getMachineFunction().getRegInfo().addLiveOut(RVLocs[i].getLocReg());
854  }
855  SDValue Chain = Op.getOperand(0);
856
857  // Handle tail call return.
858  Chain = GetPossiblePreceedingTailCall(Chain, X86ISD::TAILCALL);
859  if (Chain.getOpcode() == X86ISD::TAILCALL) {
860    SDValue TailCall = Chain;
861    SDValue TargetAddress = TailCall.getOperand(1);
862    SDValue StackAdjustment = TailCall.getOperand(2);
863    assert(((TargetAddress.getOpcode() == ISD::Register &&
864               (cast<RegisterSDNode>(TargetAddress)->getReg() == X86::ECX ||
865                cast<RegisterSDNode>(TargetAddress)->getReg() == X86::R9)) ||
866              TargetAddress.getOpcode() == ISD::TargetExternalSymbol ||
867              TargetAddress.getOpcode() == ISD::TargetGlobalAddress) &&
868             "Expecting an global address, external symbol, or register");
869    assert(StackAdjustment.getOpcode() == ISD::Constant &&
870           "Expecting a const value");
871
872    SmallVector<SDValue,8> Operands;
873    Operands.push_back(Chain.getOperand(0));
874    Operands.push_back(TargetAddress);
875    Operands.push_back(StackAdjustment);
876    // Copy registers used by the call. Last operand is a flag so it is not
877    // copied.
878    for (unsigned i=3; i < TailCall.getNumOperands()-1; i++) {
879      Operands.push_back(Chain.getOperand(i));
880    }
881    return DAG.getNode(X86ISD::TC_RETURN, MVT::Other, &Operands[0],
882                       Operands.size());
883  }
884
885  // Regular return.
886  SDValue Flag;
887
888  SmallVector<SDValue, 6> RetOps;
889  RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
890  // Operand #1 = Bytes To Pop
891  RetOps.push_back(DAG.getConstant(getBytesToPopOnReturn(), MVT::i16));
892
893  // Copy the result values into the output registers.
894  for (unsigned i = 0; i != RVLocs.size(); ++i) {
895    CCValAssign &VA = RVLocs[i];
896    assert(VA.isRegLoc() && "Can only return in registers!");
897    SDValue ValToCopy = Op.getOperand(i*2+1);
898
899    // Returns in ST0/ST1 are handled specially: these are pushed as operands to
900    // the RET instruction and handled by the FP Stackifier.
901    if (RVLocs[i].getLocReg() == X86::ST0 ||
902        RVLocs[i].getLocReg() == X86::ST1) {
903      // If this is a copy from an xmm register to ST(0), use an FPExtend to
904      // change the value to the FP stack register class.
905      if (isScalarFPTypeInSSEReg(RVLocs[i].getValVT()))
906        ValToCopy = DAG.getNode(ISD::FP_EXTEND, MVT::f80, ValToCopy);
907      RetOps.push_back(ValToCopy);
908      // Don't emit a copytoreg.
909      continue;
910    }
911
912    Chain = DAG.getCopyToReg(Chain, VA.getLocReg(), ValToCopy, Flag);
913    Flag = Chain.getValue(1);
914  }
915
916  // The x86-64 ABI for returning structs by value requires that we copy
917  // the sret argument into %rax for the return. We saved the argument into
918  // a virtual register in the entry block, so now we copy the value out
919  // and into %rax.
920  if (Subtarget->is64Bit() &&
921      DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
922    MachineFunction &MF = DAG.getMachineFunction();
923    X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
924    unsigned Reg = FuncInfo->getSRetReturnReg();
925    if (!Reg) {
926      Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(MVT::i64));
927      FuncInfo->setSRetReturnReg(Reg);
928    }
929    SDValue Val = DAG.getCopyFromReg(Chain, Reg, getPointerTy());
930
931    Chain = DAG.getCopyToReg(Chain, X86::RAX, Val, Flag);
932    Flag = Chain.getValue(1);
933  }
934
935  RetOps[0] = Chain;  // Update chain.
936
937  // Add the flag if we have it.
938  if (Flag.Val)
939    RetOps.push_back(Flag);
940
941  return DAG.getNode(X86ISD::RET_FLAG, MVT::Other, &RetOps[0], RetOps.size());
942}
943
944
945/// LowerCallResult - Lower the result values of an ISD::CALL into the
946/// appropriate copies out of appropriate physical registers.  This assumes that
947/// Chain/InFlag are the input chain/flag to use, and that TheCall is the call
948/// being lowered.  The returns a SDNode with the same number of values as the
949/// ISD::CALL.
950SDNode *X86TargetLowering::
951LowerCallResult(SDValue Chain, SDValue InFlag, SDNode *TheCall,
952                unsigned CallingConv, SelectionDAG &DAG) {
953
954  // Assign locations to each value returned by this call.
955  SmallVector<CCValAssign, 16> RVLocs;
956  bool isVarArg = cast<ConstantSDNode>(TheCall->getOperand(2))->getValue() != 0;
957  CCState CCInfo(CallingConv, isVarArg, getTargetMachine(), RVLocs);
958  CCInfo.AnalyzeCallResult(TheCall, RetCC_X86);
959
960  SmallVector<SDValue, 8> ResultVals;
961
962  // Copy all of the result registers out of their specified physreg.
963  for (unsigned i = 0; i != RVLocs.size(); ++i) {
964    MVT CopyVT = RVLocs[i].getValVT();
965
966    // If this is a call to a function that returns an fp value on the floating
967    // point stack, but where we prefer to use the value in xmm registers, copy
968    // it out as F80 and use a truncate to move it from fp stack reg to xmm reg.
969    if (RVLocs[i].getLocReg() == X86::ST0 &&
970        isScalarFPTypeInSSEReg(RVLocs[i].getValVT())) {
971      CopyVT = MVT::f80;
972    }
973
974    Chain = DAG.getCopyFromReg(Chain, RVLocs[i].getLocReg(),
975                               CopyVT, InFlag).getValue(1);
976    SDValue Val = Chain.getValue(0);
977    InFlag = Chain.getValue(2);
978
979    if (CopyVT != RVLocs[i].getValVT()) {
980      // Round the F80 the right size, which also moves to the appropriate xmm
981      // register.
982      Val = DAG.getNode(ISD::FP_ROUND, RVLocs[i].getValVT(), Val,
983                        // This truncation won't change the value.
984                        DAG.getIntPtrConstant(1));
985    }
986
987    ResultVals.push_back(Val);
988  }
989
990  // Merge everything together with a MERGE_VALUES node.
991  ResultVals.push_back(Chain);
992  return DAG.getMergeValues(TheCall->getVTList(), &ResultVals[0],
993                            ResultVals.size()).Val;
994}
995
996
997//===----------------------------------------------------------------------===//
998//                C & StdCall & Fast Calling Convention implementation
999//===----------------------------------------------------------------------===//
1000//  StdCall calling convention seems to be standard for many Windows' API
1001//  routines and around. It differs from C calling convention just a little:
1002//  callee should clean up the stack, not caller. Symbols should be also
1003//  decorated in some fancy way :) It doesn't support any vector arguments.
1004//  For info on fast calling convention see Fast Calling Convention (tail call)
1005//  implementation LowerX86_32FastCCCallTo.
1006
1007/// AddLiveIn - This helper function adds the specified physical register to the
1008/// MachineFunction as a live in value.  It also creates a corresponding virtual
1009/// register for it.
1010static unsigned AddLiveIn(MachineFunction &MF, unsigned PReg,
1011                          const TargetRegisterClass *RC) {
1012  assert(RC->contains(PReg) && "Not the correct regclass!");
1013  unsigned VReg = MF.getRegInfo().createVirtualRegister(RC);
1014  MF.getRegInfo().addLiveIn(PReg, VReg);
1015  return VReg;
1016}
1017
1018/// CallIsStructReturn - Determines whether a CALL node uses struct return
1019/// semantics.
1020static bool CallIsStructReturn(SDValue Op) {
1021  unsigned NumOps = (Op.getNumOperands() - 5) / 2;
1022  if (!NumOps)
1023    return false;
1024
1025  return cast<ARG_FLAGSSDNode>(Op.getOperand(6))->getArgFlags().isSRet();
1026}
1027
1028/// ArgsAreStructReturn - Determines whether a FORMAL_ARGUMENTS node uses struct
1029/// return semantics.
1030static bool ArgsAreStructReturn(SDValue Op) {
1031  unsigned NumArgs = Op.Val->getNumValues() - 1;
1032  if (!NumArgs)
1033    return false;
1034
1035  return cast<ARG_FLAGSSDNode>(Op.getOperand(3))->getArgFlags().isSRet();
1036}
1037
1038/// IsCalleePop - Determines whether a CALL or FORMAL_ARGUMENTS node requires
1039/// the callee to pop its own arguments. Callee pop is necessary to support tail
1040/// calls.
1041bool X86TargetLowering::IsCalleePop(SDValue Op) {
1042  bool IsVarArg = cast<ConstantSDNode>(Op.getOperand(2))->getValue() != 0;
1043  if (IsVarArg)
1044    return false;
1045
1046  switch (cast<ConstantSDNode>(Op.getOperand(1))->getValue()) {
1047  default:
1048    return false;
1049  case CallingConv::X86_StdCall:
1050    return !Subtarget->is64Bit();
1051  case CallingConv::X86_FastCall:
1052    return !Subtarget->is64Bit();
1053  case CallingConv::Fast:
1054    return PerformTailCallOpt;
1055  }
1056}
1057
1058/// CCAssignFnForNode - Selects the correct CCAssignFn for a CALL or
1059/// FORMAL_ARGUMENTS node.
1060CCAssignFn *X86TargetLowering::CCAssignFnForNode(SDValue Op) const {
1061  unsigned CC = cast<ConstantSDNode>(Op.getOperand(1))->getValue();
1062
1063  if (Subtarget->is64Bit()) {
1064    if (Subtarget->isTargetWin64())
1065      return CC_X86_Win64_C;
1066    else {
1067      if (CC == CallingConv::Fast && PerformTailCallOpt)
1068        return CC_X86_64_TailCall;
1069      else
1070        return CC_X86_64_C;
1071    }
1072  }
1073
1074  if (CC == CallingConv::X86_FastCall)
1075    return CC_X86_32_FastCall;
1076  else if (CC == CallingConv::Fast && PerformTailCallOpt)
1077    return CC_X86_32_TailCall;
1078  else
1079    return CC_X86_32_C;
1080}
1081
1082/// NameDecorationForFORMAL_ARGUMENTS - Selects the appropriate decoration to
1083/// apply to a MachineFunction containing a given FORMAL_ARGUMENTS node.
1084NameDecorationStyle
1085X86TargetLowering::NameDecorationForFORMAL_ARGUMENTS(SDValue Op) {
1086  unsigned CC = cast<ConstantSDNode>(Op.getOperand(1))->getValue();
1087  if (CC == CallingConv::X86_FastCall)
1088    return FastCall;
1089  else if (CC == CallingConv::X86_StdCall)
1090    return StdCall;
1091  return None;
1092}
1093
1094
1095/// CallRequiresGOTInRegister - Check whether the call requires the GOT pointer
1096/// in a register before calling.
1097bool X86TargetLowering::CallRequiresGOTPtrInReg(bool Is64Bit, bool IsTailCall) {
1098  return !IsTailCall && !Is64Bit &&
1099    getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1100    Subtarget->isPICStyleGOT();
1101}
1102
1103/// CallRequiresFnAddressInReg - Check whether the call requires the function
1104/// address to be loaded in a register.
1105bool
1106X86TargetLowering::CallRequiresFnAddressInReg(bool Is64Bit, bool IsTailCall) {
1107  return !Is64Bit && IsTailCall &&
1108    getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1109    Subtarget->isPICStyleGOT();
1110}
1111
1112/// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
1113/// by "Src" to address "Dst" with size and alignment information specified by
1114/// the specific parameter attribute. The copy will be passed as a byval
1115/// function parameter.
1116static SDValue
1117CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
1118                          ISD::ArgFlagsTy Flags, SelectionDAG &DAG) {
1119  SDValue SizeNode     = DAG.getConstant(Flags.getByValSize(), MVT::i32);
1120  return DAG.getMemcpy(Chain, Dst, Src, SizeNode, Flags.getByValAlign(),
1121                       /*AlwaysInline=*/true, NULL, 0, NULL, 0);
1122}
1123
1124SDValue X86TargetLowering::LowerMemArgument(SDValue Op, SelectionDAG &DAG,
1125                                              const CCValAssign &VA,
1126                                              MachineFrameInfo *MFI,
1127                                              unsigned CC,
1128                                              SDValue Root, unsigned i) {
1129  // Create the nodes corresponding to a load from this parameter slot.
1130  ISD::ArgFlagsTy Flags =
1131    cast<ARG_FLAGSSDNode>(Op.getOperand(3 + i))->getArgFlags();
1132  bool AlwaysUseMutable = (CC==CallingConv::Fast) && PerformTailCallOpt;
1133  bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
1134
1135  // FIXME: For now, all byval parameter objects are marked mutable. This can be
1136  // changed with more analysis.
1137  // In case of tail call optimization mark all arguments mutable. Since they
1138  // could be overwritten by lowering of arguments in case of a tail call.
1139  int FI = MFI->CreateFixedObject(VA.getValVT().getSizeInBits()/8,
1140                                  VA.getLocMemOffset(), isImmutable);
1141  SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
1142  if (Flags.isByVal())
1143    return FIN;
1144  return DAG.getLoad(VA.getValVT(), Root, FIN,
1145                     PseudoSourceValue::getFixedStack(FI), 0);
1146}
1147
1148SDValue
1149X86TargetLowering::LowerFORMAL_ARGUMENTS(SDValue Op, SelectionDAG &DAG) {
1150  MachineFunction &MF = DAG.getMachineFunction();
1151  X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1152
1153  const Function* Fn = MF.getFunction();
1154  if (Fn->hasExternalLinkage() &&
1155      Subtarget->isTargetCygMing() &&
1156      Fn->getName() == "main")
1157    FuncInfo->setForceFramePointer(true);
1158
1159  // Decorate the function name.
1160  FuncInfo->setDecorationStyle(NameDecorationForFORMAL_ARGUMENTS(Op));
1161
1162  MachineFrameInfo *MFI = MF.getFrameInfo();
1163  SDValue Root = Op.getOperand(0);
1164  bool isVarArg = cast<ConstantSDNode>(Op.getOperand(2))->getValue() != 0;
1165  unsigned CC = MF.getFunction()->getCallingConv();
1166  bool Is64Bit = Subtarget->is64Bit();
1167  bool IsWin64 = Subtarget->isTargetWin64();
1168
1169  assert(!(isVarArg && CC == CallingConv::Fast) &&
1170         "Var args not supported with calling convention fastcc");
1171
1172  // Assign locations to all of the incoming arguments.
1173  SmallVector<CCValAssign, 16> ArgLocs;
1174  CCState CCInfo(CC, isVarArg, getTargetMachine(), ArgLocs);
1175  CCInfo.AnalyzeFormalArguments(Op.Val, CCAssignFnForNode(Op));
1176
1177  SmallVector<SDValue, 8> ArgValues;
1178  unsigned LastVal = ~0U;
1179  for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1180    CCValAssign &VA = ArgLocs[i];
1181    // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
1182    // places.
1183    assert(VA.getValNo() != LastVal &&
1184           "Don't support value assigned to multiple locs yet");
1185    LastVal = VA.getValNo();
1186
1187    if (VA.isRegLoc()) {
1188      MVT RegVT = VA.getLocVT();
1189      TargetRegisterClass *RC;
1190      if (RegVT == MVT::i32)
1191        RC = X86::GR32RegisterClass;
1192      else if (Is64Bit && RegVT == MVT::i64)
1193        RC = X86::GR64RegisterClass;
1194      else if (RegVT == MVT::f32)
1195        RC = X86::FR32RegisterClass;
1196      else if (RegVT == MVT::f64)
1197        RC = X86::FR64RegisterClass;
1198      else if (RegVT.isVector() && RegVT.getSizeInBits() == 128)
1199        RC = X86::VR128RegisterClass;
1200      else if (RegVT.isVector()) {
1201        assert(RegVT.getSizeInBits() == 64);
1202        if (!Is64Bit)
1203          RC = X86::VR64RegisterClass;     // MMX values are passed in MMXs.
1204        else {
1205          // Darwin calling convention passes MMX values in either GPRs or
1206          // XMMs in x86-64. Other targets pass them in memory.
1207          if (RegVT != MVT::v1i64 && Subtarget->hasSSE2()) {
1208            RC = X86::VR128RegisterClass;  // MMX values are passed in XMMs.
1209            RegVT = MVT::v2i64;
1210          } else {
1211            RC = X86::GR64RegisterClass;   // v1i64 values are passed in GPRs.
1212            RegVT = MVT::i64;
1213          }
1214        }
1215      } else {
1216        assert(0 && "Unknown argument type!");
1217      }
1218
1219      unsigned Reg = AddLiveIn(DAG.getMachineFunction(), VA.getLocReg(), RC);
1220      SDValue ArgValue = DAG.getCopyFromReg(Root, Reg, RegVT);
1221
1222      // If this is an 8 or 16-bit value, it is really passed promoted to 32
1223      // bits.  Insert an assert[sz]ext to capture this, then truncate to the
1224      // right size.
1225      if (VA.getLocInfo() == CCValAssign::SExt)
1226        ArgValue = DAG.getNode(ISD::AssertSext, RegVT, ArgValue,
1227                               DAG.getValueType(VA.getValVT()));
1228      else if (VA.getLocInfo() == CCValAssign::ZExt)
1229        ArgValue = DAG.getNode(ISD::AssertZext, RegVT, ArgValue,
1230                               DAG.getValueType(VA.getValVT()));
1231
1232      if (VA.getLocInfo() != CCValAssign::Full)
1233        ArgValue = DAG.getNode(ISD::TRUNCATE, VA.getValVT(), ArgValue);
1234
1235      // Handle MMX values passed in GPRs.
1236      if (Is64Bit && RegVT != VA.getLocVT()) {
1237        if (RegVT.getSizeInBits() == 64 && RC == X86::GR64RegisterClass)
1238          ArgValue = DAG.getNode(ISD::BIT_CONVERT, VA.getLocVT(), ArgValue);
1239        else if (RC == X86::VR128RegisterClass) {
1240          ArgValue = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, MVT::i64, ArgValue,
1241                                 DAG.getConstant(0, MVT::i64));
1242          ArgValue = DAG.getNode(ISD::BIT_CONVERT, VA.getLocVT(), ArgValue);
1243        }
1244      }
1245
1246      ArgValues.push_back(ArgValue);
1247    } else {
1248      assert(VA.isMemLoc());
1249      ArgValues.push_back(LowerMemArgument(Op, DAG, VA, MFI, CC, Root, i));
1250    }
1251  }
1252
1253  // The x86-64 ABI for returning structs by value requires that we copy
1254  // the sret argument into %rax for the return. Save the argument into
1255  // a virtual register so that we can access it from the return points.
1256  if (Is64Bit && DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
1257    MachineFunction &MF = DAG.getMachineFunction();
1258    X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1259    unsigned Reg = FuncInfo->getSRetReturnReg();
1260    if (!Reg) {
1261      Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(MVT::i64));
1262      FuncInfo->setSRetReturnReg(Reg);
1263    }
1264    SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), Reg, ArgValues[0]);
1265    Root = DAG.getNode(ISD::TokenFactor, MVT::Other, Copy, Root);
1266  }
1267
1268  unsigned StackSize = CCInfo.getNextStackOffset();
1269  // align stack specially for tail calls
1270  if (CC == CallingConv::Fast)
1271    StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
1272
1273  // If the function takes variable number of arguments, make a frame index for
1274  // the start of the first vararg value... for expansion of llvm.va_start.
1275  if (isVarArg) {
1276    if (Is64Bit || CC != CallingConv::X86_FastCall) {
1277      VarArgsFrameIndex = MFI->CreateFixedObject(1, StackSize);
1278    }
1279    if (Is64Bit) {
1280      unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
1281
1282      // FIXME: We should really autogenerate these arrays
1283      static const unsigned GPR64ArgRegsWin64[] = {
1284        X86::RCX, X86::RDX, X86::R8,  X86::R9
1285      };
1286      static const unsigned XMMArgRegsWin64[] = {
1287        X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3
1288      };
1289      static const unsigned GPR64ArgRegs64Bit[] = {
1290        X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
1291      };
1292      static const unsigned XMMArgRegs64Bit[] = {
1293        X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
1294        X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
1295      };
1296      const unsigned *GPR64ArgRegs, *XMMArgRegs;
1297
1298      if (IsWin64) {
1299        TotalNumIntRegs = 4; TotalNumXMMRegs = 4;
1300        GPR64ArgRegs = GPR64ArgRegsWin64;
1301        XMMArgRegs = XMMArgRegsWin64;
1302      } else {
1303        TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
1304        GPR64ArgRegs = GPR64ArgRegs64Bit;
1305        XMMArgRegs = XMMArgRegs64Bit;
1306      }
1307      unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
1308                                                       TotalNumIntRegs);
1309      unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs,
1310                                                       TotalNumXMMRegs);
1311
1312      // For X86-64, if there are vararg parameters that are passed via
1313      // registers, then we must store them to their spots on the stack so they
1314      // may be loaded by deferencing the result of va_next.
1315      VarArgsGPOffset = NumIntRegs * 8;
1316      VarArgsFPOffset = TotalNumIntRegs * 8 + NumXMMRegs * 16;
1317      RegSaveFrameIndex = MFI->CreateStackObject(TotalNumIntRegs * 8 +
1318                                                 TotalNumXMMRegs * 16, 16);
1319
1320      // Store the integer parameter registers.
1321      SmallVector<SDValue, 8> MemOps;
1322      SDValue RSFIN = DAG.getFrameIndex(RegSaveFrameIndex, getPointerTy());
1323      SDValue FIN = DAG.getNode(ISD::ADD, getPointerTy(), RSFIN,
1324                                  DAG.getIntPtrConstant(VarArgsGPOffset));
1325      for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
1326        unsigned VReg = AddLiveIn(MF, GPR64ArgRegs[NumIntRegs],
1327                                  X86::GR64RegisterClass);
1328        SDValue Val = DAG.getCopyFromReg(Root, VReg, MVT::i64);
1329        SDValue Store =
1330          DAG.getStore(Val.getValue(1), Val, FIN,
1331                       PseudoSourceValue::getFixedStack(RegSaveFrameIndex), 0);
1332        MemOps.push_back(Store);
1333        FIN = DAG.getNode(ISD::ADD, getPointerTy(), FIN,
1334                          DAG.getIntPtrConstant(8));
1335      }
1336
1337      // Now store the XMM (fp + vector) parameter registers.
1338      FIN = DAG.getNode(ISD::ADD, getPointerTy(), RSFIN,
1339                        DAG.getIntPtrConstant(VarArgsFPOffset));
1340      for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
1341        unsigned VReg = AddLiveIn(MF, XMMArgRegs[NumXMMRegs],
1342                                  X86::VR128RegisterClass);
1343        SDValue Val = DAG.getCopyFromReg(Root, VReg, MVT::v4f32);
1344        SDValue Store =
1345          DAG.getStore(Val.getValue(1), Val, FIN,
1346                       PseudoSourceValue::getFixedStack(RegSaveFrameIndex), 0);
1347        MemOps.push_back(Store);
1348        FIN = DAG.getNode(ISD::ADD, getPointerTy(), FIN,
1349                          DAG.getIntPtrConstant(16));
1350      }
1351      if (!MemOps.empty())
1352          Root = DAG.getNode(ISD::TokenFactor, MVT::Other,
1353                             &MemOps[0], MemOps.size());
1354    }
1355  }
1356
1357  // Make sure the instruction takes 8n+4 bytes to make sure the start of the
1358  // arguments and the arguments after the retaddr has been pushed are
1359  // aligned.
1360  if (!Is64Bit && CC == CallingConv::X86_FastCall &&
1361      !Subtarget->isTargetCygMing() && !Subtarget->isTargetWindows() &&
1362      (StackSize & 7) == 0)
1363    StackSize += 4;
1364
1365  ArgValues.push_back(Root);
1366
1367  // Some CCs need callee pop.
1368  if (IsCalleePop(Op)) {
1369    BytesToPopOnReturn  = StackSize; // Callee pops everything.
1370    BytesCallerReserves = 0;
1371  } else {
1372    BytesToPopOnReturn  = 0; // Callee pops nothing.
1373    // If this is an sret function, the return should pop the hidden pointer.
1374    if (!Is64Bit && ArgsAreStructReturn(Op))
1375      BytesToPopOnReturn = 4;
1376    BytesCallerReserves = StackSize;
1377  }
1378
1379  if (!Is64Bit) {
1380    RegSaveFrameIndex = 0xAAAAAAA;   // RegSaveFrameIndex is X86-64 only.
1381    if (CC == CallingConv::X86_FastCall)
1382      VarArgsFrameIndex = 0xAAAAAAA;   // fastcc functions can't have varargs.
1383  }
1384
1385  FuncInfo->setBytesToPopOnReturn(BytesToPopOnReturn);
1386
1387  // Return the new list of results.
1388  return DAG.getMergeValues(Op.Val->getVTList(), &ArgValues[0],
1389                            ArgValues.size()).getValue(Op.ResNo);
1390}
1391
1392SDValue
1393X86TargetLowering::LowerMemOpCallTo(SDValue Op, SelectionDAG &DAG,
1394                                    const SDValue &StackPtr,
1395                                    const CCValAssign &VA,
1396                                    SDValue Chain,
1397                                    SDValue Arg) {
1398  unsigned LocMemOffset = VA.getLocMemOffset();
1399  SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
1400  PtrOff = DAG.getNode(ISD::ADD, getPointerTy(), StackPtr, PtrOff);
1401  ISD::ArgFlagsTy Flags =
1402    cast<ARG_FLAGSSDNode>(Op.getOperand(6+2*VA.getValNo()))->getArgFlags();
1403  if (Flags.isByVal()) {
1404    return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG);
1405  }
1406  return DAG.getStore(Chain, Arg, PtrOff,
1407                      PseudoSourceValue::getStack(), LocMemOffset);
1408}
1409
1410/// EmitTailCallLoadRetAddr - Emit a load of return adress if tail call
1411/// optimization is performed and it is required.
1412SDValue
1413X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
1414                                           SDValue &OutRetAddr,
1415                                           SDValue Chain,
1416                                           bool IsTailCall,
1417                                           bool Is64Bit,
1418                                           int FPDiff) {
1419  if (!IsTailCall || FPDiff==0) return Chain;
1420
1421  // Adjust the Return address stack slot.
1422  MVT VT = getPointerTy();
1423  OutRetAddr = getReturnAddressFrameIndex(DAG);
1424  // Load the "old" Return address.
1425  OutRetAddr = DAG.getLoad(VT, Chain,OutRetAddr, NULL, 0);
1426  return SDValue(OutRetAddr.Val, 1);
1427}
1428
1429/// EmitTailCallStoreRetAddr - Emit a store of the return adress if tail call
1430/// optimization is performed and it is required (FPDiff!=0).
1431static SDValue
1432EmitTailCallStoreRetAddr(SelectionDAG & DAG, MachineFunction &MF,
1433                         SDValue Chain, SDValue RetAddrFrIdx,
1434                         bool Is64Bit, int FPDiff) {
1435  // Store the return address to the appropriate stack slot.
1436  if (!FPDiff) return Chain;
1437  // Calculate the new stack slot for the return address.
1438  int SlotSize = Is64Bit ? 8 : 4;
1439  int NewReturnAddrFI =
1440    MF.getFrameInfo()->CreateFixedObject(SlotSize, FPDiff-SlotSize);
1441  MVT VT = Is64Bit ? MVT::i64 : MVT::i32;
1442  SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, VT);
1443  Chain = DAG.getStore(Chain, RetAddrFrIdx, NewRetAddrFrIdx,
1444                       PseudoSourceValue::getFixedStack(NewReturnAddrFI), 0);
1445  return Chain;
1446}
1447
1448SDValue X86TargetLowering::LowerCALL(SDValue Op, SelectionDAG &DAG) {
1449  MachineFunction &MF = DAG.getMachineFunction();
1450  SDValue Chain     = Op.getOperand(0);
1451  unsigned CC         = cast<ConstantSDNode>(Op.getOperand(1))->getValue();
1452  bool isVarArg       = cast<ConstantSDNode>(Op.getOperand(2))->getValue() != 0;
1453  bool IsTailCall     = cast<ConstantSDNode>(Op.getOperand(3))->getValue() != 0
1454                        && CC == CallingConv::Fast && PerformTailCallOpt;
1455  SDValue Callee    = Op.getOperand(4);
1456  bool Is64Bit        = Subtarget->is64Bit();
1457  bool IsStructRet    = CallIsStructReturn(Op);
1458
1459  assert(!(isVarArg && CC == CallingConv::Fast) &&
1460         "Var args not supported with calling convention fastcc");
1461
1462  // Analyze operands of the call, assigning locations to each operand.
1463  SmallVector<CCValAssign, 16> ArgLocs;
1464  CCState CCInfo(CC, isVarArg, getTargetMachine(), ArgLocs);
1465  CCInfo.AnalyzeCallOperands(Op.Val, CCAssignFnForNode(Op));
1466
1467  // Get a count of how many bytes are to be pushed on the stack.
1468  unsigned NumBytes = CCInfo.getNextStackOffset();
1469  if (CC == CallingConv::Fast)
1470    NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
1471
1472  // Make sure the instruction takes 8n+4 bytes to make sure the start of the
1473  // arguments and the arguments after the retaddr has been pushed are aligned.
1474  if (!Is64Bit && CC == CallingConv::X86_FastCall &&
1475      !Subtarget->isTargetCygMing() && !Subtarget->isTargetWindows() &&
1476      (NumBytes & 7) == 0)
1477    NumBytes += 4;
1478
1479  int FPDiff = 0;
1480  if (IsTailCall) {
1481    // Lower arguments at fp - stackoffset + fpdiff.
1482    unsigned NumBytesCallerPushed =
1483      MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn();
1484    FPDiff = NumBytesCallerPushed - NumBytes;
1485
1486    // Set the delta of movement of the returnaddr stackslot.
1487    // But only set if delta is greater than previous delta.
1488    if (FPDiff < (MF.getInfo<X86MachineFunctionInfo>()->getTCReturnAddrDelta()))
1489      MF.getInfo<X86MachineFunctionInfo>()->setTCReturnAddrDelta(FPDiff);
1490  }
1491
1492  Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes));
1493
1494  SDValue RetAddrFrIdx;
1495  // Load return adress for tail calls.
1496  Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, IsTailCall, Is64Bit,
1497                                  FPDiff);
1498
1499  SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
1500  SmallVector<SDValue, 8> MemOpChains;
1501  SDValue StackPtr;
1502
1503  // Walk the register/memloc assignments, inserting copies/loads.  In the case
1504  // of tail call optimization arguments are handle later.
1505  for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1506    CCValAssign &VA = ArgLocs[i];
1507    SDValue Arg = Op.getOperand(5+2*VA.getValNo());
1508    bool isByVal = cast<ARG_FLAGSSDNode>(Op.getOperand(6+2*VA.getValNo()))->
1509      getArgFlags().isByVal();
1510
1511    // Promote the value if needed.
1512    switch (VA.getLocInfo()) {
1513    default: assert(0 && "Unknown loc info!");
1514    case CCValAssign::Full: break;
1515    case CCValAssign::SExt:
1516      Arg = DAG.getNode(ISD::SIGN_EXTEND, VA.getLocVT(), Arg);
1517      break;
1518    case CCValAssign::ZExt:
1519      Arg = DAG.getNode(ISD::ZERO_EXTEND, VA.getLocVT(), Arg);
1520      break;
1521    case CCValAssign::AExt:
1522      Arg = DAG.getNode(ISD::ANY_EXTEND, VA.getLocVT(), Arg);
1523      break;
1524    }
1525
1526    if (VA.isRegLoc()) {
1527      if (Is64Bit) {
1528        MVT RegVT = VA.getLocVT();
1529        if (RegVT.isVector() && RegVT.getSizeInBits() == 64)
1530          switch (VA.getLocReg()) {
1531          default:
1532            break;
1533          case X86::RDI: case X86::RSI: case X86::RDX: case X86::RCX:
1534          case X86::R8: {
1535            // Special case: passing MMX values in GPR registers.
1536            Arg = DAG.getNode(ISD::BIT_CONVERT, MVT::i64, Arg);
1537            break;
1538          }
1539          case X86::XMM0: case X86::XMM1: case X86::XMM2: case X86::XMM3:
1540          case X86::XMM4: case X86::XMM5: case X86::XMM6: case X86::XMM7: {
1541            // Special case: passing MMX values in XMM registers.
1542            Arg = DAG.getNode(ISD::BIT_CONVERT, MVT::i64, Arg);
1543            Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, MVT::v2i64, Arg);
1544            Arg = DAG.getNode(ISD::VECTOR_SHUFFLE, MVT::v2i64,
1545                              DAG.getNode(ISD::UNDEF, MVT::v2i64), Arg,
1546                              getMOVLMask(2, DAG));
1547            break;
1548          }
1549          }
1550      }
1551      RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1552    } else {
1553      if (!IsTailCall || (IsTailCall && isByVal)) {
1554        assert(VA.isMemLoc());
1555        if (StackPtr.Val == 0)
1556          StackPtr = DAG.getCopyFromReg(Chain, X86StackPtr, getPointerTy());
1557
1558        MemOpChains.push_back(LowerMemOpCallTo(Op, DAG, StackPtr, VA, Chain,
1559                                               Arg));
1560      }
1561    }
1562  }
1563
1564  if (!MemOpChains.empty())
1565    Chain = DAG.getNode(ISD::TokenFactor, MVT::Other,
1566                        &MemOpChains[0], MemOpChains.size());
1567
1568  // Build a sequence of copy-to-reg nodes chained together with token chain
1569  // and flag operands which copy the outgoing args into registers.
1570  SDValue InFlag;
1571  // Tail call byval lowering might overwrite argument registers so in case of
1572  // tail call optimization the copies to registers are lowered later.
1573  if (!IsTailCall)
1574    for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1575      Chain = DAG.getCopyToReg(Chain, RegsToPass[i].first, RegsToPass[i].second,
1576                               InFlag);
1577      InFlag = Chain.getValue(1);
1578    }
1579
1580  // ELF / PIC requires GOT in the EBX register before function calls via PLT
1581  // GOT pointer.
1582  if (CallRequiresGOTPtrInReg(Is64Bit, IsTailCall)) {
1583    Chain = DAG.getCopyToReg(Chain, X86::EBX,
1584                             DAG.getNode(X86ISD::GlobalBaseReg, getPointerTy()),
1585                             InFlag);
1586    InFlag = Chain.getValue(1);
1587  }
1588  // If we are tail calling and generating PIC/GOT style code load the address
1589  // of the callee into ecx. The value in ecx is used as target of the tail
1590  // jump. This is done to circumvent the ebx/callee-saved problem for tail
1591  // calls on PIC/GOT architectures. Normally we would just put the address of
1592  // GOT into ebx and then call target@PLT. But for tail callss ebx would be
1593  // restored (since ebx is callee saved) before jumping to the target@PLT.
1594  if (CallRequiresFnAddressInReg(Is64Bit, IsTailCall)) {
1595    // Note: The actual moving to ecx is done further down.
1596    GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
1597    if (G &&  !G->getGlobal()->hasHiddenVisibility() &&
1598        !G->getGlobal()->hasProtectedVisibility())
1599      Callee =  LowerGlobalAddress(Callee, DAG);
1600    else if (isa<ExternalSymbolSDNode>(Callee))
1601      Callee = LowerExternalSymbol(Callee,DAG);
1602  }
1603
1604  if (Is64Bit && isVarArg) {
1605    // From AMD64 ABI document:
1606    // For calls that may call functions that use varargs or stdargs
1607    // (prototype-less calls or calls to functions containing ellipsis (...) in
1608    // the declaration) %al is used as hidden argument to specify the number
1609    // of SSE registers used. The contents of %al do not need to match exactly
1610    // the number of registers, but must be an ubound on the number of SSE
1611    // registers used and is in the range 0 - 8 inclusive.
1612
1613    // FIXME: Verify this on Win64
1614    // Count the number of XMM registers allocated.
1615    static const unsigned XMMArgRegs[] = {
1616      X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
1617      X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
1618    };
1619    unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
1620
1621    Chain = DAG.getCopyToReg(Chain, X86::AL,
1622                             DAG.getConstant(NumXMMRegs, MVT::i8), InFlag);
1623    InFlag = Chain.getValue(1);
1624  }
1625
1626
1627  // For tail calls lower the arguments to the 'real' stack slot.
1628  if (IsTailCall) {
1629    SmallVector<SDValue, 8> MemOpChains2;
1630    SDValue FIN;
1631    int FI = 0;
1632    // Do not flag preceeding copytoreg stuff together with the following stuff.
1633    InFlag = SDValue();
1634    for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1635      CCValAssign &VA = ArgLocs[i];
1636      if (!VA.isRegLoc()) {
1637        assert(VA.isMemLoc());
1638        SDValue Arg = Op.getOperand(5+2*VA.getValNo());
1639        SDValue FlagsOp = Op.getOperand(6+2*VA.getValNo());
1640        ISD::ArgFlagsTy Flags =
1641          cast<ARG_FLAGSSDNode>(FlagsOp)->getArgFlags();
1642        // Create frame index.
1643        int32_t Offset = VA.getLocMemOffset()+FPDiff;
1644        uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
1645        FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset);
1646        FIN = DAG.getFrameIndex(FI, getPointerTy());
1647
1648        if (Flags.isByVal()) {
1649          // Copy relative to framepointer.
1650          SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
1651          if (StackPtr.Val == 0)
1652            StackPtr = DAG.getCopyFromReg(Chain, X86StackPtr, getPointerTy());
1653          Source = DAG.getNode(ISD::ADD, getPointerTy(), StackPtr, Source);
1654
1655          MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN, Chain,
1656                                                           Flags, DAG));
1657        } else {
1658          // Store relative to framepointer.
1659          MemOpChains2.push_back(
1660            DAG.getStore(Chain, Arg, FIN,
1661                         PseudoSourceValue::getFixedStack(FI), 0));
1662        }
1663      }
1664    }
1665
1666    if (!MemOpChains2.empty())
1667      Chain = DAG.getNode(ISD::TokenFactor, MVT::Other,
1668                          &MemOpChains2[0], MemOpChains2.size());
1669
1670    // Copy arguments to their registers.
1671    for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1672      Chain = DAG.getCopyToReg(Chain, RegsToPass[i].first, RegsToPass[i].second,
1673                               InFlag);
1674      InFlag = Chain.getValue(1);
1675    }
1676    InFlag =SDValue();
1677
1678    // Store the return address to the appropriate stack slot.
1679    Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx, Is64Bit,
1680                                     FPDiff);
1681  }
1682
1683  // If the callee is a GlobalAddress node (quite common, every direct call is)
1684  // turn it into a TargetGlobalAddress node so that legalize doesn't hack it.
1685  if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1686    // We should use extra load for direct calls to dllimported functions in
1687    // non-JIT mode.
1688    if (!Subtarget->GVRequiresExtraLoad(G->getGlobal(),
1689                                        getTargetMachine(), true))
1690      Callee = DAG.getTargetGlobalAddress(G->getGlobal(), getPointerTy());
1691  } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
1692    Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy());
1693  } else if (IsTailCall) {
1694    unsigned Opc = Is64Bit ? X86::R9 : X86::ECX;
1695
1696    Chain = DAG.getCopyToReg(Chain,
1697                             DAG.getRegister(Opc, getPointerTy()),
1698                             Callee,InFlag);
1699    Callee = DAG.getRegister(Opc, getPointerTy());
1700    // Add register as live out.
1701    DAG.getMachineFunction().getRegInfo().addLiveOut(Opc);
1702  }
1703
1704  // Returns a chain & a flag for retval copy to use.
1705  SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
1706  SmallVector<SDValue, 8> Ops;
1707
1708  if (IsTailCall) {
1709    Ops.push_back(Chain);
1710    Ops.push_back(DAG.getIntPtrConstant(NumBytes));
1711    Ops.push_back(DAG.getIntPtrConstant(0));
1712    if (InFlag.Val)
1713      Ops.push_back(InFlag);
1714    Chain = DAG.getNode(ISD::CALLSEQ_END, NodeTys, &Ops[0], Ops.size());
1715    InFlag = Chain.getValue(1);
1716
1717    // Returns a chain & a flag for retval copy to use.
1718    NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
1719    Ops.clear();
1720  }
1721
1722  Ops.push_back(Chain);
1723  Ops.push_back(Callee);
1724
1725  if (IsTailCall)
1726    Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
1727
1728  // Add argument registers to the end of the list so that they are known live
1729  // into the call.
1730  for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
1731    Ops.push_back(DAG.getRegister(RegsToPass[i].first,
1732                                  RegsToPass[i].second.getValueType()));
1733
1734  // Add an implicit use GOT pointer in EBX.
1735  if (!IsTailCall && !Is64Bit &&
1736      getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1737      Subtarget->isPICStyleGOT())
1738    Ops.push_back(DAG.getRegister(X86::EBX, getPointerTy()));
1739
1740  // Add an implicit use of AL for x86 vararg functions.
1741  if (Is64Bit && isVarArg)
1742    Ops.push_back(DAG.getRegister(X86::AL, MVT::i8));
1743
1744  if (InFlag.Val)
1745    Ops.push_back(InFlag);
1746
1747  if (IsTailCall) {
1748    assert(InFlag.Val &&
1749           "Flag must be set. Depend on flag being set in LowerRET");
1750    Chain = DAG.getNode(X86ISD::TAILCALL,
1751                        Op.Val->getVTList(), &Ops[0], Ops.size());
1752
1753    return SDValue(Chain.Val, Op.ResNo);
1754  }
1755
1756  Chain = DAG.getNode(X86ISD::CALL, NodeTys, &Ops[0], Ops.size());
1757  InFlag = Chain.getValue(1);
1758
1759  // Create the CALLSEQ_END node.
1760  unsigned NumBytesForCalleeToPush;
1761  if (IsCalleePop(Op))
1762    NumBytesForCalleeToPush = NumBytes;    // Callee pops everything
1763  else if (!Is64Bit && IsStructRet)
1764    // If this is is a call to a struct-return function, the callee
1765    // pops the hidden struct pointer, so we have to push it back.
1766    // This is common for Darwin/X86, Linux & Mingw32 targets.
1767    NumBytesForCalleeToPush = 4;
1768  else
1769    NumBytesForCalleeToPush = 0;  // Callee pops nothing.
1770
1771  // Returns a flag for retval copy to use.
1772  Chain = DAG.getCALLSEQ_END(Chain,
1773                             DAG.getIntPtrConstant(NumBytes),
1774                             DAG.getIntPtrConstant(NumBytesForCalleeToPush),
1775                             InFlag);
1776  InFlag = Chain.getValue(1);
1777
1778  // Handle result values, copying them out of physregs into vregs that we
1779  // return.
1780  return SDValue(LowerCallResult(Chain, InFlag, Op.Val, CC, DAG), Op.ResNo);
1781}
1782
1783
1784//===----------------------------------------------------------------------===//
1785//                Fast Calling Convention (tail call) implementation
1786//===----------------------------------------------------------------------===//
1787
1788//  Like std call, callee cleans arguments, convention except that ECX is
1789//  reserved for storing the tail called function address. Only 2 registers are
1790//  free for argument passing (inreg). Tail call optimization is performed
1791//  provided:
1792//                * tailcallopt is enabled
1793//                * caller/callee are fastcc
1794//  On X86_64 architecture with GOT-style position independent code only local
1795//  (within module) calls are supported at the moment.
1796//  To keep the stack aligned according to platform abi the function
1797//  GetAlignedArgumentStackSize ensures that argument delta is always multiples
1798//  of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
1799//  If a tail called function callee has more arguments than the caller the
1800//  caller needs to make sure that there is room to move the RETADDR to. This is
1801//  achieved by reserving an area the size of the argument delta right after the
1802//  original REtADDR, but before the saved framepointer or the spilled registers
1803//  e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
1804//  stack layout:
1805//    arg1
1806//    arg2
1807//    RETADDR
1808//    [ new RETADDR
1809//      move area ]
1810//    (possible EBP)
1811//    ESI
1812//    EDI
1813//    local1 ..
1814
1815/// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
1816/// for a 16 byte align requirement.
1817unsigned X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
1818                                                        SelectionDAG& DAG) {
1819  if (PerformTailCallOpt) {
1820    MachineFunction &MF = DAG.getMachineFunction();
1821    const TargetMachine &TM = MF.getTarget();
1822    const TargetFrameInfo &TFI = *TM.getFrameInfo();
1823    unsigned StackAlignment = TFI.getStackAlignment();
1824    uint64_t AlignMask = StackAlignment - 1;
1825    int64_t Offset = StackSize;
1826    unsigned SlotSize = Subtarget->is64Bit() ? 8 : 4;
1827    if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
1828      // Number smaller than 12 so just add the difference.
1829      Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
1830    } else {
1831      // Mask out lower bits, add stackalignment once plus the 12 bytes.
1832      Offset = ((~AlignMask) & Offset) + StackAlignment +
1833        (StackAlignment-SlotSize);
1834    }
1835    StackSize = Offset;
1836  }
1837  return StackSize;
1838}
1839
1840/// IsEligibleForTailCallElimination - Check to see whether the next instruction
1841/// following the call is a return. A function is eligible if caller/callee
1842/// calling conventions match, currently only fastcc supports tail calls, and
1843/// the function CALL is immediatly followed by a RET.
1844bool X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Call,
1845                                                      SDValue Ret,
1846                                                      SelectionDAG& DAG) const {
1847  if (!PerformTailCallOpt)
1848    return false;
1849
1850  if (CheckTailCallReturnConstraints(Call, Ret)) {
1851    MachineFunction &MF = DAG.getMachineFunction();
1852    unsigned CallerCC = MF.getFunction()->getCallingConv();
1853    unsigned CalleeCC = cast<ConstantSDNode>(Call.getOperand(1))->getValue();
1854    if (CalleeCC == CallingConv::Fast && CallerCC == CalleeCC) {
1855      SDValue Callee = Call.getOperand(4);
1856      // On x86/32Bit PIC/GOT  tail calls are supported.
1857      if (getTargetMachine().getRelocationModel() != Reloc::PIC_ ||
1858          !Subtarget->isPICStyleGOT()|| !Subtarget->is64Bit())
1859        return true;
1860
1861      // Can only do local tail calls (in same module, hidden or protected) on
1862      // x86_64 PIC/GOT at the moment.
1863      if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
1864        return G->getGlobal()->hasHiddenVisibility()
1865            || G->getGlobal()->hasProtectedVisibility();
1866    }
1867  }
1868
1869  return false;
1870}
1871
1872//===----------------------------------------------------------------------===//
1873//                           Other Lowering Hooks
1874//===----------------------------------------------------------------------===//
1875
1876
1877SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) {
1878  MachineFunction &MF = DAG.getMachineFunction();
1879  X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1880  int ReturnAddrIndex = FuncInfo->getRAIndex();
1881
1882  if (ReturnAddrIndex == 0) {
1883    // Set up a frame object for the return address.
1884    if (Subtarget->is64Bit())
1885      ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(8, -8);
1886    else
1887      ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(4, -4);
1888
1889    FuncInfo->setRAIndex(ReturnAddrIndex);
1890  }
1891
1892  return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
1893}
1894
1895
1896
1897/// translateX86CC - do a one to one translation of a ISD::CondCode to the X86
1898/// specific condition code. It returns a false if it cannot do a direct
1899/// translation. X86CC is the translated CondCode.  LHS/RHS are modified as
1900/// needed.
1901static bool translateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
1902                           unsigned &X86CC, SDValue &LHS, SDValue &RHS,
1903                           SelectionDAG &DAG) {
1904  X86CC = X86::COND_INVALID;
1905  if (!isFP) {
1906    if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
1907      if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
1908        // X > -1   -> X == 0, jump !sign.
1909        RHS = DAG.getConstant(0, RHS.getValueType());
1910        X86CC = X86::COND_NS;
1911        return true;
1912      } else if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
1913        // X < 0   -> X == 0, jump on sign.
1914        X86CC = X86::COND_S;
1915        return true;
1916      } else if (SetCCOpcode == ISD::SETLT && RHSC->getValue() == 1) {
1917        // X < 1   -> X <= 0
1918        RHS = DAG.getConstant(0, RHS.getValueType());
1919        X86CC = X86::COND_LE;
1920        return true;
1921      }
1922    }
1923
1924    switch (SetCCOpcode) {
1925    default: break;
1926    case ISD::SETEQ:  X86CC = X86::COND_E;  break;
1927    case ISD::SETGT:  X86CC = X86::COND_G;  break;
1928    case ISD::SETGE:  X86CC = X86::COND_GE; break;
1929    case ISD::SETLT:  X86CC = X86::COND_L;  break;
1930    case ISD::SETLE:  X86CC = X86::COND_LE; break;
1931    case ISD::SETNE:  X86CC = X86::COND_NE; break;
1932    case ISD::SETULT: X86CC = X86::COND_B;  break;
1933    case ISD::SETUGT: X86CC = X86::COND_A;  break;
1934    case ISD::SETULE: X86CC = X86::COND_BE; break;
1935    case ISD::SETUGE: X86CC = X86::COND_AE; break;
1936    }
1937  } else {
1938    // On a floating point condition, the flags are set as follows:
1939    // ZF  PF  CF   op
1940    //  0 | 0 | 0 | X > Y
1941    //  0 | 0 | 1 | X < Y
1942    //  1 | 0 | 0 | X == Y
1943    //  1 | 1 | 1 | unordered
1944    bool Flip = false;
1945    switch (SetCCOpcode) {
1946    default: break;
1947    case ISD::SETUEQ:
1948    case ISD::SETEQ: X86CC = X86::COND_E;  break;
1949    case ISD::SETOLT: Flip = true; // Fallthrough
1950    case ISD::SETOGT:
1951    case ISD::SETGT: X86CC = X86::COND_A;  break;
1952    case ISD::SETOLE: Flip = true; // Fallthrough
1953    case ISD::SETOGE:
1954    case ISD::SETGE: X86CC = X86::COND_AE; break;
1955    case ISD::SETUGT: Flip = true; // Fallthrough
1956    case ISD::SETULT:
1957    case ISD::SETLT: X86CC = X86::COND_B;  break;
1958    case ISD::SETUGE: Flip = true; // Fallthrough
1959    case ISD::SETULE:
1960    case ISD::SETLE: X86CC = X86::COND_BE; break;
1961    case ISD::SETONE:
1962    case ISD::SETNE: X86CC = X86::COND_NE; break;
1963    case ISD::SETUO: X86CC = X86::COND_P;  break;
1964    case ISD::SETO:  X86CC = X86::COND_NP; break;
1965    }
1966    if (Flip)
1967      std::swap(LHS, RHS);
1968  }
1969
1970  return X86CC != X86::COND_INVALID;
1971}
1972
1973/// hasFPCMov - is there a floating point cmov for the specific X86 condition
1974/// code. Current x86 isa includes the following FP cmov instructions:
1975/// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
1976static bool hasFPCMov(unsigned X86CC) {
1977  switch (X86CC) {
1978  default:
1979    return false;
1980  case X86::COND_B:
1981  case X86::COND_BE:
1982  case X86::COND_E:
1983  case X86::COND_P:
1984  case X86::COND_A:
1985  case X86::COND_AE:
1986  case X86::COND_NE:
1987  case X86::COND_NP:
1988    return true;
1989  }
1990}
1991
1992/// isUndefOrInRange - Op is either an undef node or a ConstantSDNode.  Return
1993/// true if Op is undef or if its value falls within the specified range (L, H].
1994static bool isUndefOrInRange(SDValue Op, unsigned Low, unsigned Hi) {
1995  if (Op.getOpcode() == ISD::UNDEF)
1996    return true;
1997
1998  unsigned Val = cast<ConstantSDNode>(Op)->getValue();
1999  return (Val >= Low && Val < Hi);
2000}
2001
2002/// isUndefOrEqual - Op is either an undef node or a ConstantSDNode.  Return
2003/// true if Op is undef or if its value equal to the specified value.
2004static bool isUndefOrEqual(SDValue Op, unsigned Val) {
2005  if (Op.getOpcode() == ISD::UNDEF)
2006    return true;
2007  return cast<ConstantSDNode>(Op)->getValue() == Val;
2008}
2009
2010/// isPSHUFDMask - Return true if the specified VECTOR_SHUFFLE operand
2011/// specifies a shuffle of elements that is suitable for input to PSHUFD.
2012bool X86::isPSHUFDMask(SDNode *N) {
2013  assert(N->getOpcode() == ISD::BUILD_VECTOR);
2014
2015  if (N->getNumOperands() != 2 && N->getNumOperands() != 4)
2016    return false;
2017
2018  // Check if the value doesn't reference the second vector.
2019  for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
2020    SDValue Arg = N->getOperand(i);
2021    if (Arg.getOpcode() == ISD::UNDEF) continue;
2022    assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2023    if (cast<ConstantSDNode>(Arg)->getValue() >= e)
2024      return false;
2025  }
2026
2027  return true;
2028}
2029
2030/// isPSHUFHWMask - Return true if the specified VECTOR_SHUFFLE operand
2031/// specifies a shuffle of elements that is suitable for input to PSHUFHW.
2032bool X86::isPSHUFHWMask(SDNode *N) {
2033  assert(N->getOpcode() == ISD::BUILD_VECTOR);
2034
2035  if (N->getNumOperands() != 8)
2036    return false;
2037
2038  // Lower quadword copied in order.
2039  for (unsigned i = 0; i != 4; ++i) {
2040    SDValue Arg = N->getOperand(i);
2041    if (Arg.getOpcode() == ISD::UNDEF) continue;
2042    assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2043    if (cast<ConstantSDNode>(Arg)->getValue() != i)
2044      return false;
2045  }
2046
2047  // Upper quadword shuffled.
2048  for (unsigned i = 4; i != 8; ++i) {
2049    SDValue Arg = N->getOperand(i);
2050    if (Arg.getOpcode() == ISD::UNDEF) continue;
2051    assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2052    unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2053    if (Val < 4 || Val > 7)
2054      return false;
2055  }
2056
2057  return true;
2058}
2059
2060/// isPSHUFLWMask - Return true if the specified VECTOR_SHUFFLE operand
2061/// specifies a shuffle of elements that is suitable for input to PSHUFLW.
2062bool X86::isPSHUFLWMask(SDNode *N) {
2063  assert(N->getOpcode() == ISD::BUILD_VECTOR);
2064
2065  if (N->getNumOperands() != 8)
2066    return false;
2067
2068  // Upper quadword copied in order.
2069  for (unsigned i = 4; i != 8; ++i)
2070    if (!isUndefOrEqual(N->getOperand(i), i))
2071      return false;
2072
2073  // Lower quadword shuffled.
2074  for (unsigned i = 0; i != 4; ++i)
2075    if (!isUndefOrInRange(N->getOperand(i), 0, 4))
2076      return false;
2077
2078  return true;
2079}
2080
2081/// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
2082/// specifies a shuffle of elements that is suitable for input to SHUFP*.
2083static bool isSHUFPMask(SDOperandPtr Elems, unsigned NumElems) {
2084  if (NumElems != 2 && NumElems != 4) return false;
2085
2086  unsigned Half = NumElems / 2;
2087  for (unsigned i = 0; i < Half; ++i)
2088    if (!isUndefOrInRange(Elems[i], 0, NumElems))
2089      return false;
2090  for (unsigned i = Half; i < NumElems; ++i)
2091    if (!isUndefOrInRange(Elems[i], NumElems, NumElems*2))
2092      return false;
2093
2094  return true;
2095}
2096
2097bool X86::isSHUFPMask(SDNode *N) {
2098  assert(N->getOpcode() == ISD::BUILD_VECTOR);
2099  return ::isSHUFPMask(N->op_begin(), N->getNumOperands());
2100}
2101
2102/// isCommutedSHUFP - Returns true if the shuffle mask is exactly
2103/// the reverse of what x86 shuffles want. x86 shuffles requires the lower
2104/// half elements to come from vector 1 (which would equal the dest.) and
2105/// the upper half to come from vector 2.
2106static bool isCommutedSHUFP(SDOperandPtr Ops, unsigned NumOps) {
2107  if (NumOps != 2 && NumOps != 4) return false;
2108
2109  unsigned Half = NumOps / 2;
2110  for (unsigned i = 0; i < Half; ++i)
2111    if (!isUndefOrInRange(Ops[i], NumOps, NumOps*2))
2112      return false;
2113  for (unsigned i = Half; i < NumOps; ++i)
2114    if (!isUndefOrInRange(Ops[i], 0, NumOps))
2115      return false;
2116  return true;
2117}
2118
2119static bool isCommutedSHUFP(SDNode *N) {
2120  assert(N->getOpcode() == ISD::BUILD_VECTOR);
2121  return isCommutedSHUFP(N->op_begin(), N->getNumOperands());
2122}
2123
2124/// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
2125/// specifies a shuffle of elements that is suitable for input to MOVHLPS.
2126bool X86::isMOVHLPSMask(SDNode *N) {
2127  assert(N->getOpcode() == ISD::BUILD_VECTOR);
2128
2129  if (N->getNumOperands() != 4)
2130    return false;
2131
2132  // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
2133  return isUndefOrEqual(N->getOperand(0), 6) &&
2134         isUndefOrEqual(N->getOperand(1), 7) &&
2135         isUndefOrEqual(N->getOperand(2), 2) &&
2136         isUndefOrEqual(N->getOperand(3), 3);
2137}
2138
2139/// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
2140/// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
2141/// <2, 3, 2, 3>
2142bool X86::isMOVHLPS_v_undef_Mask(SDNode *N) {
2143  assert(N->getOpcode() == ISD::BUILD_VECTOR);
2144
2145  if (N->getNumOperands() != 4)
2146    return false;
2147
2148  // Expect bit0 == 2, bit1 == 3, bit2 == 2, bit3 == 3
2149  return isUndefOrEqual(N->getOperand(0), 2) &&
2150         isUndefOrEqual(N->getOperand(1), 3) &&
2151         isUndefOrEqual(N->getOperand(2), 2) &&
2152         isUndefOrEqual(N->getOperand(3), 3);
2153}
2154
2155/// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
2156/// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
2157bool X86::isMOVLPMask(SDNode *N) {
2158  assert(N->getOpcode() == ISD::BUILD_VECTOR);
2159
2160  unsigned NumElems = N->getNumOperands();
2161  if (NumElems != 2 && NumElems != 4)
2162    return false;
2163
2164  for (unsigned i = 0; i < NumElems/2; ++i)
2165    if (!isUndefOrEqual(N->getOperand(i), i + NumElems))
2166      return false;
2167
2168  for (unsigned i = NumElems/2; i < NumElems; ++i)
2169    if (!isUndefOrEqual(N->getOperand(i), i))
2170      return false;
2171
2172  return true;
2173}
2174
2175/// isMOVHPMask - Return true if the specified VECTOR_SHUFFLE operand
2176/// specifies a shuffle of elements that is suitable for input to MOVHP{S|D}
2177/// and MOVLHPS.
2178bool X86::isMOVHPMask(SDNode *N) {
2179  assert(N->getOpcode() == ISD::BUILD_VECTOR);
2180
2181  unsigned NumElems = N->getNumOperands();
2182  if (NumElems != 2 && NumElems != 4)
2183    return false;
2184
2185  for (unsigned i = 0; i < NumElems/2; ++i)
2186    if (!isUndefOrEqual(N->getOperand(i), i))
2187      return false;
2188
2189  for (unsigned i = 0; i < NumElems/2; ++i) {
2190    SDValue Arg = N->getOperand(i + NumElems/2);
2191    if (!isUndefOrEqual(Arg, i + NumElems))
2192      return false;
2193  }
2194
2195  return true;
2196}
2197
2198/// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
2199/// specifies a shuffle of elements that is suitable for input to UNPCKL.
2200bool static isUNPCKLMask(SDOperandPtr Elts, unsigned NumElts,
2201                         bool V2IsSplat = false) {
2202  if (NumElts != 2 && NumElts != 4 && NumElts != 8 && NumElts != 16)
2203    return false;
2204
2205  for (unsigned i = 0, j = 0; i != NumElts; i += 2, ++j) {
2206    SDValue BitI  = Elts[i];
2207    SDValue BitI1 = Elts[i+1];
2208    if (!isUndefOrEqual(BitI, j))
2209      return false;
2210    if (V2IsSplat) {
2211      if (isUndefOrEqual(BitI1, NumElts))
2212        return false;
2213    } else {
2214      if (!isUndefOrEqual(BitI1, j + NumElts))
2215        return false;
2216    }
2217  }
2218
2219  return true;
2220}
2221
2222bool X86::isUNPCKLMask(SDNode *N, bool V2IsSplat) {
2223  assert(N->getOpcode() == ISD::BUILD_VECTOR);
2224  return ::isUNPCKLMask(N->op_begin(), N->getNumOperands(), V2IsSplat);
2225}
2226
2227/// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
2228/// specifies a shuffle of elements that is suitable for input to UNPCKH.
2229bool static isUNPCKHMask(SDOperandPtr Elts, unsigned NumElts,
2230                         bool V2IsSplat = false) {
2231  if (NumElts != 2 && NumElts != 4 && NumElts != 8 && NumElts != 16)
2232    return false;
2233
2234  for (unsigned i = 0, j = 0; i != NumElts; i += 2, ++j) {
2235    SDValue BitI  = Elts[i];
2236    SDValue BitI1 = Elts[i+1];
2237    if (!isUndefOrEqual(BitI, j + NumElts/2))
2238      return false;
2239    if (V2IsSplat) {
2240      if (isUndefOrEqual(BitI1, NumElts))
2241        return false;
2242    } else {
2243      if (!isUndefOrEqual(BitI1, j + NumElts/2 + NumElts))
2244        return false;
2245    }
2246  }
2247
2248  return true;
2249}
2250
2251bool X86::isUNPCKHMask(SDNode *N, bool V2IsSplat) {
2252  assert(N->getOpcode() == ISD::BUILD_VECTOR);
2253  return ::isUNPCKHMask(N->op_begin(), N->getNumOperands(), V2IsSplat);
2254}
2255
2256/// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
2257/// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
2258/// <0, 0, 1, 1>
2259bool X86::isUNPCKL_v_undef_Mask(SDNode *N) {
2260  assert(N->getOpcode() == ISD::BUILD_VECTOR);
2261
2262  unsigned NumElems = N->getNumOperands();
2263  if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
2264    return false;
2265
2266  for (unsigned i = 0, j = 0; i != NumElems; i += 2, ++j) {
2267    SDValue BitI  = N->getOperand(i);
2268    SDValue BitI1 = N->getOperand(i+1);
2269
2270    if (!isUndefOrEqual(BitI, j))
2271      return false;
2272    if (!isUndefOrEqual(BitI1, j))
2273      return false;
2274  }
2275
2276  return true;
2277}
2278
2279/// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
2280/// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
2281/// <2, 2, 3, 3>
2282bool X86::isUNPCKH_v_undef_Mask(SDNode *N) {
2283  assert(N->getOpcode() == ISD::BUILD_VECTOR);
2284
2285  unsigned NumElems = N->getNumOperands();
2286  if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
2287    return false;
2288
2289  for (unsigned i = 0, j = NumElems / 2; i != NumElems; i += 2, ++j) {
2290    SDValue BitI  = N->getOperand(i);
2291    SDValue BitI1 = N->getOperand(i + 1);
2292
2293    if (!isUndefOrEqual(BitI, j))
2294      return false;
2295    if (!isUndefOrEqual(BitI1, j))
2296      return false;
2297  }
2298
2299  return true;
2300}
2301
2302/// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
2303/// specifies a shuffle of elements that is suitable for input to MOVSS,
2304/// MOVSD, and MOVD, i.e. setting the lowest element.
2305static bool isMOVLMask(SDOperandPtr Elts, unsigned NumElts) {
2306  if (NumElts != 2 && NumElts != 4)
2307    return false;
2308
2309  if (!isUndefOrEqual(Elts[0], NumElts))
2310    return false;
2311
2312  for (unsigned i = 1; i < NumElts; ++i) {
2313    if (!isUndefOrEqual(Elts[i], i))
2314      return false;
2315  }
2316
2317  return true;
2318}
2319
2320bool X86::isMOVLMask(SDNode *N) {
2321  assert(N->getOpcode() == ISD::BUILD_VECTOR);
2322  return ::isMOVLMask(N->op_begin(), N->getNumOperands());
2323}
2324
2325/// isCommutedMOVL - Returns true if the shuffle mask is except the reverse
2326/// of what x86 movss want. X86 movs requires the lowest  element to be lowest
2327/// element of vector 2 and the other elements to come from vector 1 in order.
2328static bool isCommutedMOVL(SDOperandPtr Ops, unsigned NumOps,
2329                           bool V2IsSplat = false,
2330                           bool V2IsUndef = false) {
2331  if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
2332    return false;
2333
2334  if (!isUndefOrEqual(Ops[0], 0))
2335    return false;
2336
2337  for (unsigned i = 1; i < NumOps; ++i) {
2338    SDValue Arg = Ops[i];
2339    if (!(isUndefOrEqual(Arg, i+NumOps) ||
2340          (V2IsUndef && isUndefOrInRange(Arg, NumOps, NumOps*2)) ||
2341          (V2IsSplat && isUndefOrEqual(Arg, NumOps))))
2342      return false;
2343  }
2344
2345  return true;
2346}
2347
2348static bool isCommutedMOVL(SDNode *N, bool V2IsSplat = false,
2349                           bool V2IsUndef = false) {
2350  assert(N->getOpcode() == ISD::BUILD_VECTOR);
2351  return isCommutedMOVL(N->op_begin(), N->getNumOperands(),
2352                        V2IsSplat, V2IsUndef);
2353}
2354
2355/// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
2356/// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
2357bool X86::isMOVSHDUPMask(SDNode *N) {
2358  assert(N->getOpcode() == ISD::BUILD_VECTOR);
2359
2360  if (N->getNumOperands() != 4)
2361    return false;
2362
2363  // Expect 1, 1, 3, 3
2364  for (unsigned i = 0; i < 2; ++i) {
2365    SDValue Arg = N->getOperand(i);
2366    if (Arg.getOpcode() == ISD::UNDEF) continue;
2367    assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2368    unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2369    if (Val != 1) return false;
2370  }
2371
2372  bool HasHi = false;
2373  for (unsigned i = 2; i < 4; ++i) {
2374    SDValue Arg = N->getOperand(i);
2375    if (Arg.getOpcode() == ISD::UNDEF) continue;
2376    assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2377    unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2378    if (Val != 3) return false;
2379    HasHi = true;
2380  }
2381
2382  // Don't use movshdup if it can be done with a shufps.
2383  return HasHi;
2384}
2385
2386/// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
2387/// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
2388bool X86::isMOVSLDUPMask(SDNode *N) {
2389  assert(N->getOpcode() == ISD::BUILD_VECTOR);
2390
2391  if (N->getNumOperands() != 4)
2392    return false;
2393
2394  // Expect 0, 0, 2, 2
2395  for (unsigned i = 0; i < 2; ++i) {
2396    SDValue Arg = N->getOperand(i);
2397    if (Arg.getOpcode() == ISD::UNDEF) continue;
2398    assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2399    unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2400    if (Val != 0) return false;
2401  }
2402
2403  bool HasHi = false;
2404  for (unsigned i = 2; i < 4; ++i) {
2405    SDValue Arg = N->getOperand(i);
2406    if (Arg.getOpcode() == ISD::UNDEF) continue;
2407    assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2408    unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2409    if (Val != 2) return false;
2410    HasHi = true;
2411  }
2412
2413  // Don't use movshdup if it can be done with a shufps.
2414  return HasHi;
2415}
2416
2417/// isIdentityMask - Return true if the specified VECTOR_SHUFFLE operand
2418/// specifies a identity operation on the LHS or RHS.
2419static bool isIdentityMask(SDNode *N, bool RHS = false) {
2420  unsigned NumElems = N->getNumOperands();
2421  for (unsigned i = 0; i < NumElems; ++i)
2422    if (!isUndefOrEqual(N->getOperand(i), i + (RHS ? NumElems : 0)))
2423      return false;
2424  return true;
2425}
2426
2427/// isSplatMask - Return true if the specified VECTOR_SHUFFLE operand specifies
2428/// a splat of a single element.
2429static bool isSplatMask(SDNode *N) {
2430  assert(N->getOpcode() == ISD::BUILD_VECTOR);
2431
2432  // This is a splat operation if each element of the permute is the same, and
2433  // if the value doesn't reference the second vector.
2434  unsigned NumElems = N->getNumOperands();
2435  SDValue ElementBase;
2436  unsigned i = 0;
2437  for (; i != NumElems; ++i) {
2438    SDValue Elt = N->getOperand(i);
2439    if (isa<ConstantSDNode>(Elt)) {
2440      ElementBase = Elt;
2441      break;
2442    }
2443  }
2444
2445  if (!ElementBase.Val)
2446    return false;
2447
2448  for (; i != NumElems; ++i) {
2449    SDValue Arg = N->getOperand(i);
2450    if (Arg.getOpcode() == ISD::UNDEF) continue;
2451    assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2452    if (Arg != ElementBase) return false;
2453  }
2454
2455  // Make sure it is a splat of the first vector operand.
2456  return cast<ConstantSDNode>(ElementBase)->getValue() < NumElems;
2457}
2458
2459/// isSplatMask - Return true if the specified VECTOR_SHUFFLE operand specifies
2460/// a splat of a single element and it's a 2 or 4 element mask.
2461bool X86::isSplatMask(SDNode *N) {
2462  assert(N->getOpcode() == ISD::BUILD_VECTOR);
2463
2464  // We can only splat 64-bit, and 32-bit quantities with a single instruction.
2465  if (N->getNumOperands() != 4 && N->getNumOperands() != 2)
2466    return false;
2467  return ::isSplatMask(N);
2468}
2469
2470/// isSplatLoMask - Return true if the specified VECTOR_SHUFFLE operand
2471/// specifies a splat of zero element.
2472bool X86::isSplatLoMask(SDNode *N) {
2473  assert(N->getOpcode() == ISD::BUILD_VECTOR);
2474
2475  for (unsigned i = 0, e = N->getNumOperands(); i < e; ++i)
2476    if (!isUndefOrEqual(N->getOperand(i), 0))
2477      return false;
2478  return true;
2479}
2480
2481/// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
2482/// the specified isShuffleMask VECTOR_SHUFFLE mask with PSHUF* and SHUFP*
2483/// instructions.
2484unsigned X86::getShuffleSHUFImmediate(SDNode *N) {
2485  unsigned NumOperands = N->getNumOperands();
2486  unsigned Shift = (NumOperands == 4) ? 2 : 1;
2487  unsigned Mask = 0;
2488  for (unsigned i = 0; i < NumOperands; ++i) {
2489    unsigned Val = 0;
2490    SDValue Arg = N->getOperand(NumOperands-i-1);
2491    if (Arg.getOpcode() != ISD::UNDEF)
2492      Val = cast<ConstantSDNode>(Arg)->getValue();
2493    if (Val >= NumOperands) Val -= NumOperands;
2494    Mask |= Val;
2495    if (i != NumOperands - 1)
2496      Mask <<= Shift;
2497  }
2498
2499  return Mask;
2500}
2501
2502/// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
2503/// the specified isShuffleMask VECTOR_SHUFFLE mask with PSHUFHW
2504/// instructions.
2505unsigned X86::getShufflePSHUFHWImmediate(SDNode *N) {
2506  unsigned Mask = 0;
2507  // 8 nodes, but we only care about the last 4.
2508  for (unsigned i = 7; i >= 4; --i) {
2509    unsigned Val = 0;
2510    SDValue Arg = N->getOperand(i);
2511    if (Arg.getOpcode() != ISD::UNDEF)
2512      Val = cast<ConstantSDNode>(Arg)->getValue();
2513    Mask |= (Val - 4);
2514    if (i != 4)
2515      Mask <<= 2;
2516  }
2517
2518  return Mask;
2519}
2520
2521/// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
2522/// the specified isShuffleMask VECTOR_SHUFFLE mask with PSHUFLW
2523/// instructions.
2524unsigned X86::getShufflePSHUFLWImmediate(SDNode *N) {
2525  unsigned Mask = 0;
2526  // 8 nodes, but we only care about the first 4.
2527  for (int i = 3; i >= 0; --i) {
2528    unsigned Val = 0;
2529    SDValue Arg = N->getOperand(i);
2530    if (Arg.getOpcode() != ISD::UNDEF)
2531      Val = cast<ConstantSDNode>(Arg)->getValue();
2532    Mask |= Val;
2533    if (i != 0)
2534      Mask <<= 2;
2535  }
2536
2537  return Mask;
2538}
2539
2540/// isPSHUFHW_PSHUFLWMask - true if the specified VECTOR_SHUFFLE operand
2541/// specifies a 8 element shuffle that can be broken into a pair of
2542/// PSHUFHW and PSHUFLW.
2543static bool isPSHUFHW_PSHUFLWMask(SDNode *N) {
2544  assert(N->getOpcode() == ISD::BUILD_VECTOR);
2545
2546  if (N->getNumOperands() != 8)
2547    return false;
2548
2549  // Lower quadword shuffled.
2550  for (unsigned i = 0; i != 4; ++i) {
2551    SDValue Arg = N->getOperand(i);
2552    if (Arg.getOpcode() == ISD::UNDEF) continue;
2553    assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2554    unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2555    if (Val >= 4)
2556      return false;
2557  }
2558
2559  // Upper quadword shuffled.
2560  for (unsigned i = 4; i != 8; ++i) {
2561    SDValue Arg = N->getOperand(i);
2562    if (Arg.getOpcode() == ISD::UNDEF) continue;
2563    assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2564    unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2565    if (Val < 4 || Val > 7)
2566      return false;
2567  }
2568
2569  return true;
2570}
2571
2572/// CommuteVectorShuffle - Swap vector_shuffle operands as well as
2573/// values in ther permute mask.
2574static SDValue CommuteVectorShuffle(SDValue Op, SDValue &V1,
2575                                      SDValue &V2, SDValue &Mask,
2576                                      SelectionDAG &DAG) {
2577  MVT VT = Op.getValueType();
2578  MVT MaskVT = Mask.getValueType();
2579  MVT EltVT = MaskVT.getVectorElementType();
2580  unsigned NumElems = Mask.getNumOperands();
2581  SmallVector<SDValue, 8> MaskVec;
2582
2583  for (unsigned i = 0; i != NumElems; ++i) {
2584    SDValue Arg = Mask.getOperand(i);
2585    if (Arg.getOpcode() == ISD::UNDEF) {
2586      MaskVec.push_back(DAG.getNode(ISD::UNDEF, EltVT));
2587      continue;
2588    }
2589    assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2590    unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2591    if (Val < NumElems)
2592      MaskVec.push_back(DAG.getConstant(Val + NumElems, EltVT));
2593    else
2594      MaskVec.push_back(DAG.getConstant(Val - NumElems, EltVT));
2595  }
2596
2597  std::swap(V1, V2);
2598  Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], NumElems);
2599  return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2, Mask);
2600}
2601
2602/// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
2603/// the two vector operands have swapped position.
2604static
2605SDValue CommuteVectorShuffleMask(SDValue Mask, SelectionDAG &DAG) {
2606  MVT MaskVT = Mask.getValueType();
2607  MVT EltVT = MaskVT.getVectorElementType();
2608  unsigned NumElems = Mask.getNumOperands();
2609  SmallVector<SDValue, 8> MaskVec;
2610  for (unsigned i = 0; i != NumElems; ++i) {
2611    SDValue Arg = Mask.getOperand(i);
2612    if (Arg.getOpcode() == ISD::UNDEF) {
2613      MaskVec.push_back(DAG.getNode(ISD::UNDEF, EltVT));
2614      continue;
2615    }
2616    assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2617    unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2618    if (Val < NumElems)
2619      MaskVec.push_back(DAG.getConstant(Val + NumElems, EltVT));
2620    else
2621      MaskVec.push_back(DAG.getConstant(Val - NumElems, EltVT));
2622  }
2623  return DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], NumElems);
2624}
2625
2626
2627/// ShouldXformToMOVHLPS - Return true if the node should be transformed to
2628/// match movhlps. The lower half elements should come from upper half of
2629/// V1 (and in order), and the upper half elements should come from the upper
2630/// half of V2 (and in order).
2631static bool ShouldXformToMOVHLPS(SDNode *Mask) {
2632  unsigned NumElems = Mask->getNumOperands();
2633  if (NumElems != 4)
2634    return false;
2635  for (unsigned i = 0, e = 2; i != e; ++i)
2636    if (!isUndefOrEqual(Mask->getOperand(i), i+2))
2637      return false;
2638  for (unsigned i = 2; i != 4; ++i)
2639    if (!isUndefOrEqual(Mask->getOperand(i), i+4))
2640      return false;
2641  return true;
2642}
2643
2644/// isScalarLoadToVector - Returns true if the node is a scalar load that
2645/// is promoted to a vector. It also returns the LoadSDNode by reference if
2646/// required.
2647static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = NULL) {
2648  if (N->getOpcode() == ISD::SCALAR_TO_VECTOR) {
2649    N = N->getOperand(0).Val;
2650    if (ISD::isNON_EXTLoad(N)) {
2651      if (LD)
2652        *LD = cast<LoadSDNode>(N);
2653      return true;
2654    }
2655  }
2656  return false;
2657}
2658
2659/// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
2660/// match movlp{s|d}. The lower half elements should come from lower half of
2661/// V1 (and in order), and the upper half elements should come from the upper
2662/// half of V2 (and in order). And since V1 will become the source of the
2663/// MOVLP, it must be either a vector load or a scalar load to vector.
2664static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2, SDNode *Mask) {
2665  if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
2666    return false;
2667  // Is V2 is a vector load, don't do this transformation. We will try to use
2668  // load folding shufps op.
2669  if (ISD::isNON_EXTLoad(V2))
2670    return false;
2671
2672  unsigned NumElems = Mask->getNumOperands();
2673  if (NumElems != 2 && NumElems != 4)
2674    return false;
2675  for (unsigned i = 0, e = NumElems/2; i != e; ++i)
2676    if (!isUndefOrEqual(Mask->getOperand(i), i))
2677      return false;
2678  for (unsigned i = NumElems/2; i != NumElems; ++i)
2679    if (!isUndefOrEqual(Mask->getOperand(i), i+NumElems))
2680      return false;
2681  return true;
2682}
2683
2684/// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
2685/// all the same.
2686static bool isSplatVector(SDNode *N) {
2687  if (N->getOpcode() != ISD::BUILD_VECTOR)
2688    return false;
2689
2690  SDValue SplatValue = N->getOperand(0);
2691  for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
2692    if (N->getOperand(i) != SplatValue)
2693      return false;
2694  return true;
2695}
2696
2697/// isUndefShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
2698/// to an undef.
2699static bool isUndefShuffle(SDNode *N) {
2700  if (N->getOpcode() != ISD::VECTOR_SHUFFLE)
2701    return false;
2702
2703  SDValue V1 = N->getOperand(0);
2704  SDValue V2 = N->getOperand(1);
2705  SDValue Mask = N->getOperand(2);
2706  unsigned NumElems = Mask.getNumOperands();
2707  for (unsigned i = 0; i != NumElems; ++i) {
2708    SDValue Arg = Mask.getOperand(i);
2709    if (Arg.getOpcode() != ISD::UNDEF) {
2710      unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2711      if (Val < NumElems && V1.getOpcode() != ISD::UNDEF)
2712        return false;
2713      else if (Val >= NumElems && V2.getOpcode() != ISD::UNDEF)
2714        return false;
2715    }
2716  }
2717  return true;
2718}
2719
2720/// isZeroNode - Returns true if Elt is a constant zero or a floating point
2721/// constant +0.0.
2722static inline bool isZeroNode(SDValue Elt) {
2723  return ((isa<ConstantSDNode>(Elt) &&
2724           cast<ConstantSDNode>(Elt)->getValue() == 0) ||
2725          (isa<ConstantFPSDNode>(Elt) &&
2726           cast<ConstantFPSDNode>(Elt)->getValueAPF().isPosZero()));
2727}
2728
2729/// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
2730/// to an zero vector.
2731static bool isZeroShuffle(SDNode *N) {
2732  if (N->getOpcode() != ISD::VECTOR_SHUFFLE)
2733    return false;
2734
2735  SDValue V1 = N->getOperand(0);
2736  SDValue V2 = N->getOperand(1);
2737  SDValue Mask = N->getOperand(2);
2738  unsigned NumElems = Mask.getNumOperands();
2739  for (unsigned i = 0; i != NumElems; ++i) {
2740    SDValue Arg = Mask.getOperand(i);
2741    if (Arg.getOpcode() == ISD::UNDEF)
2742      continue;
2743
2744    unsigned Idx = cast<ConstantSDNode>(Arg)->getValue();
2745    if (Idx < NumElems) {
2746      unsigned Opc = V1.Val->getOpcode();
2747      if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.Val))
2748        continue;
2749      if (Opc != ISD::BUILD_VECTOR ||
2750          !isZeroNode(V1.Val->getOperand(Idx)))
2751        return false;
2752    } else if (Idx >= NumElems) {
2753      unsigned Opc = V2.Val->getOpcode();
2754      if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.Val))
2755        continue;
2756      if (Opc != ISD::BUILD_VECTOR ||
2757          !isZeroNode(V2.Val->getOperand(Idx - NumElems)))
2758        return false;
2759    }
2760  }
2761  return true;
2762}
2763
2764/// getZeroVector - Returns a vector of specified type with all zero elements.
2765///
2766static SDValue getZeroVector(MVT VT, bool HasSSE2, SelectionDAG &DAG) {
2767  assert(VT.isVector() && "Expected a vector type");
2768
2769  // Always build zero vectors as <4 x i32> or <2 x i32> bitcasted to their dest
2770  // type.  This ensures they get CSE'd.
2771  SDValue Vec;
2772  if (VT.getSizeInBits() == 64) { // MMX
2773    SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
2774    Vec = DAG.getNode(ISD::BUILD_VECTOR, MVT::v2i32, Cst, Cst);
2775  } else if (HasSSE2) {  // SSE2
2776    SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
2777    Vec = DAG.getNode(ISD::BUILD_VECTOR, MVT::v4i32, Cst, Cst, Cst, Cst);
2778  } else { // SSE1
2779    SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
2780    Vec = DAG.getNode(ISD::BUILD_VECTOR, MVT::v4f32, Cst, Cst, Cst, Cst);
2781  }
2782  return DAG.getNode(ISD::BIT_CONVERT, VT, Vec);
2783}
2784
2785/// getOnesVector - Returns a vector of specified type with all bits set.
2786///
2787static SDValue getOnesVector(MVT VT, SelectionDAG &DAG) {
2788  assert(VT.isVector() && "Expected a vector type");
2789
2790  // Always build ones vectors as <4 x i32> or <2 x i32> bitcasted to their dest
2791  // type.  This ensures they get CSE'd.
2792  SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
2793  SDValue Vec;
2794  if (VT.getSizeInBits() == 64)  // MMX
2795    Vec = DAG.getNode(ISD::BUILD_VECTOR, MVT::v2i32, Cst, Cst);
2796  else                                              // SSE
2797    Vec = DAG.getNode(ISD::BUILD_VECTOR, MVT::v4i32, Cst, Cst, Cst, Cst);
2798  return DAG.getNode(ISD::BIT_CONVERT, VT, Vec);
2799}
2800
2801
2802/// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
2803/// that point to V2 points to its first element.
2804static SDValue NormalizeMask(SDValue Mask, SelectionDAG &DAG) {
2805  assert(Mask.getOpcode() == ISD::BUILD_VECTOR);
2806
2807  bool Changed = false;
2808  SmallVector<SDValue, 8> MaskVec;
2809  unsigned NumElems = Mask.getNumOperands();
2810  for (unsigned i = 0; i != NumElems; ++i) {
2811    SDValue Arg = Mask.getOperand(i);
2812    if (Arg.getOpcode() != ISD::UNDEF) {
2813      unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2814      if (Val > NumElems) {
2815        Arg = DAG.getConstant(NumElems, Arg.getValueType());
2816        Changed = true;
2817      }
2818    }
2819    MaskVec.push_back(Arg);
2820  }
2821
2822  if (Changed)
2823    Mask = DAG.getNode(ISD::BUILD_VECTOR, Mask.getValueType(),
2824                       &MaskVec[0], MaskVec.size());
2825  return Mask;
2826}
2827
2828/// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
2829/// operation of specified width.
2830static SDValue getMOVLMask(unsigned NumElems, SelectionDAG &DAG) {
2831  MVT MaskVT = MVT::getIntVectorWithNumElements(NumElems);
2832  MVT BaseVT = MaskVT.getVectorElementType();
2833
2834  SmallVector<SDValue, 8> MaskVec;
2835  MaskVec.push_back(DAG.getConstant(NumElems, BaseVT));
2836  for (unsigned i = 1; i != NumElems; ++i)
2837    MaskVec.push_back(DAG.getConstant(i, BaseVT));
2838  return DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], MaskVec.size());
2839}
2840
2841/// getUnpacklMask - Returns a vector_shuffle mask for an unpackl operation
2842/// of specified width.
2843static SDValue getUnpacklMask(unsigned NumElems, SelectionDAG &DAG) {
2844  MVT MaskVT = MVT::getIntVectorWithNumElements(NumElems);
2845  MVT BaseVT = MaskVT.getVectorElementType();
2846  SmallVector<SDValue, 8> MaskVec;
2847  for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
2848    MaskVec.push_back(DAG.getConstant(i,            BaseVT));
2849    MaskVec.push_back(DAG.getConstant(i + NumElems, BaseVT));
2850  }
2851  return DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], MaskVec.size());
2852}
2853
2854/// getUnpackhMask - Returns a vector_shuffle mask for an unpackh operation
2855/// of specified width.
2856static SDValue getUnpackhMask(unsigned NumElems, SelectionDAG &DAG) {
2857  MVT MaskVT = MVT::getIntVectorWithNumElements(NumElems);
2858  MVT BaseVT = MaskVT.getVectorElementType();
2859  unsigned Half = NumElems/2;
2860  SmallVector<SDValue, 8> MaskVec;
2861  for (unsigned i = 0; i != Half; ++i) {
2862    MaskVec.push_back(DAG.getConstant(i + Half,            BaseVT));
2863    MaskVec.push_back(DAG.getConstant(i + NumElems + Half, BaseVT));
2864  }
2865  return DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], MaskVec.size());
2866}
2867
2868/// getSwapEltZeroMask - Returns a vector_shuffle mask for a shuffle that swaps
2869/// element #0 of a vector with the specified index, leaving the rest of the
2870/// elements in place.
2871static SDValue getSwapEltZeroMask(unsigned NumElems, unsigned DestElt,
2872                                   SelectionDAG &DAG) {
2873  MVT MaskVT = MVT::getIntVectorWithNumElements(NumElems);
2874  MVT BaseVT = MaskVT.getVectorElementType();
2875  SmallVector<SDValue, 8> MaskVec;
2876  // Element #0 of the result gets the elt we are replacing.
2877  MaskVec.push_back(DAG.getConstant(DestElt, BaseVT));
2878  for (unsigned i = 1; i != NumElems; ++i)
2879    MaskVec.push_back(DAG.getConstant(i == DestElt ? 0 : i, BaseVT));
2880  return DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], MaskVec.size());
2881}
2882
2883/// PromoteSplat - Promote a splat of v4f32, v8i16 or v16i8 to v4i32.
2884static SDValue PromoteSplat(SDValue Op, SelectionDAG &DAG, bool HasSSE2) {
2885  MVT PVT = HasSSE2 ? MVT::v4i32 : MVT::v4f32;
2886  MVT VT = Op.getValueType();
2887  if (PVT == VT)
2888    return Op;
2889  SDValue V1 = Op.getOperand(0);
2890  SDValue Mask = Op.getOperand(2);
2891  unsigned NumElems = Mask.getNumOperands();
2892  // Special handling of v4f32 -> v4i32.
2893  if (VT != MVT::v4f32) {
2894    Mask = getUnpacklMask(NumElems, DAG);
2895    while (NumElems > 4) {
2896      V1 = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V1, Mask);
2897      NumElems >>= 1;
2898    }
2899    Mask = getZeroVector(MVT::v4i32, true, DAG);
2900  }
2901
2902  V1 = DAG.getNode(ISD::BIT_CONVERT, PVT, V1);
2903  SDValue Shuffle = DAG.getNode(ISD::VECTOR_SHUFFLE, PVT, V1,
2904                                  DAG.getNode(ISD::UNDEF, PVT), Mask);
2905  return DAG.getNode(ISD::BIT_CONVERT, VT, Shuffle);
2906}
2907
2908/// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
2909/// vector of zero or undef vector.  This produces a shuffle where the low
2910/// element of V2 is swizzled into the zero/undef vector, landing at element
2911/// Idx.  This produces a shuffle mask like 4,1,2,3 (idx=0) or  0,1,2,4 (idx=3).
2912static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
2913                                             bool isZero, bool HasSSE2,
2914                                             SelectionDAG &DAG) {
2915  MVT VT = V2.getValueType();
2916  SDValue V1 = isZero
2917    ? getZeroVector(VT, HasSSE2, DAG) : DAG.getNode(ISD::UNDEF, VT);
2918  unsigned NumElems = V2.getValueType().getVectorNumElements();
2919  MVT MaskVT = MVT::getIntVectorWithNumElements(NumElems);
2920  MVT EVT = MaskVT.getVectorElementType();
2921  SmallVector<SDValue, 16> MaskVec;
2922  for (unsigned i = 0; i != NumElems; ++i)
2923    if (i == Idx)  // If this is the insertion idx, put the low elt of V2 here.
2924      MaskVec.push_back(DAG.getConstant(NumElems, EVT));
2925    else
2926      MaskVec.push_back(DAG.getConstant(i, EVT));
2927  SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
2928                               &MaskVec[0], MaskVec.size());
2929  return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2, Mask);
2930}
2931
2932/// getNumOfConsecutiveZeros - Return the number of elements in a result of
2933/// a shuffle that is zero.
2934static
2935unsigned getNumOfConsecutiveZeros(SDValue Op, SDValue Mask,
2936                                  unsigned NumElems, bool Low,
2937                                  SelectionDAG &DAG) {
2938  unsigned NumZeros = 0;
2939  for (unsigned i = 0; i < NumElems; ++i) {
2940    unsigned Index = Low ? i : NumElems-i-1;
2941    SDValue Idx = Mask.getOperand(Index);
2942    if (Idx.getOpcode() == ISD::UNDEF) {
2943      ++NumZeros;
2944      continue;
2945    }
2946    SDValue Elt = DAG.getShuffleScalarElt(Op.Val, Index);
2947    if (Elt.Val && isZeroNode(Elt))
2948      ++NumZeros;
2949    else
2950      break;
2951  }
2952  return NumZeros;
2953}
2954
2955/// isVectorShift - Returns true if the shuffle can be implemented as a
2956/// logical left or right shift of a vector.
2957static bool isVectorShift(SDValue Op, SDValue Mask, SelectionDAG &DAG,
2958                          bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
2959  unsigned NumElems = Mask.getNumOperands();
2960
2961  isLeft = true;
2962  unsigned NumZeros= getNumOfConsecutiveZeros(Op, Mask, NumElems, true, DAG);
2963  if (!NumZeros) {
2964    isLeft = false;
2965    NumZeros = getNumOfConsecutiveZeros(Op, Mask, NumElems, false, DAG);
2966    if (!NumZeros)
2967      return false;
2968  }
2969
2970  bool SeenV1 = false;
2971  bool SeenV2 = false;
2972  for (unsigned i = NumZeros; i < NumElems; ++i) {
2973    unsigned Val = isLeft ? (i - NumZeros) : i;
2974    SDValue Idx = Mask.getOperand(isLeft ? i : (i - NumZeros));
2975    if (Idx.getOpcode() == ISD::UNDEF)
2976      continue;
2977    unsigned Index = cast<ConstantSDNode>(Idx)->getValue();
2978    if (Index < NumElems)
2979      SeenV1 = true;
2980    else {
2981      Index -= NumElems;
2982      SeenV2 = true;
2983    }
2984    if (Index != Val)
2985      return false;
2986  }
2987  if (SeenV1 && SeenV2)
2988    return false;
2989
2990  ShVal = SeenV1 ? Op.getOperand(0) : Op.getOperand(1);
2991  ShAmt = NumZeros;
2992  return true;
2993}
2994
2995
2996/// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
2997///
2998static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
2999                                       unsigned NumNonZero, unsigned NumZero,
3000                                       SelectionDAG &DAG, TargetLowering &TLI) {
3001  if (NumNonZero > 8)
3002    return SDValue();
3003
3004  SDValue V(0, 0);
3005  bool First = true;
3006  for (unsigned i = 0; i < 16; ++i) {
3007    bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
3008    if (ThisIsNonZero && First) {
3009      if (NumZero)
3010        V = getZeroVector(MVT::v8i16, true, DAG);
3011      else
3012        V = DAG.getNode(ISD::UNDEF, MVT::v8i16);
3013      First = false;
3014    }
3015
3016    if ((i & 1) != 0) {
3017      SDValue ThisElt(0, 0), LastElt(0, 0);
3018      bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
3019      if (LastIsNonZero) {
3020        LastElt = DAG.getNode(ISD::ZERO_EXTEND, MVT::i16, Op.getOperand(i-1));
3021      }
3022      if (ThisIsNonZero) {
3023        ThisElt = DAG.getNode(ISD::ZERO_EXTEND, MVT::i16, Op.getOperand(i));
3024        ThisElt = DAG.getNode(ISD::SHL, MVT::i16,
3025                              ThisElt, DAG.getConstant(8, MVT::i8));
3026        if (LastIsNonZero)
3027          ThisElt = DAG.getNode(ISD::OR, MVT::i16, ThisElt, LastElt);
3028      } else
3029        ThisElt = LastElt;
3030
3031      if (ThisElt.Val)
3032        V = DAG.getNode(ISD::INSERT_VECTOR_ELT, MVT::v8i16, V, ThisElt,
3033                        DAG.getIntPtrConstant(i/2));
3034    }
3035  }
3036
3037  return DAG.getNode(ISD::BIT_CONVERT, MVT::v16i8, V);
3038}
3039
3040/// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
3041///
3042static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
3043                                       unsigned NumNonZero, unsigned NumZero,
3044                                       SelectionDAG &DAG, TargetLowering &TLI) {
3045  if (NumNonZero > 4)
3046    return SDValue();
3047
3048  SDValue V(0, 0);
3049  bool First = true;
3050  for (unsigned i = 0; i < 8; ++i) {
3051    bool isNonZero = (NonZeros & (1 << i)) != 0;
3052    if (isNonZero) {
3053      if (First) {
3054        if (NumZero)
3055          V = getZeroVector(MVT::v8i16, true, DAG);
3056        else
3057          V = DAG.getNode(ISD::UNDEF, MVT::v8i16);
3058        First = false;
3059      }
3060      V = DAG.getNode(ISD::INSERT_VECTOR_ELT, MVT::v8i16, V, Op.getOperand(i),
3061                      DAG.getIntPtrConstant(i));
3062    }
3063  }
3064
3065  return V;
3066}
3067
3068/// getVShift - Return a vector logical shift node.
3069///
3070static SDValue getVShift(bool isLeft, MVT VT, SDValue SrcOp,
3071                           unsigned NumBits, SelectionDAG &DAG,
3072                           const TargetLowering &TLI) {
3073  bool isMMX = VT.getSizeInBits() == 64;
3074  MVT ShVT = isMMX ? MVT::v1i64 : MVT::v2i64;
3075  unsigned Opc = isLeft ? X86ISD::VSHL : X86ISD::VSRL;
3076  SrcOp = DAG.getNode(ISD::BIT_CONVERT, ShVT, SrcOp);
3077  return DAG.getNode(ISD::BIT_CONVERT, VT,
3078                     DAG.getNode(Opc, ShVT, SrcOp,
3079                              DAG.getConstant(NumBits, TLI.getShiftAmountTy())));
3080}
3081
3082SDValue
3083X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) {
3084  // All zero's are handled with pxor, all one's are handled with pcmpeqd.
3085  if (ISD::isBuildVectorAllZeros(Op.Val) || ISD::isBuildVectorAllOnes(Op.Val)) {
3086    // Canonicalize this to either <4 x i32> or <2 x i32> (SSE vs MMX) to
3087    // 1) ensure the zero vectors are CSE'd, and 2) ensure that i64 scalars are
3088    // eliminated on x86-32 hosts.
3089    if (Op.getValueType() == MVT::v4i32 || Op.getValueType() == MVT::v2i32)
3090      return Op;
3091
3092    if (ISD::isBuildVectorAllOnes(Op.Val))
3093      return getOnesVector(Op.getValueType(), DAG);
3094    return getZeroVector(Op.getValueType(), Subtarget->hasSSE2(), DAG);
3095  }
3096
3097  MVT VT = Op.getValueType();
3098  MVT EVT = VT.getVectorElementType();
3099  unsigned EVTBits = EVT.getSizeInBits();
3100
3101  unsigned NumElems = Op.getNumOperands();
3102  unsigned NumZero  = 0;
3103  unsigned NumNonZero = 0;
3104  unsigned NonZeros = 0;
3105  bool IsAllConstants = true;
3106  SmallSet<SDValue, 8> Values;
3107  for (unsigned i = 0; i < NumElems; ++i) {
3108    SDValue Elt = Op.getOperand(i);
3109    if (Elt.getOpcode() == ISD::UNDEF)
3110      continue;
3111    Values.insert(Elt);
3112    if (Elt.getOpcode() != ISD::Constant &&
3113        Elt.getOpcode() != ISD::ConstantFP)
3114      IsAllConstants = false;
3115    if (isZeroNode(Elt))
3116      NumZero++;
3117    else {
3118      NonZeros |= (1 << i);
3119      NumNonZero++;
3120    }
3121  }
3122
3123  if (NumNonZero == 0) {
3124    // All undef vector. Return an UNDEF.  All zero vectors were handled above.
3125    return DAG.getNode(ISD::UNDEF, VT);
3126  }
3127
3128  // Special case for single non-zero, non-undef, element.
3129  if (NumNonZero == 1 && NumElems <= 4) {
3130    unsigned Idx = CountTrailingZeros_32(NonZeros);
3131    SDValue Item = Op.getOperand(Idx);
3132
3133    // If this is an insertion of an i64 value on x86-32, and if the top bits of
3134    // the value are obviously zero, truncate the value to i32 and do the
3135    // insertion that way.  Only do this if the value is non-constant or if the
3136    // value is a constant being inserted into element 0.  It is cheaper to do
3137    // a constant pool load than it is to do a movd + shuffle.
3138    if (EVT == MVT::i64 && !Subtarget->is64Bit() &&
3139        (!IsAllConstants || Idx == 0)) {
3140      if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
3141        // Handle MMX and SSE both.
3142        MVT VecVT = VT == MVT::v2i64 ? MVT::v4i32 : MVT::v2i32;
3143        unsigned VecElts = VT == MVT::v2i64 ? 4 : 2;
3144
3145        // Truncate the value (which may itself be a constant) to i32, and
3146        // convert it to a vector with movd (S2V+shuffle to zero extend).
3147        Item = DAG.getNode(ISD::TRUNCATE, MVT::i32, Item);
3148        Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, VecVT, Item);
3149        Item = getShuffleVectorZeroOrUndef(Item, 0, true,
3150                                           Subtarget->hasSSE2(), DAG);
3151
3152        // Now we have our 32-bit value zero extended in the low element of
3153        // a vector.  If Idx != 0, swizzle it into place.
3154        if (Idx != 0) {
3155          SDValue Ops[] = {
3156            Item, DAG.getNode(ISD::UNDEF, Item.getValueType()),
3157            getSwapEltZeroMask(VecElts, Idx, DAG)
3158          };
3159          Item = DAG.getNode(ISD::VECTOR_SHUFFLE, VecVT, Ops, 3);
3160        }
3161        return DAG.getNode(ISD::BIT_CONVERT, Op.getValueType(), Item);
3162      }
3163    }
3164
3165    // If we have a constant or non-constant insertion into the low element of
3166    // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
3167    // the rest of the elements.  This will be matched as movd/movq/movss/movsd
3168    // depending on what the source datatype is.  Because we can only get here
3169    // when NumElems <= 4, this only needs to handle i32/f32/i64/f64.
3170    if (Idx == 0 &&
3171        // Don't do this for i64 values on x86-32.
3172        (EVT != MVT::i64 || Subtarget->is64Bit())) {
3173      Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, VT, Item);
3174      // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
3175      return getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0,
3176                                         Subtarget->hasSSE2(), DAG);
3177    }
3178
3179    // Is it a vector logical left shift?
3180    if (NumElems == 2 && Idx == 1 &&
3181        isZeroNode(Op.getOperand(0)) && !isZeroNode(Op.getOperand(1))) {
3182      unsigned NumBits = VT.getSizeInBits();
3183      return getVShift(true, VT,
3184                       DAG.getNode(ISD::SCALAR_TO_VECTOR, VT, Op.getOperand(1)),
3185                       NumBits/2, DAG, *this);
3186    }
3187
3188    if (IsAllConstants) // Otherwise, it's better to do a constpool load.
3189      return SDValue();
3190
3191    // Otherwise, if this is a vector with i32 or f32 elements, and the element
3192    // is a non-constant being inserted into an element other than the low one,
3193    // we can't use a constant pool load.  Instead, use SCALAR_TO_VECTOR (aka
3194    // movd/movss) to move this into the low element, then shuffle it into
3195    // place.
3196    if (EVTBits == 32) {
3197      Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, VT, Item);
3198
3199      // Turn it into a shuffle of zero and zero-extended scalar to vector.
3200      Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0,
3201                                         Subtarget->hasSSE2(), DAG);
3202      MVT MaskVT  = MVT::getIntVectorWithNumElements(NumElems);
3203      MVT MaskEVT = MaskVT.getVectorElementType();
3204      SmallVector<SDValue, 8> MaskVec;
3205      for (unsigned i = 0; i < NumElems; i++)
3206        MaskVec.push_back(DAG.getConstant((i == Idx) ? 0 : 1, MaskEVT));
3207      SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3208                                   &MaskVec[0], MaskVec.size());
3209      return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, Item,
3210                         DAG.getNode(ISD::UNDEF, VT), Mask);
3211    }
3212  }
3213
3214  // Splat is obviously ok. Let legalizer expand it to a shuffle.
3215  if (Values.size() == 1)
3216    return SDValue();
3217
3218  // A vector full of immediates; various special cases are already
3219  // handled, so this is best done with a single constant-pool load.
3220  if (IsAllConstants)
3221    return SDValue();
3222
3223  // Let legalizer expand 2-wide build_vectors.
3224  if (EVTBits == 64) {
3225    if (NumNonZero == 1) {
3226      // One half is zero or undef.
3227      unsigned Idx = CountTrailingZeros_32(NonZeros);
3228      SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, VT,
3229                                 Op.getOperand(Idx));
3230      return getShuffleVectorZeroOrUndef(V2, Idx, true,
3231                                         Subtarget->hasSSE2(), DAG);
3232    }
3233    return SDValue();
3234  }
3235
3236  // If element VT is < 32 bits, convert it to inserts into a zero vector.
3237  if (EVTBits == 8 && NumElems == 16) {
3238    SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
3239                                        *this);
3240    if (V.Val) return V;
3241  }
3242
3243  if (EVTBits == 16 && NumElems == 8) {
3244    SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
3245                                        *this);
3246    if (V.Val) return V;
3247  }
3248
3249  // If element VT is == 32 bits, turn it into a number of shuffles.
3250  SmallVector<SDValue, 8> V;
3251  V.resize(NumElems);
3252  if (NumElems == 4 && NumZero > 0) {
3253    for (unsigned i = 0; i < 4; ++i) {
3254      bool isZero = !(NonZeros & (1 << i));
3255      if (isZero)
3256        V[i] = getZeroVector(VT, Subtarget->hasSSE2(), DAG);
3257      else
3258        V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, VT, Op.getOperand(i));
3259    }
3260
3261    for (unsigned i = 0; i < 2; ++i) {
3262      switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
3263        default: break;
3264        case 0:
3265          V[i] = V[i*2];  // Must be a zero vector.
3266          break;
3267        case 1:
3268          V[i] = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V[i*2+1], V[i*2],
3269                             getMOVLMask(NumElems, DAG));
3270          break;
3271        case 2:
3272          V[i] = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V[i*2], V[i*2+1],
3273                             getMOVLMask(NumElems, DAG));
3274          break;
3275        case 3:
3276          V[i] = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V[i*2], V[i*2+1],
3277                             getUnpacklMask(NumElems, DAG));
3278          break;
3279      }
3280    }
3281
3282    MVT MaskVT = MVT::getIntVectorWithNumElements(NumElems);
3283    MVT EVT = MaskVT.getVectorElementType();
3284    SmallVector<SDValue, 8> MaskVec;
3285    bool Reverse = (NonZeros & 0x3) == 2;
3286    for (unsigned i = 0; i < 2; ++i)
3287      if (Reverse)
3288        MaskVec.push_back(DAG.getConstant(1-i, EVT));
3289      else
3290        MaskVec.push_back(DAG.getConstant(i, EVT));
3291    Reverse = ((NonZeros & (0x3 << 2)) >> 2) == 2;
3292    for (unsigned i = 0; i < 2; ++i)
3293      if (Reverse)
3294        MaskVec.push_back(DAG.getConstant(1-i+NumElems, EVT));
3295      else
3296        MaskVec.push_back(DAG.getConstant(i+NumElems, EVT));
3297    SDValue ShufMask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3298                                     &MaskVec[0], MaskVec.size());
3299    return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V[0], V[1], ShufMask);
3300  }
3301
3302  if (Values.size() > 2) {
3303    // Expand into a number of unpckl*.
3304    // e.g. for v4f32
3305    //   Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
3306    //         : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
3307    //   Step 2: unpcklps X, Y ==>    <3, 2, 1, 0>
3308    SDValue UnpckMask = getUnpacklMask(NumElems, DAG);
3309    for (unsigned i = 0; i < NumElems; ++i)
3310      V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, VT, Op.getOperand(i));
3311    NumElems >>= 1;
3312    while (NumElems != 0) {
3313      for (unsigned i = 0; i < NumElems; ++i)
3314        V[i] = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V[i], V[i + NumElems],
3315                           UnpckMask);
3316      NumElems >>= 1;
3317    }
3318    return V[0];
3319  }
3320
3321  return SDValue();
3322}
3323
3324static
3325SDValue LowerVECTOR_SHUFFLEv8i16(SDValue V1, SDValue V2,
3326                                   SDValue PermMask, SelectionDAG &DAG,
3327                                   TargetLowering &TLI) {
3328  SDValue NewV;
3329  MVT MaskVT = MVT::getIntVectorWithNumElements(8);
3330  MVT MaskEVT = MaskVT.getVectorElementType();
3331  MVT PtrVT = TLI.getPointerTy();
3332  SmallVector<SDValue, 8> MaskElts(PermMask.Val->op_begin(),
3333                                     PermMask.Val->op_end());
3334
3335  // First record which half of which vector the low elements come from.
3336  SmallVector<unsigned, 4> LowQuad(4);
3337  for (unsigned i = 0; i < 4; ++i) {
3338    SDValue Elt = MaskElts[i];
3339    if (Elt.getOpcode() == ISD::UNDEF)
3340      continue;
3341    unsigned EltIdx = cast<ConstantSDNode>(Elt)->getValue();
3342    int QuadIdx = EltIdx / 4;
3343    ++LowQuad[QuadIdx];
3344  }
3345  int BestLowQuad = -1;
3346  unsigned MaxQuad = 1;
3347  for (unsigned i = 0; i < 4; ++i) {
3348    if (LowQuad[i] > MaxQuad) {
3349      BestLowQuad = i;
3350      MaxQuad = LowQuad[i];
3351    }
3352  }
3353
3354  // Record which half of which vector the high elements come from.
3355  SmallVector<unsigned, 4> HighQuad(4);
3356  for (unsigned i = 4; i < 8; ++i) {
3357    SDValue Elt = MaskElts[i];
3358    if (Elt.getOpcode() == ISD::UNDEF)
3359      continue;
3360    unsigned EltIdx = cast<ConstantSDNode>(Elt)->getValue();
3361    int QuadIdx = EltIdx / 4;
3362    ++HighQuad[QuadIdx];
3363  }
3364  int BestHighQuad = -1;
3365  MaxQuad = 1;
3366  for (unsigned i = 0; i < 4; ++i) {
3367    if (HighQuad[i] > MaxQuad) {
3368      BestHighQuad = i;
3369      MaxQuad = HighQuad[i];
3370    }
3371  }
3372
3373  // If it's possible to sort parts of either half with PSHUF{H|L}W, then do it.
3374  if (BestLowQuad != -1 || BestHighQuad != -1) {
3375    // First sort the 4 chunks in order using shufpd.
3376    SmallVector<SDValue, 8> MaskVec;
3377    if (BestLowQuad != -1)
3378      MaskVec.push_back(DAG.getConstant(BestLowQuad, MVT::i32));
3379    else
3380      MaskVec.push_back(DAG.getConstant(0, MVT::i32));
3381    if (BestHighQuad != -1)
3382      MaskVec.push_back(DAG.getConstant(BestHighQuad, MVT::i32));
3383    else
3384      MaskVec.push_back(DAG.getConstant(1, MVT::i32));
3385    SDValue Mask= DAG.getNode(ISD::BUILD_VECTOR, MVT::v2i32, &MaskVec[0],2);
3386    NewV = DAG.getNode(ISD::VECTOR_SHUFFLE, MVT::v2i64,
3387                       DAG.getNode(ISD::BIT_CONVERT, MVT::v2i64, V1),
3388                       DAG.getNode(ISD::BIT_CONVERT, MVT::v2i64, V2), Mask);
3389    NewV = DAG.getNode(ISD::BIT_CONVERT, MVT::v8i16, NewV);
3390
3391    // Now sort high and low parts separately.
3392    BitVector InOrder(8);
3393    if (BestLowQuad != -1) {
3394      // Sort lower half in order using PSHUFLW.
3395      MaskVec.clear();
3396      bool AnyOutOrder = false;
3397      for (unsigned i = 0; i != 4; ++i) {
3398        SDValue Elt = MaskElts[i];
3399        if (Elt.getOpcode() == ISD::UNDEF) {
3400          MaskVec.push_back(Elt);
3401          InOrder.set(i);
3402        } else {
3403          unsigned EltIdx = cast<ConstantSDNode>(Elt)->getValue();
3404          if (EltIdx != i)
3405            AnyOutOrder = true;
3406          MaskVec.push_back(DAG.getConstant(EltIdx % 4, MaskEVT));
3407          // If this element is in the right place after this shuffle, then
3408          // remember it.
3409          if ((int)(EltIdx / 4) == BestLowQuad)
3410            InOrder.set(i);
3411        }
3412      }
3413      if (AnyOutOrder) {
3414        for (unsigned i = 4; i != 8; ++i)
3415          MaskVec.push_back(DAG.getConstant(i, MaskEVT));
3416        SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], 8);
3417        NewV = DAG.getNode(ISD::VECTOR_SHUFFLE, MVT::v8i16, NewV, NewV, Mask);
3418      }
3419    }
3420
3421    if (BestHighQuad != -1) {
3422      // Sort high half in order using PSHUFHW if possible.
3423      MaskVec.clear();
3424      for (unsigned i = 0; i != 4; ++i)
3425        MaskVec.push_back(DAG.getConstant(i, MaskEVT));
3426      bool AnyOutOrder = false;
3427      for (unsigned i = 4; i != 8; ++i) {
3428        SDValue Elt = MaskElts[i];
3429        if (Elt.getOpcode() == ISD::UNDEF) {
3430          MaskVec.push_back(Elt);
3431          InOrder.set(i);
3432        } else {
3433          unsigned EltIdx = cast<ConstantSDNode>(Elt)->getValue();
3434          if (EltIdx != i)
3435            AnyOutOrder = true;
3436          MaskVec.push_back(DAG.getConstant((EltIdx % 4) + 4, MaskEVT));
3437          // If this element is in the right place after this shuffle, then
3438          // remember it.
3439          if ((int)(EltIdx / 4) == BestHighQuad)
3440            InOrder.set(i);
3441        }
3442      }
3443      if (AnyOutOrder) {
3444        SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], 8);
3445        NewV = DAG.getNode(ISD::VECTOR_SHUFFLE, MVT::v8i16, NewV, NewV, Mask);
3446      }
3447    }
3448
3449    // The other elements are put in the right place using pextrw and pinsrw.
3450    for (unsigned i = 0; i != 8; ++i) {
3451      if (InOrder[i])
3452        continue;
3453      SDValue Elt = MaskElts[i];
3454      unsigned EltIdx = cast<ConstantSDNode>(Elt)->getValue();
3455      SDValue ExtOp = (EltIdx < 8)
3456        ? DAG.getNode(ISD::EXTRACT_VECTOR_ELT, MVT::i16, V1,
3457                      DAG.getConstant(EltIdx, PtrVT))
3458        : DAG.getNode(ISD::EXTRACT_VECTOR_ELT, MVT::i16, V2,
3459                      DAG.getConstant(EltIdx - 8, PtrVT));
3460      NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, MVT::v8i16, NewV, ExtOp,
3461                         DAG.getConstant(i, PtrVT));
3462    }
3463    return NewV;
3464  }
3465
3466  // PSHUF{H|L}W are not used. Lower into extracts and inserts but try to use
3467  ///as few as possible.
3468  // First, let's find out how many elements are already in the right order.
3469  unsigned V1InOrder = 0;
3470  unsigned V1FromV1 = 0;
3471  unsigned V2InOrder = 0;
3472  unsigned V2FromV2 = 0;
3473  SmallVector<SDValue, 8> V1Elts;
3474  SmallVector<SDValue, 8> V2Elts;
3475  for (unsigned i = 0; i < 8; ++i) {
3476    SDValue Elt = MaskElts[i];
3477    if (Elt.getOpcode() == ISD::UNDEF) {
3478      V1Elts.push_back(Elt);
3479      V2Elts.push_back(Elt);
3480      ++V1InOrder;
3481      ++V2InOrder;
3482      continue;
3483    }
3484    unsigned EltIdx = cast<ConstantSDNode>(Elt)->getValue();
3485    if (EltIdx == i) {
3486      V1Elts.push_back(Elt);
3487      V2Elts.push_back(DAG.getConstant(i+8, MaskEVT));
3488      ++V1InOrder;
3489    } else if (EltIdx == i+8) {
3490      V1Elts.push_back(Elt);
3491      V2Elts.push_back(DAG.getConstant(i, MaskEVT));
3492      ++V2InOrder;
3493    } else if (EltIdx < 8) {
3494      V1Elts.push_back(Elt);
3495      ++V1FromV1;
3496    } else {
3497      V2Elts.push_back(DAG.getConstant(EltIdx-8, MaskEVT));
3498      ++V2FromV2;
3499    }
3500  }
3501
3502  if (V2InOrder > V1InOrder) {
3503    PermMask = CommuteVectorShuffleMask(PermMask, DAG);
3504    std::swap(V1, V2);
3505    std::swap(V1Elts, V2Elts);
3506    std::swap(V1FromV1, V2FromV2);
3507  }
3508
3509  if ((V1FromV1 + V1InOrder) != 8) {
3510    // Some elements are from V2.
3511    if (V1FromV1) {
3512      // If there are elements that are from V1 but out of place,
3513      // then first sort them in place
3514      SmallVector<SDValue, 8> MaskVec;
3515      for (unsigned i = 0; i < 8; ++i) {
3516        SDValue Elt = V1Elts[i];
3517        if (Elt.getOpcode() == ISD::UNDEF) {
3518          MaskVec.push_back(DAG.getNode(ISD::UNDEF, MaskEVT));
3519          continue;
3520        }
3521        unsigned EltIdx = cast<ConstantSDNode>(Elt)->getValue();
3522        if (EltIdx >= 8)
3523          MaskVec.push_back(DAG.getNode(ISD::UNDEF, MaskEVT));
3524        else
3525          MaskVec.push_back(DAG.getConstant(EltIdx, MaskEVT));
3526      }
3527      SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], 8);
3528      V1 = DAG.getNode(ISD::VECTOR_SHUFFLE, MVT::v8i16, V1, V1, Mask);
3529    }
3530
3531    NewV = V1;
3532    for (unsigned i = 0; i < 8; ++i) {
3533      SDValue Elt = V1Elts[i];
3534      if (Elt.getOpcode() == ISD::UNDEF)
3535        continue;
3536      unsigned EltIdx = cast<ConstantSDNode>(Elt)->getValue();
3537      if (EltIdx < 8)
3538        continue;
3539      SDValue ExtOp = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, MVT::i16, V2,
3540                                    DAG.getConstant(EltIdx - 8, PtrVT));
3541      NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, MVT::v8i16, NewV, ExtOp,
3542                         DAG.getConstant(i, PtrVT));
3543    }
3544    return NewV;
3545  } else {
3546    // All elements are from V1.
3547    NewV = V1;
3548    for (unsigned i = 0; i < 8; ++i) {
3549      SDValue Elt = V1Elts[i];
3550      if (Elt.getOpcode() == ISD::UNDEF)
3551        continue;
3552      unsigned EltIdx = cast<ConstantSDNode>(Elt)->getValue();
3553      SDValue ExtOp = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, MVT::i16, V1,
3554                                    DAG.getConstant(EltIdx, PtrVT));
3555      NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, MVT::v8i16, NewV, ExtOp,
3556                         DAG.getConstant(i, PtrVT));
3557    }
3558    return NewV;
3559  }
3560}
3561
3562/// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
3563/// ones, or rewriting v4i32 / v2f32 as 2 wide ones if possible. This can be
3564/// done when every pair / quad of shuffle mask elements point to elements in
3565/// the right sequence. e.g.
3566/// vector_shuffle <>, <>, < 3, 4, | 10, 11, | 0, 1, | 14, 15>
3567static
3568SDValue RewriteAsNarrowerShuffle(SDValue V1, SDValue V2,
3569                                MVT VT,
3570                                SDValue PermMask, SelectionDAG &DAG,
3571                                TargetLowering &TLI) {
3572  unsigned NumElems = PermMask.getNumOperands();
3573  unsigned NewWidth = (NumElems == 4) ? 2 : 4;
3574  MVT MaskVT = MVT::getIntVectorWithNumElements(NewWidth);
3575  MVT MaskEltVT = MaskVT.getVectorElementType();
3576  MVT NewVT = MaskVT;
3577  switch (VT.getSimpleVT()) {
3578  default: assert(false && "Unexpected!");
3579  case MVT::v4f32: NewVT = MVT::v2f64; break;
3580  case MVT::v4i32: NewVT = MVT::v2i64; break;
3581  case MVT::v8i16: NewVT = MVT::v4i32; break;
3582  case MVT::v16i8: NewVT = MVT::v4i32; break;
3583  }
3584
3585  if (NewWidth == 2) {
3586    if (VT.isInteger())
3587      NewVT = MVT::v2i64;
3588    else
3589      NewVT = MVT::v2f64;
3590  }
3591  unsigned Scale = NumElems / NewWidth;
3592  SmallVector<SDValue, 8> MaskVec;
3593  for (unsigned i = 0; i < NumElems; i += Scale) {
3594    unsigned StartIdx = ~0U;
3595    for (unsigned j = 0; j < Scale; ++j) {
3596      SDValue Elt = PermMask.getOperand(i+j);
3597      if (Elt.getOpcode() == ISD::UNDEF)
3598        continue;
3599      unsigned EltIdx = cast<ConstantSDNode>(Elt)->getValue();
3600      if (StartIdx == ~0U)
3601        StartIdx = EltIdx - (EltIdx % Scale);
3602      if (EltIdx != StartIdx + j)
3603        return SDValue();
3604    }
3605    if (StartIdx == ~0U)
3606      MaskVec.push_back(DAG.getNode(ISD::UNDEF, MaskEltVT));
3607    else
3608      MaskVec.push_back(DAG.getConstant(StartIdx / Scale, MaskEltVT));
3609  }
3610
3611  V1 = DAG.getNode(ISD::BIT_CONVERT, NewVT, V1);
3612  V2 = DAG.getNode(ISD::BIT_CONVERT, NewVT, V2);
3613  return DAG.getNode(ISD::VECTOR_SHUFFLE, NewVT, V1, V2,
3614                     DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3615                                 &MaskVec[0], MaskVec.size()));
3616}
3617
3618/// getVZextMovL - Return a zero-extending vector move low node.
3619///
3620static SDValue getVZextMovL(MVT VT, MVT OpVT,
3621                              SDValue SrcOp, SelectionDAG &DAG,
3622                              const X86Subtarget *Subtarget) {
3623  if (VT == MVT::v2f64 || VT == MVT::v4f32) {
3624    LoadSDNode *LD = NULL;
3625    if (!isScalarLoadToVector(SrcOp.Val, &LD))
3626      LD = dyn_cast<LoadSDNode>(SrcOp);
3627    if (!LD) {
3628      // movssrr and movsdrr do not clear top bits. Try to use movd, movq
3629      // instead.
3630      MVT EVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
3631      if ((EVT != MVT::i64 || Subtarget->is64Bit()) &&
3632          SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
3633          SrcOp.getOperand(0).getOpcode() == ISD::BIT_CONVERT &&
3634          SrcOp.getOperand(0).getOperand(0).getValueType() == EVT) {
3635        // PR2108
3636        OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
3637        return DAG.getNode(ISD::BIT_CONVERT, VT,
3638                           DAG.getNode(X86ISD::VZEXT_MOVL, OpVT,
3639                                       DAG.getNode(ISD::SCALAR_TO_VECTOR, OpVT,
3640                                                   SrcOp.getOperand(0).getOperand(0))));
3641      }
3642    }
3643  }
3644
3645  return DAG.getNode(ISD::BIT_CONVERT, VT,
3646                     DAG.getNode(X86ISD::VZEXT_MOVL, OpVT,
3647                                 DAG.getNode(ISD::BIT_CONVERT, OpVT, SrcOp)));
3648}
3649
3650/// LowerVECTOR_SHUFFLE_4wide - Handle all 4 wide cases with a number of
3651/// shuffles.
3652static SDValue
3653LowerVECTOR_SHUFFLE_4wide(SDValue V1, SDValue V2,
3654                          SDValue PermMask, MVT VT, SelectionDAG &DAG) {
3655  MVT MaskVT = PermMask.getValueType();
3656  MVT MaskEVT = MaskVT.getVectorElementType();
3657  SmallVector<std::pair<int, int>, 8> Locs;
3658  Locs.reserve(4);
3659  SmallVector<SDValue, 8> Mask1(4, DAG.getNode(ISD::UNDEF, MaskEVT));
3660  unsigned NumHi = 0;
3661  unsigned NumLo = 0;
3662  for (unsigned i = 0; i != 4; ++i) {
3663    SDValue Elt = PermMask.getOperand(i);
3664    if (Elt.getOpcode() == ISD::UNDEF) {
3665      Locs[i] = std::make_pair(-1, -1);
3666    } else {
3667      unsigned Val = cast<ConstantSDNode>(Elt)->getValue();
3668      assert(Val < 8 && "Invalid VECTOR_SHUFFLE index!");
3669      if (Val < 4) {
3670        Locs[i] = std::make_pair(0, NumLo);
3671        Mask1[NumLo] = Elt;
3672        NumLo++;
3673      } else {
3674        Locs[i] = std::make_pair(1, NumHi);
3675        if (2+NumHi < 4)
3676          Mask1[2+NumHi] = Elt;
3677        NumHi++;
3678      }
3679    }
3680  }
3681
3682  if (NumLo <= 2 && NumHi <= 2) {
3683    // If no more than two elements come from either vector. This can be
3684    // implemented with two shuffles. First shuffle gather the elements.
3685    // The second shuffle, which takes the first shuffle as both of its
3686    // vector operands, put the elements into the right order.
3687    V1 = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2,
3688                     DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3689                                 &Mask1[0], Mask1.size()));
3690
3691    SmallVector<SDValue, 8> Mask2(4, DAG.getNode(ISD::UNDEF, MaskEVT));
3692    for (unsigned i = 0; i != 4; ++i) {
3693      if (Locs[i].first == -1)
3694        continue;
3695      else {
3696        unsigned Idx = (i < 2) ? 0 : 4;
3697        Idx += Locs[i].first * 2 + Locs[i].second;
3698        Mask2[i] = DAG.getConstant(Idx, MaskEVT);
3699      }
3700    }
3701
3702    return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V1,
3703                       DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3704                                   &Mask2[0], Mask2.size()));
3705  } else if (NumLo == 3 || NumHi == 3) {
3706    // Otherwise, we must have three elements from one vector, call it X, and
3707    // one element from the other, call it Y.  First, use a shufps to build an
3708    // intermediate vector with the one element from Y and the element from X
3709    // that will be in the same half in the final destination (the indexes don't
3710    // matter). Then, use a shufps to build the final vector, taking the half
3711    // containing the element from Y from the intermediate, and the other half
3712    // from X.
3713    if (NumHi == 3) {
3714      // Normalize it so the 3 elements come from V1.
3715      PermMask = CommuteVectorShuffleMask(PermMask, DAG);
3716      std::swap(V1, V2);
3717    }
3718
3719    // Find the element from V2.
3720    unsigned HiIndex;
3721    for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
3722      SDValue Elt = PermMask.getOperand(HiIndex);
3723      if (Elt.getOpcode() == ISD::UNDEF)
3724        continue;
3725      unsigned Val = cast<ConstantSDNode>(Elt)->getValue();
3726      if (Val >= 4)
3727        break;
3728    }
3729
3730    Mask1[0] = PermMask.getOperand(HiIndex);
3731    Mask1[1] = DAG.getNode(ISD::UNDEF, MaskEVT);
3732    Mask1[2] = PermMask.getOperand(HiIndex^1);
3733    Mask1[3] = DAG.getNode(ISD::UNDEF, MaskEVT);
3734    V2 = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2,
3735                     DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &Mask1[0], 4));
3736
3737    if (HiIndex >= 2) {
3738      Mask1[0] = PermMask.getOperand(0);
3739      Mask1[1] = PermMask.getOperand(1);
3740      Mask1[2] = DAG.getConstant(HiIndex & 1 ? 6 : 4, MaskEVT);
3741      Mask1[3] = DAG.getConstant(HiIndex & 1 ? 4 : 6, MaskEVT);
3742      return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2,
3743                         DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &Mask1[0], 4));
3744    } else {
3745      Mask1[0] = DAG.getConstant(HiIndex & 1 ? 2 : 0, MaskEVT);
3746      Mask1[1] = DAG.getConstant(HiIndex & 1 ? 0 : 2, MaskEVT);
3747      Mask1[2] = PermMask.getOperand(2);
3748      Mask1[3] = PermMask.getOperand(3);
3749      if (Mask1[2].getOpcode() != ISD::UNDEF)
3750        Mask1[2] = DAG.getConstant(cast<ConstantSDNode>(Mask1[2])->getValue()+4,
3751                                   MaskEVT);
3752      if (Mask1[3].getOpcode() != ISD::UNDEF)
3753        Mask1[3] = DAG.getConstant(cast<ConstantSDNode>(Mask1[3])->getValue()+4,
3754                                   MaskEVT);
3755      return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V2, V1,
3756                         DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &Mask1[0], 4));
3757    }
3758  }
3759
3760  // Break it into (shuffle shuffle_hi, shuffle_lo).
3761  Locs.clear();
3762  SmallVector<SDValue,8> LoMask(4, DAG.getNode(ISD::UNDEF, MaskEVT));
3763  SmallVector<SDValue,8> HiMask(4, DAG.getNode(ISD::UNDEF, MaskEVT));
3764  SmallVector<SDValue,8> *MaskPtr = &LoMask;
3765  unsigned MaskIdx = 0;
3766  unsigned LoIdx = 0;
3767  unsigned HiIdx = 2;
3768  for (unsigned i = 0; i != 4; ++i) {
3769    if (i == 2) {
3770      MaskPtr = &HiMask;
3771      MaskIdx = 1;
3772      LoIdx = 0;
3773      HiIdx = 2;
3774    }
3775    SDValue Elt = PermMask.getOperand(i);
3776    if (Elt.getOpcode() == ISD::UNDEF) {
3777      Locs[i] = std::make_pair(-1, -1);
3778    } else if (cast<ConstantSDNode>(Elt)->getValue() < 4) {
3779      Locs[i] = std::make_pair(MaskIdx, LoIdx);
3780      (*MaskPtr)[LoIdx] = Elt;
3781      LoIdx++;
3782    } else {
3783      Locs[i] = std::make_pair(MaskIdx, HiIdx);
3784      (*MaskPtr)[HiIdx] = Elt;
3785      HiIdx++;
3786    }
3787  }
3788
3789  SDValue LoShuffle = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2,
3790                                    DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3791                                                &LoMask[0], LoMask.size()));
3792  SDValue HiShuffle = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2,
3793                                    DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3794                                                &HiMask[0], HiMask.size()));
3795  SmallVector<SDValue, 8> MaskOps;
3796  for (unsigned i = 0; i != 4; ++i) {
3797    if (Locs[i].first == -1) {
3798      MaskOps.push_back(DAG.getNode(ISD::UNDEF, MaskEVT));
3799    } else {
3800      unsigned Idx = Locs[i].first * 4 + Locs[i].second;
3801      MaskOps.push_back(DAG.getConstant(Idx, MaskEVT));
3802    }
3803  }
3804  return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, LoShuffle, HiShuffle,
3805                     DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3806                                 &MaskOps[0], MaskOps.size()));
3807}
3808
3809SDValue
3810X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) {
3811  SDValue V1 = Op.getOperand(0);
3812  SDValue V2 = Op.getOperand(1);
3813  SDValue PermMask = Op.getOperand(2);
3814  MVT VT = Op.getValueType();
3815  unsigned NumElems = PermMask.getNumOperands();
3816  bool isMMX = VT.getSizeInBits() == 64;
3817  bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
3818  bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
3819  bool V1IsSplat = false;
3820  bool V2IsSplat = false;
3821
3822  if (isUndefShuffle(Op.Val))
3823    return DAG.getNode(ISD::UNDEF, VT);
3824
3825  if (isZeroShuffle(Op.Val))
3826    return getZeroVector(VT, Subtarget->hasSSE2(), DAG);
3827
3828  if (isIdentityMask(PermMask.Val))
3829    return V1;
3830  else if (isIdentityMask(PermMask.Val, true))
3831    return V2;
3832
3833  if (isSplatMask(PermMask.Val)) {
3834    if (isMMX || NumElems < 4) return Op;
3835    // Promote it to a v4{if}32 splat.
3836    return PromoteSplat(Op, DAG, Subtarget->hasSSE2());
3837  }
3838
3839  // If the shuffle can be profitably rewritten as a narrower shuffle, then
3840  // do it!
3841  if (VT == MVT::v8i16 || VT == MVT::v16i8) {
3842    SDValue NewOp= RewriteAsNarrowerShuffle(V1, V2, VT, PermMask, DAG, *this);
3843    if (NewOp.Val)
3844      return DAG.getNode(ISD::BIT_CONVERT, VT, LowerVECTOR_SHUFFLE(NewOp, DAG));
3845  } else if ((VT == MVT::v4i32 || (VT == MVT::v4f32 && Subtarget->hasSSE2()))) {
3846    // FIXME: Figure out a cleaner way to do this.
3847    // Try to make use of movq to zero out the top part.
3848    if (ISD::isBuildVectorAllZeros(V2.Val)) {
3849      SDValue NewOp = RewriteAsNarrowerShuffle(V1, V2, VT, PermMask,
3850                                                 DAG, *this);
3851      if (NewOp.Val) {
3852        SDValue NewV1 = NewOp.getOperand(0);
3853        SDValue NewV2 = NewOp.getOperand(1);
3854        SDValue NewMask = NewOp.getOperand(2);
3855        if (isCommutedMOVL(NewMask.Val, true, false)) {
3856          NewOp = CommuteVectorShuffle(NewOp, NewV1, NewV2, NewMask, DAG);
3857          return getVZextMovL(VT, NewOp.getValueType(), NewV2, DAG, Subtarget);
3858        }
3859      }
3860    } else if (ISD::isBuildVectorAllZeros(V1.Val)) {
3861      SDValue NewOp= RewriteAsNarrowerShuffle(V1, V2, VT, PermMask,
3862                                                DAG, *this);
3863      if (NewOp.Val && X86::isMOVLMask(NewOp.getOperand(2).Val))
3864        return getVZextMovL(VT, NewOp.getValueType(), NewOp.getOperand(1),
3865                             DAG, Subtarget);
3866    }
3867  }
3868
3869  // Check if this can be converted into a logical shift.
3870  bool isLeft = false;
3871  unsigned ShAmt = 0;
3872  SDValue ShVal;
3873  bool isShift = isVectorShift(Op, PermMask, DAG, isLeft, ShVal, ShAmt);
3874  if (isShift && ShVal.hasOneUse()) {
3875    // If the shifted value has multiple uses, it may be cheaper to use
3876    // v_set0 + movlhps or movhlps, etc.
3877    MVT EVT = VT.getVectorElementType();
3878    ShAmt *= EVT.getSizeInBits();
3879    return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this);
3880  }
3881
3882  if (X86::isMOVLMask(PermMask.Val)) {
3883    if (V1IsUndef)
3884      return V2;
3885    if (ISD::isBuildVectorAllZeros(V1.Val))
3886      return getVZextMovL(VT, VT, V2, DAG, Subtarget);
3887    if (!isMMX)
3888      return Op;
3889  }
3890
3891  if (!isMMX && (X86::isMOVSHDUPMask(PermMask.Val) ||
3892                 X86::isMOVSLDUPMask(PermMask.Val) ||
3893                 X86::isMOVHLPSMask(PermMask.Val) ||
3894                 X86::isMOVHPMask(PermMask.Val) ||
3895                 X86::isMOVLPMask(PermMask.Val)))
3896    return Op;
3897
3898  if (ShouldXformToMOVHLPS(PermMask.Val) ||
3899      ShouldXformToMOVLP(V1.Val, V2.Val, PermMask.Val))
3900    return CommuteVectorShuffle(Op, V1, V2, PermMask, DAG);
3901
3902  if (isShift) {
3903    // No better options. Use a vshl / vsrl.
3904    MVT EVT = VT.getVectorElementType();
3905    ShAmt *= EVT.getSizeInBits();
3906    return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this);
3907  }
3908
3909  bool Commuted = false;
3910  // FIXME: This should also accept a bitcast of a splat?  Be careful, not
3911  // 1,1,1,1 -> v8i16 though.
3912  V1IsSplat = isSplatVector(V1.Val);
3913  V2IsSplat = isSplatVector(V2.Val);
3914
3915  // Canonicalize the splat or undef, if present, to be on the RHS.
3916  if ((V1IsSplat || V1IsUndef) && !(V2IsSplat || V2IsUndef)) {
3917    Op = CommuteVectorShuffle(Op, V1, V2, PermMask, DAG);
3918    std::swap(V1IsSplat, V2IsSplat);
3919    std::swap(V1IsUndef, V2IsUndef);
3920    Commuted = true;
3921  }
3922
3923  // FIXME: Figure out a cleaner way to do this.
3924  if (isCommutedMOVL(PermMask.Val, V2IsSplat, V2IsUndef)) {
3925    if (V2IsUndef) return V1;
3926    Op = CommuteVectorShuffle(Op, V1, V2, PermMask, DAG);
3927    if (V2IsSplat) {
3928      // V2 is a splat, so the mask may be malformed. That is, it may point
3929      // to any V2 element. The instruction selectior won't like this. Get
3930      // a corrected mask and commute to form a proper MOVS{S|D}.
3931      SDValue NewMask = getMOVLMask(NumElems, DAG);
3932      if (NewMask.Val != PermMask.Val)
3933        Op = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2, NewMask);
3934    }
3935    return Op;
3936  }
3937
3938  if (X86::isUNPCKL_v_undef_Mask(PermMask.Val) ||
3939      X86::isUNPCKH_v_undef_Mask(PermMask.Val) ||
3940      X86::isUNPCKLMask(PermMask.Val) ||
3941      X86::isUNPCKHMask(PermMask.Val))
3942    return Op;
3943
3944  if (V2IsSplat) {
3945    // Normalize mask so all entries that point to V2 points to its first
3946    // element then try to match unpck{h|l} again. If match, return a
3947    // new vector_shuffle with the corrected mask.
3948    SDValue NewMask = NormalizeMask(PermMask, DAG);
3949    if (NewMask.Val != PermMask.Val) {
3950      if (X86::isUNPCKLMask(PermMask.Val, true)) {
3951        SDValue NewMask = getUnpacklMask(NumElems, DAG);
3952        return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2, NewMask);
3953      } else if (X86::isUNPCKHMask(PermMask.Val, true)) {
3954        SDValue NewMask = getUnpackhMask(NumElems, DAG);
3955        return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2, NewMask);
3956      }
3957    }
3958  }
3959
3960  // Normalize the node to match x86 shuffle ops if needed
3961  if (V2.getOpcode() != ISD::UNDEF && isCommutedSHUFP(PermMask.Val))
3962      Op = CommuteVectorShuffle(Op, V1, V2, PermMask, DAG);
3963
3964  if (Commuted) {
3965    // Commute is back and try unpck* again.
3966    Op = CommuteVectorShuffle(Op, V1, V2, PermMask, DAG);
3967    if (X86::isUNPCKL_v_undef_Mask(PermMask.Val) ||
3968        X86::isUNPCKH_v_undef_Mask(PermMask.Val) ||
3969        X86::isUNPCKLMask(PermMask.Val) ||
3970        X86::isUNPCKHMask(PermMask.Val))
3971      return Op;
3972  }
3973
3974  // Try PSHUF* first, then SHUFP*.
3975  // MMX doesn't have PSHUFD but it does have PSHUFW. While it's theoretically
3976  // possible to shuffle a v2i32 using PSHUFW, that's not yet implemented.
3977  if (isMMX && NumElems == 4 && X86::isPSHUFDMask(PermMask.Val)) {
3978    if (V2.getOpcode() != ISD::UNDEF)
3979      return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1,
3980                         DAG.getNode(ISD::UNDEF, VT), PermMask);
3981    return Op;
3982  }
3983
3984  if (!isMMX) {
3985    if (Subtarget->hasSSE2() &&
3986        (X86::isPSHUFDMask(PermMask.Val) ||
3987         X86::isPSHUFHWMask(PermMask.Val) ||
3988         X86::isPSHUFLWMask(PermMask.Val))) {
3989      MVT RVT = VT;
3990      if (VT == MVT::v4f32) {
3991        RVT = MVT::v4i32;
3992        Op = DAG.getNode(ISD::VECTOR_SHUFFLE, RVT,
3993                         DAG.getNode(ISD::BIT_CONVERT, RVT, V1),
3994                         DAG.getNode(ISD::UNDEF, RVT), PermMask);
3995      } else if (V2.getOpcode() != ISD::UNDEF)
3996        Op = DAG.getNode(ISD::VECTOR_SHUFFLE, RVT, V1,
3997                         DAG.getNode(ISD::UNDEF, RVT), PermMask);
3998      if (RVT != VT)
3999        Op = DAG.getNode(ISD::BIT_CONVERT, VT, Op);
4000      return Op;
4001    }
4002
4003    // Binary or unary shufps.
4004    if (X86::isSHUFPMask(PermMask.Val) ||
4005        (V2.getOpcode() == ISD::UNDEF && X86::isPSHUFDMask(PermMask.Val)))
4006      return Op;
4007  }
4008
4009  // Handle v8i16 specifically since SSE can do byte extraction and insertion.
4010  if (VT == MVT::v8i16) {
4011    SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(V1, V2, PermMask, DAG, *this);
4012    if (NewOp.Val)
4013      return NewOp;
4014  }
4015
4016  // Handle all 4 wide cases with a number of shuffles except for MMX.
4017  if (NumElems == 4 && !isMMX)
4018    return LowerVECTOR_SHUFFLE_4wide(V1, V2, PermMask, VT, DAG);
4019
4020  return SDValue();
4021}
4022
4023SDValue
4024X86TargetLowering::LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op,
4025                                                SelectionDAG &DAG) {
4026  MVT VT = Op.getValueType();
4027  if (VT.getSizeInBits() == 8) {
4028    SDValue Extract = DAG.getNode(X86ISD::PEXTRB, MVT::i32,
4029                                    Op.getOperand(0), Op.getOperand(1));
4030    SDValue Assert  = DAG.getNode(ISD::AssertZext, MVT::i32, Extract,
4031                                    DAG.getValueType(VT));
4032    return DAG.getNode(ISD::TRUNCATE, VT, Assert);
4033  } else if (VT.getSizeInBits() == 16) {
4034    SDValue Extract = DAG.getNode(X86ISD::PEXTRW, MVT::i32,
4035                                    Op.getOperand(0), Op.getOperand(1));
4036    SDValue Assert  = DAG.getNode(ISD::AssertZext, MVT::i32, Extract,
4037                                    DAG.getValueType(VT));
4038    return DAG.getNode(ISD::TRUNCATE, VT, Assert);
4039  } else if (VT == MVT::f32) {
4040    // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
4041    // the result back to FR32 register. It's only worth matching if the
4042    // result has a single use which is a store or a bitcast to i32.
4043    if (!Op.hasOneUse())
4044      return SDValue();
4045    SDNode *User = *Op.Val->use_begin();
4046    if (User->getOpcode() != ISD::STORE &&
4047        (User->getOpcode() != ISD::BIT_CONVERT ||
4048         User->getValueType(0) != MVT::i32))
4049      return SDValue();
4050    SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, MVT::i32,
4051                    DAG.getNode(ISD::BIT_CONVERT, MVT::v4i32, Op.getOperand(0)),
4052                                    Op.getOperand(1));
4053    return DAG.getNode(ISD::BIT_CONVERT, MVT::f32, Extract);
4054  }
4055  return SDValue();
4056}
4057
4058
4059SDValue
4060X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
4061  if (!isa<ConstantSDNode>(Op.getOperand(1)))
4062    return SDValue();
4063
4064  if (Subtarget->hasSSE41()) {
4065    SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
4066    if (Res.Val)
4067      return Res;
4068  }
4069
4070  MVT VT = Op.getValueType();
4071  // TODO: handle v16i8.
4072  if (VT.getSizeInBits() == 16) {
4073    SDValue Vec = Op.getOperand(0);
4074    unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getValue();
4075    if (Idx == 0)
4076      return DAG.getNode(ISD::TRUNCATE, MVT::i16,
4077                         DAG.getNode(ISD::EXTRACT_VECTOR_ELT, MVT::i32,
4078                                 DAG.getNode(ISD::BIT_CONVERT, MVT::v4i32, Vec),
4079                                     Op.getOperand(1)));
4080    // Transform it so it match pextrw which produces a 32-bit result.
4081    MVT EVT = (MVT::SimpleValueType)(VT.getSimpleVT()+1);
4082    SDValue Extract = DAG.getNode(X86ISD::PEXTRW, EVT,
4083                                    Op.getOperand(0), Op.getOperand(1));
4084    SDValue Assert  = DAG.getNode(ISD::AssertZext, EVT, Extract,
4085                                    DAG.getValueType(VT));
4086    return DAG.getNode(ISD::TRUNCATE, VT, Assert);
4087  } else if (VT.getSizeInBits() == 32) {
4088    unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getValue();
4089    if (Idx == 0)
4090      return Op;
4091    // SHUFPS the element to the lowest double word, then movss.
4092    MVT MaskVT = MVT::getIntVectorWithNumElements(4);
4093    SmallVector<SDValue, 8> IdxVec;
4094    IdxVec.
4095      push_back(DAG.getConstant(Idx, MaskVT.getVectorElementType()));
4096    IdxVec.
4097      push_back(DAG.getNode(ISD::UNDEF, MaskVT.getVectorElementType()));
4098    IdxVec.
4099      push_back(DAG.getNode(ISD::UNDEF, MaskVT.getVectorElementType()));
4100    IdxVec.
4101      push_back(DAG.getNode(ISD::UNDEF, MaskVT.getVectorElementType()));
4102    SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
4103                                 &IdxVec[0], IdxVec.size());
4104    SDValue Vec = Op.getOperand(0);
4105    Vec = DAG.getNode(ISD::VECTOR_SHUFFLE, Vec.getValueType(),
4106                      Vec, DAG.getNode(ISD::UNDEF, Vec.getValueType()), Mask);
4107    return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, VT, Vec,
4108                       DAG.getIntPtrConstant(0));
4109  } else if (VT.getSizeInBits() == 64) {
4110    // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
4111    // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
4112    //        to match extract_elt for f64.
4113    unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getValue();
4114    if (Idx == 0)
4115      return Op;
4116
4117    // UNPCKHPD the element to the lowest double word, then movsd.
4118    // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
4119    // to a f64mem, the whole operation is folded into a single MOVHPDmr.
4120    MVT MaskVT = MVT::getIntVectorWithNumElements(2);
4121    SmallVector<SDValue, 8> IdxVec;
4122    IdxVec.push_back(DAG.getConstant(1, MaskVT.getVectorElementType()));
4123    IdxVec.
4124      push_back(DAG.getNode(ISD::UNDEF, MaskVT.getVectorElementType()));
4125    SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
4126                                 &IdxVec[0], IdxVec.size());
4127    SDValue Vec = Op.getOperand(0);
4128    Vec = DAG.getNode(ISD::VECTOR_SHUFFLE, Vec.getValueType(),
4129                      Vec, DAG.getNode(ISD::UNDEF, Vec.getValueType()), Mask);
4130    return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, VT, Vec,
4131                       DAG.getIntPtrConstant(0));
4132  }
4133
4134  return SDValue();
4135}
4136
4137SDValue
4138X86TargetLowering::LowerINSERT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG){
4139  MVT VT = Op.getValueType();
4140  MVT EVT = VT.getVectorElementType();
4141
4142  SDValue N0 = Op.getOperand(0);
4143  SDValue N1 = Op.getOperand(1);
4144  SDValue N2 = Op.getOperand(2);
4145
4146  if ((EVT.getSizeInBits() == 8) || (EVT.getSizeInBits() == 16)) {
4147    unsigned Opc = (EVT.getSizeInBits() == 8) ? X86ISD::PINSRB
4148                                                  : X86ISD::PINSRW;
4149    // Transform it so it match pinsr{b,w} which expects a GR32 as its second
4150    // argument.
4151    if (N1.getValueType() != MVT::i32)
4152      N1 = DAG.getNode(ISD::ANY_EXTEND, MVT::i32, N1);
4153    if (N2.getValueType() != MVT::i32)
4154      N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getValue());
4155    return DAG.getNode(Opc, VT, N0, N1, N2);
4156  } else if (EVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
4157    // Bits [7:6] of the constant are the source select.  This will always be
4158    //  zero here.  The DAG Combiner may combine an extract_elt index into these
4159    //  bits.  For example (insert (extract, 3), 2) could be matched by putting
4160    //  the '3' into bits [7:6] of X86ISD::INSERTPS.
4161    // Bits [5:4] of the constant are the destination select.  This is the
4162    //  value of the incoming immediate.
4163    // Bits [3:0] of the constant are the zero mask.  The DAG Combiner may
4164    //   combine either bitwise AND or insert of float 0.0 to set these bits.
4165    N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getValue() << 4);
4166    return DAG.getNode(X86ISD::INSERTPS, VT, N0, N1, N2);
4167  }
4168  return SDValue();
4169}
4170
4171SDValue
4172X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
4173  MVT VT = Op.getValueType();
4174  MVT EVT = VT.getVectorElementType();
4175
4176  if (Subtarget->hasSSE41())
4177    return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
4178
4179  if (EVT == MVT::i8)
4180    return SDValue();
4181
4182  SDValue N0 = Op.getOperand(0);
4183  SDValue N1 = Op.getOperand(1);
4184  SDValue N2 = Op.getOperand(2);
4185
4186  if (EVT.getSizeInBits() == 16) {
4187    // Transform it so it match pinsrw which expects a 16-bit value in a GR32
4188    // as its second argument.
4189    if (N1.getValueType() != MVT::i32)
4190      N1 = DAG.getNode(ISD::ANY_EXTEND, MVT::i32, N1);
4191    if (N2.getValueType() != MVT::i32)
4192      N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getValue());
4193    return DAG.getNode(X86ISD::PINSRW, VT, N0, N1, N2);
4194  }
4195  return SDValue();
4196}
4197
4198SDValue
4199X86TargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
4200  if (Op.getValueType() == MVT::v2f32)
4201    return DAG.getNode(ISD::BIT_CONVERT, MVT::v2f32,
4202                       DAG.getNode(ISD::SCALAR_TO_VECTOR, MVT::v2i32,
4203                                   DAG.getNode(ISD::BIT_CONVERT, MVT::i32,
4204                                               Op.getOperand(0))));
4205
4206  SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, MVT::i32, Op.getOperand(0));
4207  MVT VT = MVT::v2i32;
4208  switch (Op.getValueType().getSimpleVT()) {
4209  default: break;
4210  case MVT::v16i8:
4211  case MVT::v8i16:
4212    VT = MVT::v4i32;
4213    break;
4214  }
4215  return DAG.getNode(ISD::BIT_CONVERT, Op.getValueType(),
4216                     DAG.getNode(ISD::SCALAR_TO_VECTOR, VT, AnyExt));
4217}
4218
4219// ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
4220// their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
4221// one of the above mentioned nodes. It has to be wrapped because otherwise
4222// Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
4223// be used to form addressing mode. These wrapped nodes will be selected
4224// into MOV32ri.
4225SDValue
4226X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) {
4227  ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
4228  SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(),
4229                                               getPointerTy(),
4230                                               CP->getAlignment());
4231  Result = DAG.getNode(X86ISD::Wrapper, getPointerTy(), Result);
4232  // With PIC, the address is actually $g + Offset.
4233  if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
4234      !Subtarget->isPICStyleRIPRel()) {
4235    Result = DAG.getNode(ISD::ADD, getPointerTy(),
4236                         DAG.getNode(X86ISD::GlobalBaseReg, getPointerTy()),
4237                         Result);
4238  }
4239
4240  return Result;
4241}
4242
4243SDValue
4244X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) {
4245  GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
4246  SDValue Result = DAG.getTargetGlobalAddress(GV, getPointerTy());
4247  Result = DAG.getNode(X86ISD::Wrapper, getPointerTy(), Result);
4248  // With PIC, the address is actually $g + Offset.
4249  if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
4250      !Subtarget->isPICStyleRIPRel()) {
4251    Result = DAG.getNode(ISD::ADD, getPointerTy(),
4252                         DAG.getNode(X86ISD::GlobalBaseReg, getPointerTy()),
4253                         Result);
4254  }
4255
4256  // For Darwin & Mingw32, external and weak symbols are indirect, so we want to
4257  // load the value at address GV, not the value of GV itself. This means that
4258  // the GlobalAddress must be in the base or index register of the address, not
4259  // the GV offset field. Platform check is inside GVRequiresExtraLoad() call
4260  // The same applies for external symbols during PIC codegen
4261  if (Subtarget->GVRequiresExtraLoad(GV, getTargetMachine(), false))
4262    Result = DAG.getLoad(getPointerTy(), DAG.getEntryNode(), Result,
4263                         PseudoSourceValue::getGOT(), 0);
4264
4265  return Result;
4266}
4267
4268// Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
4269static SDValue
4270LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
4271                                const MVT PtrVT) {
4272  SDValue InFlag;
4273  SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), X86::EBX,
4274                                     DAG.getNode(X86ISD::GlobalBaseReg,
4275                                                 PtrVT), InFlag);
4276  InFlag = Chain.getValue(1);
4277
4278  // emit leal symbol@TLSGD(,%ebx,1), %eax
4279  SDVTList NodeTys = DAG.getVTList(PtrVT, MVT::Other, MVT::Flag);
4280  SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(),
4281                                             GA->getValueType(0),
4282                                             GA->getOffset());
4283  SDValue Ops[] = { Chain,  TGA, InFlag };
4284  SDValue Result = DAG.getNode(X86ISD::TLSADDR, NodeTys, Ops, 3);
4285  InFlag = Result.getValue(2);
4286  Chain = Result.getValue(1);
4287
4288  // call ___tls_get_addr. This function receives its argument in
4289  // the register EAX.
4290  Chain = DAG.getCopyToReg(Chain, X86::EAX, Result, InFlag);
4291  InFlag = Chain.getValue(1);
4292
4293  NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
4294  SDValue Ops1[] = { Chain,
4295                      DAG.getTargetExternalSymbol("___tls_get_addr",
4296                                                  PtrVT),
4297                      DAG.getRegister(X86::EAX, PtrVT),
4298                      DAG.getRegister(X86::EBX, PtrVT),
4299                      InFlag };
4300  Chain = DAG.getNode(X86ISD::CALL, NodeTys, Ops1, 5);
4301  InFlag = Chain.getValue(1);
4302
4303  return DAG.getCopyFromReg(Chain, X86::EAX, PtrVT, InFlag);
4304}
4305
4306// Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
4307static SDValue
4308LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
4309                                const MVT PtrVT) {
4310  SDValue InFlag, Chain;
4311
4312  // emit leaq symbol@TLSGD(%rip), %rdi
4313  SDVTList NodeTys = DAG.getVTList(PtrVT, MVT::Other, MVT::Flag);
4314  SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(),
4315                                             GA->getValueType(0),
4316                                             GA->getOffset());
4317  SDValue Ops[]  = { DAG.getEntryNode(), TGA};
4318  SDValue Result = DAG.getNode(X86ISD::TLSADDR, NodeTys, Ops, 2);
4319  Chain  = Result.getValue(1);
4320  InFlag = Result.getValue(2);
4321
4322  // call ___tls_get_addr. This function receives its argument in
4323  // the register RDI.
4324  Chain = DAG.getCopyToReg(Chain, X86::RDI, Result, InFlag);
4325  InFlag = Chain.getValue(1);
4326
4327  NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
4328  SDValue Ops1[] = { Chain,
4329                      DAG.getTargetExternalSymbol("___tls_get_addr",
4330                                                  PtrVT),
4331                      DAG.getRegister(X86::RDI, PtrVT),
4332                      InFlag };
4333  Chain = DAG.getNode(X86ISD::CALL, NodeTys, Ops1, 4);
4334  InFlag = Chain.getValue(1);
4335
4336  return DAG.getCopyFromReg(Chain, X86::RAX, PtrVT, InFlag);
4337}
4338
4339// Lower ISD::GlobalTLSAddress using the "initial exec" (for no-pic) or
4340// "local exec" model.
4341static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
4342                                     const MVT PtrVT) {
4343  // Get the Thread Pointer
4344  SDValue ThreadPointer = DAG.getNode(X86ISD::THREAD_POINTER, PtrVT);
4345  // emit "addl x@ntpoff,%eax" (local exec) or "addl x@indntpoff,%eax" (initial
4346  // exec)
4347  SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(),
4348                                             GA->getValueType(0),
4349                                             GA->getOffset());
4350  SDValue Offset = DAG.getNode(X86ISD::Wrapper, PtrVT, TGA);
4351
4352  if (GA->getGlobal()->isDeclaration()) // initial exec TLS model
4353    Offset = DAG.getLoad(PtrVT, DAG.getEntryNode(), Offset,
4354                         PseudoSourceValue::getGOT(), 0);
4355
4356  // The address of the thread local variable is the add of the thread
4357  // pointer with the offset of the variable.
4358  return DAG.getNode(ISD::ADD, PtrVT, ThreadPointer, Offset);
4359}
4360
4361SDValue
4362X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) {
4363  // TODO: implement the "local dynamic" model
4364  // TODO: implement the "initial exec"model for pic executables
4365  assert(Subtarget->isTargetELF() &&
4366         "TLS not implemented for non-ELF targets");
4367  GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
4368  // If the relocation model is PIC, use the "General Dynamic" TLS Model,
4369  // otherwise use the "Local Exec"TLS Model
4370  if (Subtarget->is64Bit()) {
4371    return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
4372  } else {
4373    if (getTargetMachine().getRelocationModel() == Reloc::PIC_)
4374      return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
4375    else
4376      return LowerToTLSExecModel(GA, DAG, getPointerTy());
4377  }
4378}
4379
4380SDValue
4381X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) {
4382  const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
4383  SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy());
4384  Result = DAG.getNode(X86ISD::Wrapper, getPointerTy(), Result);
4385  // With PIC, the address is actually $g + Offset.
4386  if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
4387      !Subtarget->isPICStyleRIPRel()) {
4388    Result = DAG.getNode(ISD::ADD, getPointerTy(),
4389                         DAG.getNode(X86ISD::GlobalBaseReg, getPointerTy()),
4390                         Result);
4391  }
4392
4393  return Result;
4394}
4395
4396SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) {
4397  JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
4398  SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy());
4399  Result = DAG.getNode(X86ISD::Wrapper, getPointerTy(), Result);
4400  // With PIC, the address is actually $g + Offset.
4401  if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
4402      !Subtarget->isPICStyleRIPRel()) {
4403    Result = DAG.getNode(ISD::ADD, getPointerTy(),
4404                         DAG.getNode(X86ISD::GlobalBaseReg, getPointerTy()),
4405                         Result);
4406  }
4407
4408  return Result;
4409}
4410
4411/// LowerShift - Lower SRA_PARTS and friends, which return two i32 values and
4412/// take a 2 x i32 value to shift plus a shift amount.
4413SDValue X86TargetLowering::LowerShift(SDValue Op, SelectionDAG &DAG) {
4414  assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4415  MVT VT = Op.getValueType();
4416  unsigned VTBits = VT.getSizeInBits();
4417  bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
4418  SDValue ShOpLo = Op.getOperand(0);
4419  SDValue ShOpHi = Op.getOperand(1);
4420  SDValue ShAmt  = Op.getOperand(2);
4421  SDValue Tmp1 = isSRA ?
4422    DAG.getNode(ISD::SRA, VT, ShOpHi, DAG.getConstant(VTBits - 1, MVT::i8)) :
4423    DAG.getConstant(0, VT);
4424
4425  SDValue Tmp2, Tmp3;
4426  if (Op.getOpcode() == ISD::SHL_PARTS) {
4427    Tmp2 = DAG.getNode(X86ISD::SHLD, VT, ShOpHi, ShOpLo, ShAmt);
4428    Tmp3 = DAG.getNode(ISD::SHL, VT, ShOpLo, ShAmt);
4429  } else {
4430    Tmp2 = DAG.getNode(X86ISD::SHRD, VT, ShOpLo, ShOpHi, ShAmt);
4431    Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, VT, ShOpHi, ShAmt);
4432  }
4433
4434  SDValue AndNode = DAG.getNode(ISD::AND, MVT::i8, ShAmt,
4435                                  DAG.getConstant(VTBits, MVT::i8));
4436  SDValue Cond = DAG.getNode(X86ISD::CMP, VT,
4437                               AndNode, DAG.getConstant(0, MVT::i8));
4438
4439  SDValue Hi, Lo;
4440  SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
4441  SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
4442  SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
4443
4444  if (Op.getOpcode() == ISD::SHL_PARTS) {
4445    Hi = DAG.getNode(X86ISD::CMOV, VT, Ops0, 4);
4446    Lo = DAG.getNode(X86ISD::CMOV, VT, Ops1, 4);
4447  } else {
4448    Lo = DAG.getNode(X86ISD::CMOV, VT, Ops0, 4);
4449    Hi = DAG.getNode(X86ISD::CMOV, VT, Ops1, 4);
4450  }
4451
4452  SDValue Ops[2] = { Lo, Hi };
4453  return DAG.getMergeValues(Ops, 2);
4454}
4455
4456SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
4457  MVT SrcVT = Op.getOperand(0).getValueType();
4458  assert(SrcVT.getSimpleVT() <= MVT::i64 && SrcVT.getSimpleVT() >= MVT::i16 &&
4459         "Unknown SINT_TO_FP to lower!");
4460
4461  // These are really Legal; caller falls through into that case.
4462  if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
4463    return SDValue();
4464  if (SrcVT == MVT::i64 && Op.getValueType() != MVT::f80 &&
4465      Subtarget->is64Bit())
4466    return SDValue();
4467
4468  unsigned Size = SrcVT.getSizeInBits()/8;
4469  MachineFunction &MF = DAG.getMachineFunction();
4470  int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size);
4471  SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
4472  SDValue Chain = DAG.getStore(DAG.getEntryNode(), Op.getOperand(0),
4473                                 StackSlot,
4474                                 PseudoSourceValue::getFixedStack(SSFI), 0);
4475
4476  // Build the FILD
4477  SDVTList Tys;
4478  bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
4479  if (useSSE)
4480    Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Flag);
4481  else
4482    Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
4483  SmallVector<SDValue, 8> Ops;
4484  Ops.push_back(Chain);
4485  Ops.push_back(StackSlot);
4486  Ops.push_back(DAG.getValueType(SrcVT));
4487  SDValue Result = DAG.getNode(useSSE ? X86ISD::FILD_FLAG : X86ISD::FILD,
4488                                 Tys, &Ops[0], Ops.size());
4489
4490  if (useSSE) {
4491    Chain = Result.getValue(1);
4492    SDValue InFlag = Result.getValue(2);
4493
4494    // FIXME: Currently the FST is flagged to the FILD_FLAG. This
4495    // shouldn't be necessary except that RFP cannot be live across
4496    // multiple blocks. When stackifier is fixed, they can be uncoupled.
4497    MachineFunction &MF = DAG.getMachineFunction();
4498    int SSFI = MF.getFrameInfo()->CreateStackObject(8, 8);
4499    SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
4500    Tys = DAG.getVTList(MVT::Other);
4501    SmallVector<SDValue, 8> Ops;
4502    Ops.push_back(Chain);
4503    Ops.push_back(Result);
4504    Ops.push_back(StackSlot);
4505    Ops.push_back(DAG.getValueType(Op.getValueType()));
4506    Ops.push_back(InFlag);
4507    Chain = DAG.getNode(X86ISD::FST, Tys, &Ops[0], Ops.size());
4508    Result = DAG.getLoad(Op.getValueType(), Chain, StackSlot,
4509                         PseudoSourceValue::getFixedStack(SSFI), 0);
4510  }
4511
4512  return Result;
4513}
4514
4515std::pair<SDValue,SDValue> X86TargetLowering::
4516FP_TO_SINTHelper(SDValue Op, SelectionDAG &DAG) {
4517  assert(Op.getValueType().getSimpleVT() <= MVT::i64 &&
4518         Op.getValueType().getSimpleVT() >= MVT::i16 &&
4519         "Unknown FP_TO_SINT to lower!");
4520
4521  // These are really Legal.
4522  if (Op.getValueType() == MVT::i32 &&
4523      isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
4524    return std::make_pair(SDValue(), SDValue());
4525  if (Subtarget->is64Bit() &&
4526      Op.getValueType() == MVT::i64 &&
4527      Op.getOperand(0).getValueType() != MVT::f80)
4528    return std::make_pair(SDValue(), SDValue());
4529
4530  // We lower FP->sint64 into FISTP64, followed by a load, all to a temporary
4531  // stack slot.
4532  MachineFunction &MF = DAG.getMachineFunction();
4533  unsigned MemSize = Op.getValueType().getSizeInBits()/8;
4534  int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize);
4535  SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
4536  unsigned Opc;
4537  switch (Op.getValueType().getSimpleVT()) {
4538  default: assert(0 && "Invalid FP_TO_SINT to lower!");
4539  case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
4540  case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
4541  case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
4542  }
4543
4544  SDValue Chain = DAG.getEntryNode();
4545  SDValue Value = Op.getOperand(0);
4546  if (isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType())) {
4547    assert(Op.getValueType() == MVT::i64 && "Invalid FP_TO_SINT to lower!");
4548    Chain = DAG.getStore(Chain, Value, StackSlot,
4549                         PseudoSourceValue::getFixedStack(SSFI), 0);
4550    SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
4551    SDValue Ops[] = {
4552      Chain, StackSlot, DAG.getValueType(Op.getOperand(0).getValueType())
4553    };
4554    Value = DAG.getNode(X86ISD::FLD, Tys, Ops, 3);
4555    Chain = Value.getValue(1);
4556    SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize);
4557    StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
4558  }
4559
4560  // Build the FP_TO_INT*_IN_MEM
4561  SDValue Ops[] = { Chain, Value, StackSlot };
4562  SDValue FIST = DAG.getNode(Opc, MVT::Other, Ops, 3);
4563
4564  return std::make_pair(FIST, StackSlot);
4565}
4566
4567SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op, SelectionDAG &DAG) {
4568  std::pair<SDValue,SDValue> Vals = FP_TO_SINTHelper(Op, DAG);
4569  SDValue FIST = Vals.first, StackSlot = Vals.second;
4570  if (FIST.Val == 0) return SDValue();
4571
4572  // Load the result.
4573  return DAG.getLoad(Op.getValueType(), FIST, StackSlot, NULL, 0);
4574}
4575
4576SDNode *X86TargetLowering::ExpandFP_TO_SINT(SDNode *N, SelectionDAG &DAG) {
4577  std::pair<SDValue,SDValue> Vals = FP_TO_SINTHelper(SDValue(N, 0), DAG);
4578  SDValue FIST = Vals.first, StackSlot = Vals.second;
4579  if (FIST.Val == 0) return 0;
4580
4581  MVT VT = N->getValueType(0);
4582
4583  // Return a load from the stack slot.
4584  SDValue Res = DAG.getLoad(VT, FIST, StackSlot, NULL, 0);
4585
4586  // Use MERGE_VALUES to drop the chain result value and get a node with one
4587  // result.  This requires turning off getMergeValues simplification, since
4588  // otherwise it will give us Res back.
4589  return DAG.getMergeValues(&Res, 1, false).Val;
4590}
4591
4592SDValue X86TargetLowering::LowerFABS(SDValue Op, SelectionDAG &DAG) {
4593  MVT VT = Op.getValueType();
4594  MVT EltVT = VT;
4595  if (VT.isVector())
4596    EltVT = VT.getVectorElementType();
4597  std::vector<Constant*> CV;
4598  if (EltVT == MVT::f64) {
4599    Constant *C = ConstantFP::get(APFloat(APInt(64, ~(1ULL << 63))));
4600    CV.push_back(C);
4601    CV.push_back(C);
4602  } else {
4603    Constant *C = ConstantFP::get(APFloat(APInt(32, ~(1U << 31))));
4604    CV.push_back(C);
4605    CV.push_back(C);
4606    CV.push_back(C);
4607    CV.push_back(C);
4608  }
4609  Constant *C = ConstantVector::get(CV);
4610  SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 4);
4611  SDValue Mask = DAG.getLoad(VT, DAG.getEntryNode(), CPIdx,
4612                               PseudoSourceValue::getConstantPool(), 0,
4613                               false, 16);
4614  return DAG.getNode(X86ISD::FAND, VT, Op.getOperand(0), Mask);
4615}
4616
4617SDValue X86TargetLowering::LowerFNEG(SDValue Op, SelectionDAG &DAG) {
4618  MVT VT = Op.getValueType();
4619  MVT EltVT = VT;
4620  unsigned EltNum = 1;
4621  if (VT.isVector()) {
4622    EltVT = VT.getVectorElementType();
4623    EltNum = VT.getVectorNumElements();
4624  }
4625  std::vector<Constant*> CV;
4626  if (EltVT == MVT::f64) {
4627    Constant *C = ConstantFP::get(APFloat(APInt(64, 1ULL << 63)));
4628    CV.push_back(C);
4629    CV.push_back(C);
4630  } else {
4631    Constant *C = ConstantFP::get(APFloat(APInt(32, 1U << 31)));
4632    CV.push_back(C);
4633    CV.push_back(C);
4634    CV.push_back(C);
4635    CV.push_back(C);
4636  }
4637  Constant *C = ConstantVector::get(CV);
4638  SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 4);
4639  SDValue Mask = DAG.getLoad(VT, DAG.getEntryNode(), CPIdx,
4640                               PseudoSourceValue::getConstantPool(), 0,
4641                               false, 16);
4642  if (VT.isVector()) {
4643    return DAG.getNode(ISD::BIT_CONVERT, VT,
4644                       DAG.getNode(ISD::XOR, MVT::v2i64,
4645                    DAG.getNode(ISD::BIT_CONVERT, MVT::v2i64, Op.getOperand(0)),
4646                    DAG.getNode(ISD::BIT_CONVERT, MVT::v2i64, Mask)));
4647  } else {
4648    return DAG.getNode(X86ISD::FXOR, VT, Op.getOperand(0), Mask);
4649  }
4650}
4651
4652SDValue X86TargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) {
4653  SDValue Op0 = Op.getOperand(0);
4654  SDValue Op1 = Op.getOperand(1);
4655  MVT VT = Op.getValueType();
4656  MVT SrcVT = Op1.getValueType();
4657
4658  // If second operand is smaller, extend it first.
4659  if (SrcVT.bitsLT(VT)) {
4660    Op1 = DAG.getNode(ISD::FP_EXTEND, VT, Op1);
4661    SrcVT = VT;
4662  }
4663  // And if it is bigger, shrink it first.
4664  if (SrcVT.bitsGT(VT)) {
4665    Op1 = DAG.getNode(ISD::FP_ROUND, VT, Op1, DAG.getIntPtrConstant(1));
4666    SrcVT = VT;
4667  }
4668
4669  // At this point the operands and the result should have the same
4670  // type, and that won't be f80 since that is not custom lowered.
4671
4672  // First get the sign bit of second operand.
4673  std::vector<Constant*> CV;
4674  if (SrcVT == MVT::f64) {
4675    CV.push_back(ConstantFP::get(APFloat(APInt(64, 1ULL << 63))));
4676    CV.push_back(ConstantFP::get(APFloat(APInt(64, 0))));
4677  } else {
4678    CV.push_back(ConstantFP::get(APFloat(APInt(32, 1U << 31))));
4679    CV.push_back(ConstantFP::get(APFloat(APInt(32, 0))));
4680    CV.push_back(ConstantFP::get(APFloat(APInt(32, 0))));
4681    CV.push_back(ConstantFP::get(APFloat(APInt(32, 0))));
4682  }
4683  Constant *C = ConstantVector::get(CV);
4684  SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 4);
4685  SDValue Mask1 = DAG.getLoad(SrcVT, DAG.getEntryNode(), CPIdx,
4686                                PseudoSourceValue::getConstantPool(), 0,
4687                                false, 16);
4688  SDValue SignBit = DAG.getNode(X86ISD::FAND, SrcVT, Op1, Mask1);
4689
4690  // Shift sign bit right or left if the two operands have different types.
4691  if (SrcVT.bitsGT(VT)) {
4692    // Op0 is MVT::f32, Op1 is MVT::f64.
4693    SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, MVT::v2f64, SignBit);
4694    SignBit = DAG.getNode(X86ISD::FSRL, MVT::v2f64, SignBit,
4695                          DAG.getConstant(32, MVT::i32));
4696    SignBit = DAG.getNode(ISD::BIT_CONVERT, MVT::v4f32, SignBit);
4697    SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, MVT::f32, SignBit,
4698                          DAG.getIntPtrConstant(0));
4699  }
4700
4701  // Clear first operand sign bit.
4702  CV.clear();
4703  if (VT == MVT::f64) {
4704    CV.push_back(ConstantFP::get(APFloat(APInt(64, ~(1ULL << 63)))));
4705    CV.push_back(ConstantFP::get(APFloat(APInt(64, 0))));
4706  } else {
4707    CV.push_back(ConstantFP::get(APFloat(APInt(32, ~(1U << 31)))));
4708    CV.push_back(ConstantFP::get(APFloat(APInt(32, 0))));
4709    CV.push_back(ConstantFP::get(APFloat(APInt(32, 0))));
4710    CV.push_back(ConstantFP::get(APFloat(APInt(32, 0))));
4711  }
4712  C = ConstantVector::get(CV);
4713  CPIdx = DAG.getConstantPool(C, getPointerTy(), 4);
4714  SDValue Mask2 = DAG.getLoad(VT, DAG.getEntryNode(), CPIdx,
4715                                PseudoSourceValue::getConstantPool(), 0,
4716                                false, 16);
4717  SDValue Val = DAG.getNode(X86ISD::FAND, VT, Op0, Mask2);
4718
4719  // Or the value with the sign bit.
4720  return DAG.getNode(X86ISD::FOR, VT, Val, SignBit);
4721}
4722
4723SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) {
4724  assert(Op.getValueType() == MVT::i8 && "SetCC type must be 8-bit integer");
4725  SDValue Cond;
4726  SDValue Op0 = Op.getOperand(0);
4727  SDValue Op1 = Op.getOperand(1);
4728  SDValue CC = Op.getOperand(2);
4729  ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
4730  bool isFP = Op.getOperand(1).getValueType().isFloatingPoint();
4731  unsigned X86CC;
4732
4733  if (translateX86CC(cast<CondCodeSDNode>(CC)->get(), isFP, X86CC,
4734                     Op0, Op1, DAG)) {
4735    Cond = DAG.getNode(X86ISD::CMP, MVT::i32, Op0, Op1);
4736    return DAG.getNode(X86ISD::SETCC, MVT::i8,
4737                       DAG.getConstant(X86CC, MVT::i8), Cond);
4738  }
4739
4740  assert(isFP && "Illegal integer SetCC!");
4741
4742  Cond = DAG.getNode(X86ISD::CMP, MVT::i32, Op0, Op1);
4743  switch (SetCCOpcode) {
4744  default: assert(false && "Illegal floating point SetCC!");
4745  case ISD::SETOEQ: {  // !PF & ZF
4746    SDValue Tmp1 = DAG.getNode(X86ISD::SETCC, MVT::i8,
4747                                 DAG.getConstant(X86::COND_NP, MVT::i8), Cond);
4748    SDValue Tmp2 = DAG.getNode(X86ISD::SETCC, MVT::i8,
4749                                 DAG.getConstant(X86::COND_E, MVT::i8), Cond);
4750    return DAG.getNode(ISD::AND, MVT::i8, Tmp1, Tmp2);
4751  }
4752  case ISD::SETUNE: {  // PF | !ZF
4753    SDValue Tmp1 = DAG.getNode(X86ISD::SETCC, MVT::i8,
4754                                 DAG.getConstant(X86::COND_P, MVT::i8), Cond);
4755    SDValue Tmp2 = DAG.getNode(X86ISD::SETCC, MVT::i8,
4756                                 DAG.getConstant(X86::COND_NE, MVT::i8), Cond);
4757    return DAG.getNode(ISD::OR, MVT::i8, Tmp1, Tmp2);
4758  }
4759  }
4760}
4761
4762SDValue X86TargetLowering::LowerVSETCC(SDValue Op, SelectionDAG &DAG) {
4763  SDValue Cond;
4764  SDValue Op0 = Op.getOperand(0);
4765  SDValue Op1 = Op.getOperand(1);
4766  SDValue CC = Op.getOperand(2);
4767  MVT VT = Op.getValueType();
4768  ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
4769  bool isFP = Op.getOperand(1).getValueType().isFloatingPoint();
4770
4771  if (isFP) {
4772    unsigned SSECC = 8;
4773    MVT VT0 = Op0.getValueType();
4774    assert(VT0 == MVT::v4f32 || VT0 == MVT::v2f64);
4775    unsigned Opc = VT0 == MVT::v4f32 ? X86ISD::CMPPS : X86ISD::CMPPD;
4776    bool Swap = false;
4777
4778    switch (SetCCOpcode) {
4779    default: break;
4780    case ISD::SETOEQ:
4781    case ISD::SETEQ:  SSECC = 0; break;
4782    case ISD::SETOGT:
4783    case ISD::SETGT: Swap = true; // Fallthrough
4784    case ISD::SETLT:
4785    case ISD::SETOLT: SSECC = 1; break;
4786    case ISD::SETOGE:
4787    case ISD::SETGE: Swap = true; // Fallthrough
4788    case ISD::SETLE:
4789    case ISD::SETOLE: SSECC = 2; break;
4790    case ISD::SETUO:  SSECC = 3; break;
4791    case ISD::SETUNE:
4792    case ISD::SETNE:  SSECC = 4; break;
4793    case ISD::SETULE: Swap = true;
4794    case ISD::SETUGE: SSECC = 5; break;
4795    case ISD::SETULT: Swap = true;
4796    case ISD::SETUGT: SSECC = 6; break;
4797    case ISD::SETO:   SSECC = 7; break;
4798    }
4799    if (Swap)
4800      std::swap(Op0, Op1);
4801
4802    // In the two special cases we can't handle, emit two comparisons.
4803    if (SSECC == 8) {
4804      if (SetCCOpcode == ISD::SETUEQ) {
4805        SDValue UNORD, EQ;
4806        UNORD = DAG.getNode(Opc, VT, Op0, Op1, DAG.getConstant(3, MVT::i8));
4807        EQ = DAG.getNode(Opc, VT, Op0, Op1, DAG.getConstant(0, MVT::i8));
4808        return DAG.getNode(ISD::OR, VT, UNORD, EQ);
4809      }
4810      else if (SetCCOpcode == ISD::SETONE) {
4811        SDValue ORD, NEQ;
4812        ORD = DAG.getNode(Opc, VT, Op0, Op1, DAG.getConstant(7, MVT::i8));
4813        NEQ = DAG.getNode(Opc, VT, Op0, Op1, DAG.getConstant(4, MVT::i8));
4814        return DAG.getNode(ISD::AND, VT, ORD, NEQ);
4815      }
4816      assert(0 && "Illegal FP comparison");
4817    }
4818    // Handle all other FP comparisons here.
4819    return DAG.getNode(Opc, VT, Op0, Op1, DAG.getConstant(SSECC, MVT::i8));
4820  }
4821
4822  // We are handling one of the integer comparisons here.  Since SSE only has
4823  // GT and EQ comparisons for integer, swapping operands and multiple
4824  // operations may be required for some comparisons.
4825  unsigned Opc = 0, EQOpc = 0, GTOpc = 0;
4826  bool Swap = false, Invert = false, FlipSigns = false;
4827
4828  switch (VT.getSimpleVT()) {
4829  default: break;
4830  case MVT::v16i8: EQOpc = X86ISD::PCMPEQB; GTOpc = X86ISD::PCMPGTB; break;
4831  case MVT::v8i16: EQOpc = X86ISD::PCMPEQW; GTOpc = X86ISD::PCMPGTW; break;
4832  case MVT::v4i32: EQOpc = X86ISD::PCMPEQD; GTOpc = X86ISD::PCMPGTD; break;
4833  case MVT::v2i64: EQOpc = X86ISD::PCMPEQQ; GTOpc = X86ISD::PCMPGTQ; break;
4834  }
4835
4836  switch (SetCCOpcode) {
4837  default: break;
4838  case ISD::SETNE:  Invert = true;
4839  case ISD::SETEQ:  Opc = EQOpc; break;
4840  case ISD::SETLT:  Swap = true;
4841  case ISD::SETGT:  Opc = GTOpc; break;
4842  case ISD::SETGE:  Swap = true;
4843  case ISD::SETLE:  Opc = GTOpc; Invert = true; break;
4844  case ISD::SETULT: Swap = true;
4845  case ISD::SETUGT: Opc = GTOpc; FlipSigns = true; break;
4846  case ISD::SETUGE: Swap = true;
4847  case ISD::SETULE: Opc = GTOpc; FlipSigns = true; Invert = true; break;
4848  }
4849  if (Swap)
4850    std::swap(Op0, Op1);
4851
4852  // Since SSE has no unsigned integer comparisons, we need to flip  the sign
4853  // bits of the inputs before performing those operations.
4854  if (FlipSigns) {
4855    MVT EltVT = VT.getVectorElementType();
4856    SDValue SignBit = DAG.getConstant(EltVT.getIntegerVTSignBit(), EltVT);
4857    std::vector<SDValue> SignBits(VT.getVectorNumElements(), SignBit);
4858    SDValue SignVec = DAG.getNode(ISD::BUILD_VECTOR, VT, &SignBits[0],
4859                                    SignBits.size());
4860    Op0 = DAG.getNode(ISD::XOR, VT, Op0, SignVec);
4861    Op1 = DAG.getNode(ISD::XOR, VT, Op1, SignVec);
4862  }
4863
4864  SDValue Result = DAG.getNode(Opc, VT, Op0, Op1);
4865
4866  // If the logical-not of the result is required, perform that now.
4867  if (Invert) {
4868    MVT EltVT = VT.getVectorElementType();
4869    SDValue NegOne = DAG.getConstant(EltVT.getIntegerVTBitMask(), EltVT);
4870    std::vector<SDValue> NegOnes(VT.getVectorNumElements(), NegOne);
4871    SDValue NegOneV = DAG.getNode(ISD::BUILD_VECTOR, VT, &NegOnes[0],
4872                                    NegOnes.size());
4873    Result = DAG.getNode(ISD::XOR, VT, Result, NegOneV);
4874  }
4875  return Result;
4876}
4877
4878SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) {
4879  bool addTest = true;
4880  SDValue Cond  = Op.getOperand(0);
4881  SDValue CC;
4882
4883  if (Cond.getOpcode() == ISD::SETCC)
4884    Cond = LowerSETCC(Cond, DAG);
4885
4886  // If condition flag is set by a X86ISD::CMP, then use it as the condition
4887  // setting operand in place of the X86ISD::SETCC.
4888  if (Cond.getOpcode() == X86ISD::SETCC) {
4889    CC = Cond.getOperand(0);
4890
4891    SDValue Cmp = Cond.getOperand(1);
4892    unsigned Opc = Cmp.getOpcode();
4893    MVT VT = Op.getValueType();
4894
4895    bool IllegalFPCMov = false;
4896    if (VT.isFloatingPoint() && !VT.isVector() &&
4897        !isScalarFPTypeInSSEReg(VT))  // FPStack?
4898      IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSignExtended());
4899
4900    if ((Opc == X86ISD::CMP ||
4901         Opc == X86ISD::COMI ||
4902         Opc == X86ISD::UCOMI) && !IllegalFPCMov) {
4903      Cond = Cmp;
4904      addTest = false;
4905    }
4906  }
4907
4908  if (addTest) {
4909    CC = DAG.getConstant(X86::COND_NE, MVT::i8);
4910    Cond= DAG.getNode(X86ISD::CMP, MVT::i32, Cond, DAG.getConstant(0, MVT::i8));
4911  }
4912
4913  const MVT *VTs = DAG.getNodeValueTypes(Op.getValueType(),
4914                                                    MVT::Flag);
4915  SmallVector<SDValue, 4> Ops;
4916  // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
4917  // condition is true.
4918  Ops.push_back(Op.getOperand(2));
4919  Ops.push_back(Op.getOperand(1));
4920  Ops.push_back(CC);
4921  Ops.push_back(Cond);
4922  return DAG.getNode(X86ISD::CMOV, VTs, 2, &Ops[0], Ops.size());
4923}
4924
4925SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) {
4926  bool addTest = true;
4927  SDValue Chain = Op.getOperand(0);
4928  SDValue Cond  = Op.getOperand(1);
4929  SDValue Dest  = Op.getOperand(2);
4930  SDValue CC;
4931
4932  if (Cond.getOpcode() == ISD::SETCC)
4933    Cond = LowerSETCC(Cond, DAG);
4934
4935  // If condition flag is set by a X86ISD::CMP, then use it as the condition
4936  // setting operand in place of the X86ISD::SETCC.
4937  if (Cond.getOpcode() == X86ISD::SETCC) {
4938    CC = Cond.getOperand(0);
4939
4940    SDValue Cmp = Cond.getOperand(1);
4941    unsigned Opc = Cmp.getOpcode();
4942    if (Opc == X86ISD::CMP ||
4943        Opc == X86ISD::COMI ||
4944        Opc == X86ISD::UCOMI) {
4945      Cond = Cmp;
4946      addTest = false;
4947    }
4948  }
4949
4950  if (addTest) {
4951    CC = DAG.getConstant(X86::COND_NE, MVT::i8);
4952    Cond= DAG.getNode(X86ISD::CMP, MVT::i32, Cond, DAG.getConstant(0, MVT::i8));
4953  }
4954  return DAG.getNode(X86ISD::BRCOND, Op.getValueType(),
4955                     Chain, Op.getOperand(2), CC, Cond);
4956}
4957
4958
4959// Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
4960// Calls to _alloca is needed to probe the stack when allocating more than 4k
4961// bytes in one go. Touching the stack at 4K increments is necessary to ensure
4962// that the guard pages used by the OS virtual memory manager are allocated in
4963// correct sequence.
4964SDValue
4965X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
4966                                           SelectionDAG &DAG) {
4967  assert(Subtarget->isTargetCygMing() &&
4968         "This should be used only on Cygwin/Mingw targets");
4969
4970  // Get the inputs.
4971  SDValue Chain = Op.getOperand(0);
4972  SDValue Size  = Op.getOperand(1);
4973  // FIXME: Ensure alignment here
4974
4975  SDValue Flag;
4976
4977  MVT IntPtr = getPointerTy();
4978  MVT SPTy = Subtarget->is64Bit() ? MVT::i64 : MVT::i32;
4979
4980  Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(0));
4981
4982  Chain = DAG.getCopyToReg(Chain, X86::EAX, Size, Flag);
4983  Flag = Chain.getValue(1);
4984
4985  SDVTList  NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
4986  SDValue Ops[] = { Chain,
4987                      DAG.getTargetExternalSymbol("_alloca", IntPtr),
4988                      DAG.getRegister(X86::EAX, IntPtr),
4989                      DAG.getRegister(X86StackPtr, SPTy),
4990                      Flag };
4991  Chain = DAG.getNode(X86ISD::CALL, NodeTys, Ops, 5);
4992  Flag = Chain.getValue(1);
4993
4994  Chain = DAG.getCALLSEQ_END(Chain,
4995                             DAG.getIntPtrConstant(0),
4996                             DAG.getIntPtrConstant(0),
4997                             Flag);
4998
4999  Chain = DAG.getCopyFromReg(Chain, X86StackPtr, SPTy).getValue(1);
5000
5001  SDValue Ops1[2] = { Chain.getValue(0), Chain };
5002  return DAG.getMergeValues(Ops1, 2);
5003}
5004
5005SDValue
5006X86TargetLowering::EmitTargetCodeForMemset(SelectionDAG &DAG,
5007                                           SDValue Chain,
5008                                           SDValue Dst, SDValue Src,
5009                                           SDValue Size, unsigned Align,
5010                                        const Value *DstSV, uint64_t DstSVOff) {
5011  ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
5012
5013  /// If not DWORD aligned or size is more than the threshold, call the library.
5014  /// The libc version is likely to be faster for these cases. It can use the
5015  /// address value and run time information about the CPU.
5016  if ((Align & 3) == 0 ||
5017      !ConstantSize ||
5018      ConstantSize->getValue() > getSubtarget()->getMaxInlineSizeThreshold()) {
5019    SDValue InFlag(0, 0);
5020
5021    // Check to see if there is a specialized entry-point for memory zeroing.
5022    ConstantSDNode *V = dyn_cast<ConstantSDNode>(Src);
5023    if (const char *bzeroEntry =
5024          V && V->isNullValue() ? Subtarget->getBZeroEntry() : 0) {
5025      MVT IntPtr = getPointerTy();
5026      const Type *IntPtrTy = getTargetData()->getIntPtrType();
5027      TargetLowering::ArgListTy Args;
5028      TargetLowering::ArgListEntry Entry;
5029      Entry.Node = Dst;
5030      Entry.Ty = IntPtrTy;
5031      Args.push_back(Entry);
5032      Entry.Node = Size;
5033      Args.push_back(Entry);
5034      std::pair<SDValue,SDValue> CallResult =
5035        LowerCallTo(Chain, Type::VoidTy, false, false, false, CallingConv::C,
5036                    false, DAG.getExternalSymbol(bzeroEntry, IntPtr),
5037                    Args, DAG);
5038      return CallResult.second;
5039    }
5040
5041    // Otherwise have the target-independent code call memset.
5042    return SDValue();
5043  }
5044
5045  uint64_t SizeVal = ConstantSize->getValue();
5046  SDValue InFlag(0, 0);
5047  MVT AVT;
5048  SDValue Count;
5049  ConstantSDNode *ValC = dyn_cast<ConstantSDNode>(Src);
5050  unsigned BytesLeft = 0;
5051  bool TwoRepStos = false;
5052  if (ValC) {
5053    unsigned ValReg;
5054    uint64_t Val = ValC->getValue() & 255;
5055
5056    // If the value is a constant, then we can potentially use larger sets.
5057    switch (Align & 3) {
5058      case 2:   // WORD aligned
5059        AVT = MVT::i16;
5060        ValReg = X86::AX;
5061        Val = (Val << 8) | Val;
5062        break;
5063      case 0:  // DWORD aligned
5064        AVT = MVT::i32;
5065        ValReg = X86::EAX;
5066        Val = (Val << 8)  | Val;
5067        Val = (Val << 16) | Val;
5068        if (Subtarget->is64Bit() && ((Align & 0x7) == 0)) {  // QWORD aligned
5069          AVT = MVT::i64;
5070          ValReg = X86::RAX;
5071          Val = (Val << 32) | Val;
5072        }
5073        break;
5074      default:  // Byte aligned
5075        AVT = MVT::i8;
5076        ValReg = X86::AL;
5077        Count = DAG.getIntPtrConstant(SizeVal);
5078        break;
5079    }
5080
5081    if (AVT.bitsGT(MVT::i8)) {
5082      unsigned UBytes = AVT.getSizeInBits() / 8;
5083      Count = DAG.getIntPtrConstant(SizeVal / UBytes);
5084      BytesLeft = SizeVal % UBytes;
5085    }
5086
5087    Chain  = DAG.getCopyToReg(Chain, ValReg, DAG.getConstant(Val, AVT),
5088                              InFlag);
5089    InFlag = Chain.getValue(1);
5090  } else {
5091    AVT = MVT::i8;
5092    Count  = DAG.getIntPtrConstant(SizeVal);
5093    Chain  = DAG.getCopyToReg(Chain, X86::AL, Src, InFlag);
5094    InFlag = Chain.getValue(1);
5095  }
5096
5097  Chain  = DAG.getCopyToReg(Chain, Subtarget->is64Bit() ? X86::RCX : X86::ECX,
5098                            Count, InFlag);
5099  InFlag = Chain.getValue(1);
5100  Chain  = DAG.getCopyToReg(Chain, Subtarget->is64Bit() ? X86::RDI : X86::EDI,
5101                            Dst, InFlag);
5102  InFlag = Chain.getValue(1);
5103
5104  SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
5105  SmallVector<SDValue, 8> Ops;
5106  Ops.push_back(Chain);
5107  Ops.push_back(DAG.getValueType(AVT));
5108  Ops.push_back(InFlag);
5109  Chain  = DAG.getNode(X86ISD::REP_STOS, Tys, &Ops[0], Ops.size());
5110
5111  if (TwoRepStos) {
5112    InFlag = Chain.getValue(1);
5113    Count  = Size;
5114    MVT CVT = Count.getValueType();
5115    SDValue Left = DAG.getNode(ISD::AND, CVT, Count,
5116                               DAG.getConstant((AVT == MVT::i64) ? 7 : 3, CVT));
5117    Chain  = DAG.getCopyToReg(Chain, (CVT == MVT::i64) ? X86::RCX : X86::ECX,
5118                              Left, InFlag);
5119    InFlag = Chain.getValue(1);
5120    Tys = DAG.getVTList(MVT::Other, MVT::Flag);
5121    Ops.clear();
5122    Ops.push_back(Chain);
5123    Ops.push_back(DAG.getValueType(MVT::i8));
5124    Ops.push_back(InFlag);
5125    Chain  = DAG.getNode(X86ISD::REP_STOS, Tys, &Ops[0], Ops.size());
5126  } else if (BytesLeft) {
5127    // Handle the last 1 - 7 bytes.
5128    unsigned Offset = SizeVal - BytesLeft;
5129    MVT AddrVT = Dst.getValueType();
5130    MVT SizeVT = Size.getValueType();
5131
5132    Chain = DAG.getMemset(Chain,
5133                          DAG.getNode(ISD::ADD, AddrVT, Dst,
5134                                      DAG.getConstant(Offset, AddrVT)),
5135                          Src,
5136                          DAG.getConstant(BytesLeft, SizeVT),
5137                          Align, DstSV, DstSVOff + Offset);
5138  }
5139
5140  // TODO: Use a Tokenfactor, as in memcpy, instead of a single chain.
5141  return Chain;
5142}
5143
5144SDValue
5145X86TargetLowering::EmitTargetCodeForMemcpy(SelectionDAG &DAG,
5146                                           SDValue Chain,
5147                                           SDValue Dst, SDValue Src,
5148                                           SDValue Size, unsigned Align,
5149                                           bool AlwaysInline,
5150                                           const Value *DstSV, uint64_t DstSVOff,
5151                                           const Value *SrcSV, uint64_t SrcSVOff){
5152
5153  // This requires the copy size to be a constant, preferrably
5154  // within a subtarget-specific limit.
5155  ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
5156  if (!ConstantSize)
5157    return SDValue();
5158  uint64_t SizeVal = ConstantSize->getValue();
5159  if (!AlwaysInline && SizeVal > getSubtarget()->getMaxInlineSizeThreshold())
5160    return SDValue();
5161
5162  MVT AVT;
5163  unsigned BytesLeft = 0;
5164  if (Align >= 8 && Subtarget->is64Bit())
5165    AVT = MVT::i64;
5166  else if (Align >= 4)
5167    AVT = MVT::i32;
5168  else if (Align >= 2)
5169    AVT = MVT::i16;
5170  else
5171    AVT = MVT::i8;
5172
5173  unsigned UBytes = AVT.getSizeInBits() / 8;
5174  unsigned CountVal = SizeVal / UBytes;
5175  SDValue Count = DAG.getIntPtrConstant(CountVal);
5176  BytesLeft = SizeVal % UBytes;
5177
5178  SDValue InFlag(0, 0);
5179  Chain  = DAG.getCopyToReg(Chain, Subtarget->is64Bit() ? X86::RCX : X86::ECX,
5180                            Count, InFlag);
5181  InFlag = Chain.getValue(1);
5182  Chain  = DAG.getCopyToReg(Chain, Subtarget->is64Bit() ? X86::RDI : X86::EDI,
5183                            Dst, InFlag);
5184  InFlag = Chain.getValue(1);
5185  Chain  = DAG.getCopyToReg(Chain, Subtarget->is64Bit() ? X86::RSI : X86::ESI,
5186                            Src, InFlag);
5187  InFlag = Chain.getValue(1);
5188
5189  SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
5190  SmallVector<SDValue, 8> Ops;
5191  Ops.push_back(Chain);
5192  Ops.push_back(DAG.getValueType(AVT));
5193  Ops.push_back(InFlag);
5194  SDValue RepMovs = DAG.getNode(X86ISD::REP_MOVS, Tys, &Ops[0], Ops.size());
5195
5196  SmallVector<SDValue, 4> Results;
5197  Results.push_back(RepMovs);
5198  if (BytesLeft) {
5199    // Handle the last 1 - 7 bytes.
5200    unsigned Offset = SizeVal - BytesLeft;
5201    MVT DstVT = Dst.getValueType();
5202    MVT SrcVT = Src.getValueType();
5203    MVT SizeVT = Size.getValueType();
5204    Results.push_back(DAG.getMemcpy(Chain,
5205                                    DAG.getNode(ISD::ADD, DstVT, Dst,
5206                                                DAG.getConstant(Offset, DstVT)),
5207                                    DAG.getNode(ISD::ADD, SrcVT, Src,
5208                                                DAG.getConstant(Offset, SrcVT)),
5209                                    DAG.getConstant(BytesLeft, SizeVT),
5210                                    Align, AlwaysInline,
5211                                    DstSV, DstSVOff + Offset,
5212                                    SrcSV, SrcSVOff + Offset));
5213  }
5214
5215  return DAG.getNode(ISD::TokenFactor, MVT::Other, &Results[0], Results.size());
5216}
5217
5218/// Expand the result of: i64,outchain = READCYCLECOUNTER inchain
5219SDNode *X86TargetLowering::ExpandREADCYCLECOUNTER(SDNode *N, SelectionDAG &DAG){
5220  SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
5221  SDValue TheChain = N->getOperand(0);
5222  SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, Tys, &TheChain, 1);
5223  if (Subtarget->is64Bit()) {
5224    SDValue rax = DAG.getCopyFromReg(rd, X86::RAX, MVT::i64, rd.getValue(1));
5225    SDValue rdx = DAG.getCopyFromReg(rax.getValue(1), X86::RDX,
5226                                       MVT::i64, rax.getValue(2));
5227    SDValue Tmp = DAG.getNode(ISD::SHL, MVT::i64, rdx,
5228                                DAG.getConstant(32, MVT::i8));
5229    SDValue Ops[] = {
5230      DAG.getNode(ISD::OR, MVT::i64, rax, Tmp), rdx.getValue(1)
5231    };
5232
5233    return DAG.getMergeValues(Ops, 2).Val;
5234  }
5235
5236  SDValue eax = DAG.getCopyFromReg(rd, X86::EAX, MVT::i32, rd.getValue(1));
5237  SDValue edx = DAG.getCopyFromReg(eax.getValue(1), X86::EDX,
5238                                       MVT::i32, eax.getValue(2));
5239  // Use a buildpair to merge the two 32-bit values into a 64-bit one.
5240  SDValue Ops[] = { eax, edx };
5241  Ops[0] = DAG.getNode(ISD::BUILD_PAIR, MVT::i64, Ops, 2);
5242
5243  // Use a MERGE_VALUES to return the value and chain.
5244  Ops[1] = edx.getValue(1);
5245  return DAG.getMergeValues(Ops, 2).Val;
5246}
5247
5248SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) {
5249  const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
5250
5251  if (!Subtarget->is64Bit()) {
5252    // vastart just stores the address of the VarArgsFrameIndex slot into the
5253    // memory location argument.
5254    SDValue FR = DAG.getFrameIndex(VarArgsFrameIndex, getPointerTy());
5255    return DAG.getStore(Op.getOperand(0), FR,Op.getOperand(1), SV, 0);
5256  }
5257
5258  // __va_list_tag:
5259  //   gp_offset         (0 - 6 * 8)
5260  //   fp_offset         (48 - 48 + 8 * 16)
5261  //   overflow_arg_area (point to parameters coming in memory).
5262  //   reg_save_area
5263  SmallVector<SDValue, 8> MemOps;
5264  SDValue FIN = Op.getOperand(1);
5265  // Store gp_offset
5266  SDValue Store = DAG.getStore(Op.getOperand(0),
5267                                 DAG.getConstant(VarArgsGPOffset, MVT::i32),
5268                                 FIN, SV, 0);
5269  MemOps.push_back(Store);
5270
5271  // Store fp_offset
5272  FIN = DAG.getNode(ISD::ADD, getPointerTy(), FIN, DAG.getIntPtrConstant(4));
5273  Store = DAG.getStore(Op.getOperand(0),
5274                       DAG.getConstant(VarArgsFPOffset, MVT::i32),
5275                       FIN, SV, 0);
5276  MemOps.push_back(Store);
5277
5278  // Store ptr to overflow_arg_area
5279  FIN = DAG.getNode(ISD::ADD, getPointerTy(), FIN, DAG.getIntPtrConstant(4));
5280  SDValue OVFIN = DAG.getFrameIndex(VarArgsFrameIndex, getPointerTy());
5281  Store = DAG.getStore(Op.getOperand(0), OVFIN, FIN, SV, 0);
5282  MemOps.push_back(Store);
5283
5284  // Store ptr to reg_save_area.
5285  FIN = DAG.getNode(ISD::ADD, getPointerTy(), FIN, DAG.getIntPtrConstant(8));
5286  SDValue RSFIN = DAG.getFrameIndex(RegSaveFrameIndex, getPointerTy());
5287  Store = DAG.getStore(Op.getOperand(0), RSFIN, FIN, SV, 0);
5288  MemOps.push_back(Store);
5289  return DAG.getNode(ISD::TokenFactor, MVT::Other, &MemOps[0], MemOps.size());
5290}
5291
5292SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) {
5293  // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
5294  assert(Subtarget->is64Bit() && "This code only handles 64-bit va_arg!");
5295  SDValue Chain = Op.getOperand(0);
5296  SDValue SrcPtr = Op.getOperand(1);
5297  SDValue SrcSV = Op.getOperand(2);
5298
5299  assert(0 && "VAArgInst is not yet implemented for x86-64!");
5300  abort();
5301  return SDValue();
5302}
5303
5304SDValue X86TargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) {
5305  // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
5306  assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
5307  SDValue Chain = Op.getOperand(0);
5308  SDValue DstPtr = Op.getOperand(1);
5309  SDValue SrcPtr = Op.getOperand(2);
5310  const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
5311  const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
5312
5313  return DAG.getMemcpy(Chain, DstPtr, SrcPtr,
5314                       DAG.getIntPtrConstant(24), 8, false,
5315                       DstSV, 0, SrcSV, 0);
5316}
5317
5318SDValue
5319X86TargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) {
5320  unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getValue();
5321  switch (IntNo) {
5322  default: return SDValue();    // Don't custom lower most intrinsics.
5323  // Comparison intrinsics.
5324  case Intrinsic::x86_sse_comieq_ss:
5325  case Intrinsic::x86_sse_comilt_ss:
5326  case Intrinsic::x86_sse_comile_ss:
5327  case Intrinsic::x86_sse_comigt_ss:
5328  case Intrinsic::x86_sse_comige_ss:
5329  case Intrinsic::x86_sse_comineq_ss:
5330  case Intrinsic::x86_sse_ucomieq_ss:
5331  case Intrinsic::x86_sse_ucomilt_ss:
5332  case Intrinsic::x86_sse_ucomile_ss:
5333  case Intrinsic::x86_sse_ucomigt_ss:
5334  case Intrinsic::x86_sse_ucomige_ss:
5335  case Intrinsic::x86_sse_ucomineq_ss:
5336  case Intrinsic::x86_sse2_comieq_sd:
5337  case Intrinsic::x86_sse2_comilt_sd:
5338  case Intrinsic::x86_sse2_comile_sd:
5339  case Intrinsic::x86_sse2_comigt_sd:
5340  case Intrinsic::x86_sse2_comige_sd:
5341  case Intrinsic::x86_sse2_comineq_sd:
5342  case Intrinsic::x86_sse2_ucomieq_sd:
5343  case Intrinsic::x86_sse2_ucomilt_sd:
5344  case Intrinsic::x86_sse2_ucomile_sd:
5345  case Intrinsic::x86_sse2_ucomigt_sd:
5346  case Intrinsic::x86_sse2_ucomige_sd:
5347  case Intrinsic::x86_sse2_ucomineq_sd: {
5348    unsigned Opc = 0;
5349    ISD::CondCode CC = ISD::SETCC_INVALID;
5350    switch (IntNo) {
5351    default: break;
5352    case Intrinsic::x86_sse_comieq_ss:
5353    case Intrinsic::x86_sse2_comieq_sd:
5354      Opc = X86ISD::COMI;
5355      CC = ISD::SETEQ;
5356      break;
5357    case Intrinsic::x86_sse_comilt_ss:
5358    case Intrinsic::x86_sse2_comilt_sd:
5359      Opc = X86ISD::COMI;
5360      CC = ISD::SETLT;
5361      break;
5362    case Intrinsic::x86_sse_comile_ss:
5363    case Intrinsic::x86_sse2_comile_sd:
5364      Opc = X86ISD::COMI;
5365      CC = ISD::SETLE;
5366      break;
5367    case Intrinsic::x86_sse_comigt_ss:
5368    case Intrinsic::x86_sse2_comigt_sd:
5369      Opc = X86ISD::COMI;
5370      CC = ISD::SETGT;
5371      break;
5372    case Intrinsic::x86_sse_comige_ss:
5373    case Intrinsic::x86_sse2_comige_sd:
5374      Opc = X86ISD::COMI;
5375      CC = ISD::SETGE;
5376      break;
5377    case Intrinsic::x86_sse_comineq_ss:
5378    case Intrinsic::x86_sse2_comineq_sd:
5379      Opc = X86ISD::COMI;
5380      CC = ISD::SETNE;
5381      break;
5382    case Intrinsic::x86_sse_ucomieq_ss:
5383    case Intrinsic::x86_sse2_ucomieq_sd:
5384      Opc = X86ISD::UCOMI;
5385      CC = ISD::SETEQ;
5386      break;
5387    case Intrinsic::x86_sse_ucomilt_ss:
5388    case Intrinsic::x86_sse2_ucomilt_sd:
5389      Opc = X86ISD::UCOMI;
5390      CC = ISD::SETLT;
5391      break;
5392    case Intrinsic::x86_sse_ucomile_ss:
5393    case Intrinsic::x86_sse2_ucomile_sd:
5394      Opc = X86ISD::UCOMI;
5395      CC = ISD::SETLE;
5396      break;
5397    case Intrinsic::x86_sse_ucomigt_ss:
5398    case Intrinsic::x86_sse2_ucomigt_sd:
5399      Opc = X86ISD::UCOMI;
5400      CC = ISD::SETGT;
5401      break;
5402    case Intrinsic::x86_sse_ucomige_ss:
5403    case Intrinsic::x86_sse2_ucomige_sd:
5404      Opc = X86ISD::UCOMI;
5405      CC = ISD::SETGE;
5406      break;
5407    case Intrinsic::x86_sse_ucomineq_ss:
5408    case Intrinsic::x86_sse2_ucomineq_sd:
5409      Opc = X86ISD::UCOMI;
5410      CC = ISD::SETNE;
5411      break;
5412    }
5413
5414    unsigned X86CC;
5415    SDValue LHS = Op.getOperand(1);
5416    SDValue RHS = Op.getOperand(2);
5417    translateX86CC(CC, true, X86CC, LHS, RHS, DAG);
5418
5419    SDValue Cond = DAG.getNode(Opc, MVT::i32, LHS, RHS);
5420    SDValue SetCC = DAG.getNode(X86ISD::SETCC, MVT::i8,
5421                                  DAG.getConstant(X86CC, MVT::i8), Cond);
5422    return DAG.getNode(ISD::ANY_EXTEND, MVT::i32, SetCC);
5423  }
5424
5425  // Fix vector shift instructions where the last operand is a non-immediate
5426  // i32 value.
5427  case Intrinsic::x86_sse2_pslli_w:
5428  case Intrinsic::x86_sse2_pslli_d:
5429  case Intrinsic::x86_sse2_pslli_q:
5430  case Intrinsic::x86_sse2_psrli_w:
5431  case Intrinsic::x86_sse2_psrli_d:
5432  case Intrinsic::x86_sse2_psrli_q:
5433  case Intrinsic::x86_sse2_psrai_w:
5434  case Intrinsic::x86_sse2_psrai_d:
5435  case Intrinsic::x86_mmx_pslli_w:
5436  case Intrinsic::x86_mmx_pslli_d:
5437  case Intrinsic::x86_mmx_pslli_q:
5438  case Intrinsic::x86_mmx_psrli_w:
5439  case Intrinsic::x86_mmx_psrli_d:
5440  case Intrinsic::x86_mmx_psrli_q:
5441  case Intrinsic::x86_mmx_psrai_w:
5442  case Intrinsic::x86_mmx_psrai_d: {
5443    SDValue ShAmt = Op.getOperand(2);
5444    if (isa<ConstantSDNode>(ShAmt))
5445      return SDValue();
5446
5447    unsigned NewIntNo = 0;
5448    MVT ShAmtVT = MVT::v4i32;
5449    switch (IntNo) {
5450    case Intrinsic::x86_sse2_pslli_w:
5451      NewIntNo = Intrinsic::x86_sse2_psll_w;
5452      break;
5453    case Intrinsic::x86_sse2_pslli_d:
5454      NewIntNo = Intrinsic::x86_sse2_psll_d;
5455      break;
5456    case Intrinsic::x86_sse2_pslli_q:
5457      NewIntNo = Intrinsic::x86_sse2_psll_q;
5458      break;
5459    case Intrinsic::x86_sse2_psrli_w:
5460      NewIntNo = Intrinsic::x86_sse2_psrl_w;
5461      break;
5462    case Intrinsic::x86_sse2_psrli_d:
5463      NewIntNo = Intrinsic::x86_sse2_psrl_d;
5464      break;
5465    case Intrinsic::x86_sse2_psrli_q:
5466      NewIntNo = Intrinsic::x86_sse2_psrl_q;
5467      break;
5468    case Intrinsic::x86_sse2_psrai_w:
5469      NewIntNo = Intrinsic::x86_sse2_psra_w;
5470      break;
5471    case Intrinsic::x86_sse2_psrai_d:
5472      NewIntNo = Intrinsic::x86_sse2_psra_d;
5473      break;
5474    default: {
5475      ShAmtVT = MVT::v2i32;
5476      switch (IntNo) {
5477      case Intrinsic::x86_mmx_pslli_w:
5478        NewIntNo = Intrinsic::x86_mmx_psll_w;
5479        break;
5480      case Intrinsic::x86_mmx_pslli_d:
5481        NewIntNo = Intrinsic::x86_mmx_psll_d;
5482        break;
5483      case Intrinsic::x86_mmx_pslli_q:
5484        NewIntNo = Intrinsic::x86_mmx_psll_q;
5485        break;
5486      case Intrinsic::x86_mmx_psrli_w:
5487        NewIntNo = Intrinsic::x86_mmx_psrl_w;
5488        break;
5489      case Intrinsic::x86_mmx_psrli_d:
5490        NewIntNo = Intrinsic::x86_mmx_psrl_d;
5491        break;
5492      case Intrinsic::x86_mmx_psrli_q:
5493        NewIntNo = Intrinsic::x86_mmx_psrl_q;
5494        break;
5495      case Intrinsic::x86_mmx_psrai_w:
5496        NewIntNo = Intrinsic::x86_mmx_psra_w;
5497        break;
5498      case Intrinsic::x86_mmx_psrai_d:
5499        NewIntNo = Intrinsic::x86_mmx_psra_d;
5500        break;
5501      default: abort();  // Can't reach here.
5502      }
5503      break;
5504    }
5505    }
5506    MVT VT = Op.getValueType();
5507    ShAmt = DAG.getNode(ISD::BIT_CONVERT, VT,
5508                        DAG.getNode(ISD::SCALAR_TO_VECTOR, ShAmtVT, ShAmt));
5509    return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, VT,
5510                       DAG.getConstant(NewIntNo, MVT::i32),
5511                       Op.getOperand(1), ShAmt);
5512  }
5513  }
5514}
5515
5516SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) {
5517  // Depths > 0 not supported yet!
5518  if (cast<ConstantSDNode>(Op.getOperand(0))->getValue() > 0)
5519    return SDValue();
5520
5521  // Just load the return address
5522  SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
5523  return DAG.getLoad(getPointerTy(), DAG.getEntryNode(), RetAddrFI, NULL, 0);
5524}
5525
5526SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) {
5527  // Depths > 0 not supported yet!
5528  if (cast<ConstantSDNode>(Op.getOperand(0))->getValue() > 0)
5529    return SDValue();
5530
5531  SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
5532  return DAG.getNode(ISD::SUB, getPointerTy(), RetAddrFI,
5533                     DAG.getIntPtrConstant(!Subtarget->is64Bit() ? 4 : 8));
5534}
5535
5536SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
5537                                                       SelectionDAG &DAG) {
5538  // Is not yet supported on x86-64
5539  if (Subtarget->is64Bit())
5540    return SDValue();
5541
5542  return DAG.getIntPtrConstant(8);
5543}
5544
5545SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG)
5546{
5547  assert(!Subtarget->is64Bit() &&
5548         "Lowering of eh_return builtin is not supported yet on x86-64");
5549
5550  MachineFunction &MF = DAG.getMachineFunction();
5551  SDValue Chain     = Op.getOperand(0);
5552  SDValue Offset    = Op.getOperand(1);
5553  SDValue Handler   = Op.getOperand(2);
5554
5555  SDValue Frame = DAG.getRegister(RegInfo->getFrameRegister(MF),
5556                                    getPointerTy());
5557
5558  SDValue StoreAddr = DAG.getNode(ISD::SUB, getPointerTy(), Frame,
5559                                    DAG.getIntPtrConstant(-4UL));
5560  StoreAddr = DAG.getNode(ISD::ADD, getPointerTy(), StoreAddr, Offset);
5561  Chain = DAG.getStore(Chain, Handler, StoreAddr, NULL, 0);
5562  Chain = DAG.getCopyToReg(Chain, X86::ECX, StoreAddr);
5563  MF.getRegInfo().addLiveOut(X86::ECX);
5564
5565  return DAG.getNode(X86ISD::EH_RETURN, MVT::Other,
5566                     Chain, DAG.getRegister(X86::ECX, getPointerTy()));
5567}
5568
5569SDValue X86TargetLowering::LowerTRAMPOLINE(SDValue Op,
5570                                             SelectionDAG &DAG) {
5571  SDValue Root = Op.getOperand(0);
5572  SDValue Trmp = Op.getOperand(1); // trampoline
5573  SDValue FPtr = Op.getOperand(2); // nested function
5574  SDValue Nest = Op.getOperand(3); // 'nest' parameter value
5575
5576  const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
5577
5578  const X86InstrInfo *TII =
5579    ((X86TargetMachine&)getTargetMachine()).getInstrInfo();
5580
5581  if (Subtarget->is64Bit()) {
5582    SDValue OutChains[6];
5583
5584    // Large code-model.
5585
5586    const unsigned char JMP64r  = TII->getBaseOpcodeFor(X86::JMP64r);
5587    const unsigned char MOV64ri = TII->getBaseOpcodeFor(X86::MOV64ri);
5588
5589    const unsigned char N86R10 = RegInfo->getX86RegNum(X86::R10);
5590    const unsigned char N86R11 = RegInfo->getX86RegNum(X86::R11);
5591
5592    const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
5593
5594    // Load the pointer to the nested function into R11.
5595    unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
5596    SDValue Addr = Trmp;
5597    OutChains[0] = DAG.getStore(Root, DAG.getConstant(OpCode, MVT::i16), Addr,
5598                                TrmpAddr, 0);
5599
5600    Addr = DAG.getNode(ISD::ADD, MVT::i64, Trmp, DAG.getConstant(2, MVT::i64));
5601    OutChains[1] = DAG.getStore(Root, FPtr, Addr, TrmpAddr, 2, false, 2);
5602
5603    // Load the 'nest' parameter value into R10.
5604    // R10 is specified in X86CallingConv.td
5605    OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
5606    Addr = DAG.getNode(ISD::ADD, MVT::i64, Trmp, DAG.getConstant(10, MVT::i64));
5607    OutChains[2] = DAG.getStore(Root, DAG.getConstant(OpCode, MVT::i16), Addr,
5608                                TrmpAddr, 10);
5609
5610    Addr = DAG.getNode(ISD::ADD, MVT::i64, Trmp, DAG.getConstant(12, MVT::i64));
5611    OutChains[3] = DAG.getStore(Root, Nest, Addr, TrmpAddr, 12, false, 2);
5612
5613    // Jump to the nested function.
5614    OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
5615    Addr = DAG.getNode(ISD::ADD, MVT::i64, Trmp, DAG.getConstant(20, MVT::i64));
5616    OutChains[4] = DAG.getStore(Root, DAG.getConstant(OpCode, MVT::i16), Addr,
5617                                TrmpAddr, 20);
5618
5619    unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
5620    Addr = DAG.getNode(ISD::ADD, MVT::i64, Trmp, DAG.getConstant(22, MVT::i64));
5621    OutChains[5] = DAG.getStore(Root, DAG.getConstant(ModRM, MVT::i8), Addr,
5622                                TrmpAddr, 22);
5623
5624    SDValue Ops[] =
5625      { Trmp, DAG.getNode(ISD::TokenFactor, MVT::Other, OutChains, 6) };
5626    return DAG.getMergeValues(Ops, 2);
5627  } else {
5628    const Function *Func =
5629      cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
5630    unsigned CC = Func->getCallingConv();
5631    unsigned NestReg;
5632
5633    switch (CC) {
5634    default:
5635      assert(0 && "Unsupported calling convention");
5636    case CallingConv::C:
5637    case CallingConv::X86_StdCall: {
5638      // Pass 'nest' parameter in ECX.
5639      // Must be kept in sync with X86CallingConv.td
5640      NestReg = X86::ECX;
5641
5642      // Check that ECX wasn't needed by an 'inreg' parameter.
5643      const FunctionType *FTy = Func->getFunctionType();
5644      const PAListPtr &Attrs = Func->getParamAttrs();
5645
5646      if (!Attrs.isEmpty() && !Func->isVarArg()) {
5647        unsigned InRegCount = 0;
5648        unsigned Idx = 1;
5649
5650        for (FunctionType::param_iterator I = FTy->param_begin(),
5651             E = FTy->param_end(); I != E; ++I, ++Idx)
5652          if (Attrs.paramHasAttr(Idx, ParamAttr::InReg))
5653            // FIXME: should only count parameters that are lowered to integers.
5654            InRegCount += (getTargetData()->getTypeSizeInBits(*I) + 31) / 32;
5655
5656        if (InRegCount > 2) {
5657          cerr << "Nest register in use - reduce number of inreg parameters!\n";
5658          abort();
5659        }
5660      }
5661      break;
5662    }
5663    case CallingConv::X86_FastCall:
5664      // Pass 'nest' parameter in EAX.
5665      // Must be kept in sync with X86CallingConv.td
5666      NestReg = X86::EAX;
5667      break;
5668    }
5669
5670    SDValue OutChains[4];
5671    SDValue Addr, Disp;
5672
5673    Addr = DAG.getNode(ISD::ADD, MVT::i32, Trmp, DAG.getConstant(10, MVT::i32));
5674    Disp = DAG.getNode(ISD::SUB, MVT::i32, FPtr, Addr);
5675
5676    const unsigned char MOV32ri = TII->getBaseOpcodeFor(X86::MOV32ri);
5677    const unsigned char N86Reg = RegInfo->getX86RegNum(NestReg);
5678    OutChains[0] = DAG.getStore(Root, DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
5679                                Trmp, TrmpAddr, 0);
5680
5681    Addr = DAG.getNode(ISD::ADD, MVT::i32, Trmp, DAG.getConstant(1, MVT::i32));
5682    OutChains[1] = DAG.getStore(Root, Nest, Addr, TrmpAddr, 1, false, 1);
5683
5684    const unsigned char JMP = TII->getBaseOpcodeFor(X86::JMP);
5685    Addr = DAG.getNode(ISD::ADD, MVT::i32, Trmp, DAG.getConstant(5, MVT::i32));
5686    OutChains[2] = DAG.getStore(Root, DAG.getConstant(JMP, MVT::i8), Addr,
5687                                TrmpAddr, 5, false, 1);
5688
5689    Addr = DAG.getNode(ISD::ADD, MVT::i32, Trmp, DAG.getConstant(6, MVT::i32));
5690    OutChains[3] = DAG.getStore(Root, Disp, Addr, TrmpAddr, 6, false, 1);
5691
5692    SDValue Ops[] =
5693      { Trmp, DAG.getNode(ISD::TokenFactor, MVT::Other, OutChains, 4) };
5694    return DAG.getMergeValues(Ops, 2);
5695  }
5696}
5697
5698SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op, SelectionDAG &DAG) {
5699  /*
5700   The rounding mode is in bits 11:10 of FPSR, and has the following
5701   settings:
5702     00 Round to nearest
5703     01 Round to -inf
5704     10 Round to +inf
5705     11 Round to 0
5706
5707  FLT_ROUNDS, on the other hand, expects the following:
5708    -1 Undefined
5709     0 Round to 0
5710     1 Round to nearest
5711     2 Round to +inf
5712     3 Round to -inf
5713
5714  To perform the conversion, we do:
5715    (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
5716  */
5717
5718  MachineFunction &MF = DAG.getMachineFunction();
5719  const TargetMachine &TM = MF.getTarget();
5720  const TargetFrameInfo &TFI = *TM.getFrameInfo();
5721  unsigned StackAlignment = TFI.getStackAlignment();
5722  MVT VT = Op.getValueType();
5723
5724  // Save FP Control Word to stack slot
5725  int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment);
5726  SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
5727
5728  SDValue Chain = DAG.getNode(X86ISD::FNSTCW16m, MVT::Other,
5729                                DAG.getEntryNode(), StackSlot);
5730
5731  // Load FP Control Word from stack slot
5732  SDValue CWD = DAG.getLoad(MVT::i16, Chain, StackSlot, NULL, 0);
5733
5734  // Transform as necessary
5735  SDValue CWD1 =
5736    DAG.getNode(ISD::SRL, MVT::i16,
5737                DAG.getNode(ISD::AND, MVT::i16,
5738                            CWD, DAG.getConstant(0x800, MVT::i16)),
5739                DAG.getConstant(11, MVT::i8));
5740  SDValue CWD2 =
5741    DAG.getNode(ISD::SRL, MVT::i16,
5742                DAG.getNode(ISD::AND, MVT::i16,
5743                            CWD, DAG.getConstant(0x400, MVT::i16)),
5744                DAG.getConstant(9, MVT::i8));
5745
5746  SDValue RetVal =
5747    DAG.getNode(ISD::AND, MVT::i16,
5748                DAG.getNode(ISD::ADD, MVT::i16,
5749                            DAG.getNode(ISD::OR, MVT::i16, CWD1, CWD2),
5750                            DAG.getConstant(1, MVT::i16)),
5751                DAG.getConstant(3, MVT::i16));
5752
5753
5754  return DAG.getNode((VT.getSizeInBits() < 16 ?
5755                      ISD::TRUNCATE : ISD::ZERO_EXTEND), VT, RetVal);
5756}
5757
5758SDValue X86TargetLowering::LowerCTLZ(SDValue Op, SelectionDAG &DAG) {
5759  MVT VT = Op.getValueType();
5760  MVT OpVT = VT;
5761  unsigned NumBits = VT.getSizeInBits();
5762
5763  Op = Op.getOperand(0);
5764  if (VT == MVT::i8) {
5765    // Zero extend to i32 since there is not an i8 bsr.
5766    OpVT = MVT::i32;
5767    Op = DAG.getNode(ISD::ZERO_EXTEND, OpVT, Op);
5768  }
5769
5770  // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
5771  SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
5772  Op = DAG.getNode(X86ISD::BSR, VTs, Op);
5773
5774  // If src is zero (i.e. bsr sets ZF), returns NumBits.
5775  SmallVector<SDValue, 4> Ops;
5776  Ops.push_back(Op);
5777  Ops.push_back(DAG.getConstant(NumBits+NumBits-1, OpVT));
5778  Ops.push_back(DAG.getConstant(X86::COND_E, MVT::i8));
5779  Ops.push_back(Op.getValue(1));
5780  Op = DAG.getNode(X86ISD::CMOV, OpVT, &Ops[0], 4);
5781
5782  // Finally xor with NumBits-1.
5783  Op = DAG.getNode(ISD::XOR, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
5784
5785  if (VT == MVT::i8)
5786    Op = DAG.getNode(ISD::TRUNCATE, MVT::i8, Op);
5787  return Op;
5788}
5789
5790SDValue X86TargetLowering::LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
5791  MVT VT = Op.getValueType();
5792  MVT OpVT = VT;
5793  unsigned NumBits = VT.getSizeInBits();
5794
5795  Op = Op.getOperand(0);
5796  if (VT == MVT::i8) {
5797    OpVT = MVT::i32;
5798    Op = DAG.getNode(ISD::ZERO_EXTEND, OpVT, Op);
5799  }
5800
5801  // Issue a bsf (scan bits forward) which also sets EFLAGS.
5802  SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
5803  Op = DAG.getNode(X86ISD::BSF, VTs, Op);
5804
5805  // If src is zero (i.e. bsf sets ZF), returns NumBits.
5806  SmallVector<SDValue, 4> Ops;
5807  Ops.push_back(Op);
5808  Ops.push_back(DAG.getConstant(NumBits, OpVT));
5809  Ops.push_back(DAG.getConstant(X86::COND_E, MVT::i8));
5810  Ops.push_back(Op.getValue(1));
5811  Op = DAG.getNode(X86ISD::CMOV, OpVT, &Ops[0], 4);
5812
5813  if (VT == MVT::i8)
5814    Op = DAG.getNode(ISD::TRUNCATE, MVT::i8, Op);
5815  return Op;
5816}
5817
5818SDValue X86TargetLowering::LowerCMP_SWAP(SDValue Op, SelectionDAG &DAG) {
5819  MVT T = Op.getValueType();
5820  unsigned Reg = 0;
5821  unsigned size = 0;
5822  switch(T.getSimpleVT()) {
5823  default:
5824    assert(false && "Invalid value type!");
5825  case MVT::i8:  Reg = X86::AL;  size = 1; break;
5826  case MVT::i16: Reg = X86::AX;  size = 2; break;
5827  case MVT::i32: Reg = X86::EAX; size = 4; break;
5828  case MVT::i64:
5829    if (Subtarget->is64Bit()) {
5830      Reg = X86::RAX; size = 8;
5831    } else //Should go away when LowerType stuff lands
5832      return SDValue(ExpandATOMIC_CMP_SWAP(Op.Val, DAG), 0);
5833    break;
5834  };
5835  SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), Reg,
5836                                    Op.getOperand(3), SDValue());
5837  SDValue Ops[] = { cpIn.getValue(0),
5838                      Op.getOperand(1),
5839                      Op.getOperand(2),
5840                      DAG.getTargetConstant(size, MVT::i8),
5841                      cpIn.getValue(1) };
5842  SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
5843  SDValue Result = DAG.getNode(X86ISD::LCMPXCHG_DAG, Tys, Ops, 5);
5844  SDValue cpOut =
5845    DAG.getCopyFromReg(Result.getValue(0), Reg, T, Result.getValue(1));
5846  return cpOut;
5847}
5848
5849SDNode* X86TargetLowering::ExpandATOMIC_CMP_SWAP(SDNode* Op, SelectionDAG &DAG) {
5850  MVT T = Op->getValueType(0);
5851  assert (T == MVT::i64 && "Only know how to expand i64 Cmp and Swap");
5852  SDValue cpInL, cpInH;
5853  cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, MVT::i32, Op->getOperand(3),
5854                      DAG.getConstant(0, MVT::i32));
5855  cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, MVT::i32, Op->getOperand(3),
5856                      DAG.getConstant(1, MVT::i32));
5857  cpInL = DAG.getCopyToReg(Op->getOperand(0), X86::EAX,
5858                           cpInL, SDValue());
5859  cpInH = DAG.getCopyToReg(cpInL.getValue(0), X86::EDX,
5860                           cpInH, cpInL.getValue(1));
5861  SDValue swapInL, swapInH;
5862  swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, MVT::i32, Op->getOperand(2),
5863                        DAG.getConstant(0, MVT::i32));
5864  swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, MVT::i32, Op->getOperand(2),
5865                        DAG.getConstant(1, MVT::i32));
5866  swapInL = DAG.getCopyToReg(cpInH.getValue(0), X86::EBX,
5867                             swapInL, cpInH.getValue(1));
5868  swapInH = DAG.getCopyToReg(swapInL.getValue(0), X86::ECX,
5869                             swapInH, swapInL.getValue(1));
5870  SDValue Ops[] = { swapInH.getValue(0),
5871                      Op->getOperand(1),
5872                      swapInH.getValue(1)};
5873  SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
5874  SDValue Result = DAG.getNode(X86ISD::LCMPXCHG8_DAG, Tys, Ops, 3);
5875  SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), X86::EAX, MVT::i32,
5876                                        Result.getValue(1));
5877  SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), X86::EDX, MVT::i32,
5878                                        cpOutL.getValue(2));
5879  SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
5880  SDValue ResultVal = DAG.getNode(ISD::BUILD_PAIR, MVT::i64, OpsF, 2);
5881  SDValue Vals[2] = { ResultVal, cpOutH.getValue(1) };
5882  return DAG.getMergeValues(Vals, 2).Val;
5883}
5884
5885SDNode* X86TargetLowering::ExpandATOMIC_LOAD_SUB(SDNode* Op, SelectionDAG &DAG) {
5886  MVT T = Op->getValueType(0);
5887  SDValue negOp = DAG.getNode(ISD::SUB, T,
5888                                DAG.getConstant(0, T), Op->getOperand(2));
5889  return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, Op->getOperand(0),
5890                       Op->getOperand(1), negOp,
5891                       cast<AtomicSDNode>(Op)->getSrcValue(),
5892                       cast<AtomicSDNode>(Op)->getAlignment()).Val;
5893}
5894
5895/// LowerOperation - Provide custom lowering hooks for some operations.
5896///
5897SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) {
5898  switch (Op.getOpcode()) {
5899  default: assert(0 && "Should not custom lower this!");
5900  case ISD::ATOMIC_CMP_SWAP:    return LowerCMP_SWAP(Op,DAG);
5901  case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
5902  case ISD::VECTOR_SHUFFLE:     return LowerVECTOR_SHUFFLE(Op, DAG);
5903  case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
5904  case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
5905  case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
5906  case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
5907  case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
5908  case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
5909  case ISD::ExternalSymbol:     return LowerExternalSymbol(Op, DAG);
5910  case ISD::SHL_PARTS:
5911  case ISD::SRA_PARTS:
5912  case ISD::SRL_PARTS:          return LowerShift(Op, DAG);
5913  case ISD::SINT_TO_FP:         return LowerSINT_TO_FP(Op, DAG);
5914  case ISD::FP_TO_SINT:         return LowerFP_TO_SINT(Op, DAG);
5915  case ISD::FABS:               return LowerFABS(Op, DAG);
5916  case ISD::FNEG:               return LowerFNEG(Op, DAG);
5917  case ISD::FCOPYSIGN:          return LowerFCOPYSIGN(Op, DAG);
5918  case ISD::SETCC:              return LowerSETCC(Op, DAG);
5919  case ISD::VSETCC:             return LowerVSETCC(Op, DAG);
5920  case ISD::SELECT:             return LowerSELECT(Op, DAG);
5921  case ISD::BRCOND:             return LowerBRCOND(Op, DAG);
5922  case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
5923  case ISD::CALL:               return LowerCALL(Op, DAG);
5924  case ISD::RET:                return LowerRET(Op, DAG);
5925  case ISD::FORMAL_ARGUMENTS:   return LowerFORMAL_ARGUMENTS(Op, DAG);
5926  case ISD::VASTART:            return LowerVASTART(Op, DAG);
5927  case ISD::VAARG:              return LowerVAARG(Op, DAG);
5928  case ISD::VACOPY:             return LowerVACOPY(Op, DAG);
5929  case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
5930  case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
5931  case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
5932  case ISD::FRAME_TO_ARGS_OFFSET:
5933                                return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
5934  case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
5935  case ISD::EH_RETURN:          return LowerEH_RETURN(Op, DAG);
5936  case ISD::TRAMPOLINE:         return LowerTRAMPOLINE(Op, DAG);
5937  case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
5938  case ISD::CTLZ:               return LowerCTLZ(Op, DAG);
5939  case ISD::CTTZ:               return LowerCTTZ(Op, DAG);
5940
5941  // FIXME: REMOVE THIS WHEN LegalizeDAGTypes lands.
5942  case ISD::READCYCLECOUNTER:
5943    return SDValue(ExpandREADCYCLECOUNTER(Op.Val, DAG), 0);
5944  }
5945}
5946
5947/// ReplaceNodeResults - Replace a node with an illegal result type
5948/// with a new node built out of custom code.
5949SDNode *X86TargetLowering::ReplaceNodeResults(SDNode *N, SelectionDAG &DAG) {
5950  switch (N->getOpcode()) {
5951  default: assert(0 && "Should not custom lower this!");
5952  case ISD::FP_TO_SINT:         return ExpandFP_TO_SINT(N, DAG);
5953  case ISD::READCYCLECOUNTER:   return ExpandREADCYCLECOUNTER(N, DAG);
5954  case ISD::ATOMIC_CMP_SWAP:    return ExpandATOMIC_CMP_SWAP(N, DAG);
5955  case ISD::ATOMIC_LOAD_SUB:    return ExpandATOMIC_LOAD_SUB(N,DAG);
5956  }
5957}
5958
5959const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
5960  switch (Opcode) {
5961  default: return NULL;
5962  case X86ISD::BSF:                return "X86ISD::BSF";
5963  case X86ISD::BSR:                return "X86ISD::BSR";
5964  case X86ISD::SHLD:               return "X86ISD::SHLD";
5965  case X86ISD::SHRD:               return "X86ISD::SHRD";
5966  case X86ISD::FAND:               return "X86ISD::FAND";
5967  case X86ISD::FOR:                return "X86ISD::FOR";
5968  case X86ISD::FXOR:               return "X86ISD::FXOR";
5969  case X86ISD::FSRL:               return "X86ISD::FSRL";
5970  case X86ISD::FILD:               return "X86ISD::FILD";
5971  case X86ISD::FILD_FLAG:          return "X86ISD::FILD_FLAG";
5972  case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
5973  case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
5974  case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
5975  case X86ISD::FLD:                return "X86ISD::FLD";
5976  case X86ISD::FST:                return "X86ISD::FST";
5977  case X86ISD::CALL:               return "X86ISD::CALL";
5978  case X86ISD::TAILCALL:           return "X86ISD::TAILCALL";
5979  case X86ISD::RDTSC_DAG:          return "X86ISD::RDTSC_DAG";
5980  case X86ISD::CMP:                return "X86ISD::CMP";
5981  case X86ISD::COMI:               return "X86ISD::COMI";
5982  case X86ISD::UCOMI:              return "X86ISD::UCOMI";
5983  case X86ISD::SETCC:              return "X86ISD::SETCC";
5984  case X86ISD::CMOV:               return "X86ISD::CMOV";
5985  case X86ISD::BRCOND:             return "X86ISD::BRCOND";
5986  case X86ISD::RET_FLAG:           return "X86ISD::RET_FLAG";
5987  case X86ISD::REP_STOS:           return "X86ISD::REP_STOS";
5988  case X86ISD::REP_MOVS:           return "X86ISD::REP_MOVS";
5989  case X86ISD::GlobalBaseReg:      return "X86ISD::GlobalBaseReg";
5990  case X86ISD::Wrapper:            return "X86ISD::Wrapper";
5991  case X86ISD::PEXTRB:             return "X86ISD::PEXTRB";
5992  case X86ISD::PEXTRW:             return "X86ISD::PEXTRW";
5993  case X86ISD::INSERTPS:           return "X86ISD::INSERTPS";
5994  case X86ISD::PINSRB:             return "X86ISD::PINSRB";
5995  case X86ISD::PINSRW:             return "X86ISD::PINSRW";
5996  case X86ISD::FMAX:               return "X86ISD::FMAX";
5997  case X86ISD::FMIN:               return "X86ISD::FMIN";
5998  case X86ISD::FRSQRT:             return "X86ISD::FRSQRT";
5999  case X86ISD::FRCP:               return "X86ISD::FRCP";
6000  case X86ISD::TLSADDR:            return "X86ISD::TLSADDR";
6001  case X86ISD::THREAD_POINTER:     return "X86ISD::THREAD_POINTER";
6002  case X86ISD::EH_RETURN:          return "X86ISD::EH_RETURN";
6003  case X86ISD::TC_RETURN:          return "X86ISD::TC_RETURN";
6004  case X86ISD::FNSTCW16m:          return "X86ISD::FNSTCW16m";
6005  case X86ISD::LCMPXCHG_DAG:       return "X86ISD::LCMPXCHG_DAG";
6006  case X86ISD::LCMPXCHG8_DAG:      return "X86ISD::LCMPXCHG8_DAG";
6007  case X86ISD::VZEXT_MOVL:         return "X86ISD::VZEXT_MOVL";
6008  case X86ISD::VZEXT_LOAD:         return "X86ISD::VZEXT_LOAD";
6009  case X86ISD::VSHL:               return "X86ISD::VSHL";
6010  case X86ISD::VSRL:               return "X86ISD::VSRL";
6011  case X86ISD::CMPPD:              return "X86ISD::CMPPD";
6012  case X86ISD::CMPPS:              return "X86ISD::CMPPS";
6013  case X86ISD::PCMPEQB:            return "X86ISD::PCMPEQB";
6014  case X86ISD::PCMPEQW:            return "X86ISD::PCMPEQW";
6015  case X86ISD::PCMPEQD:            return "X86ISD::PCMPEQD";
6016  case X86ISD::PCMPEQQ:            return "X86ISD::PCMPEQQ";
6017  case X86ISD::PCMPGTB:            return "X86ISD::PCMPGTB";
6018  case X86ISD::PCMPGTW:            return "X86ISD::PCMPGTW";
6019  case X86ISD::PCMPGTD:            return "X86ISD::PCMPGTD";
6020  case X86ISD::PCMPGTQ:            return "X86ISD::PCMPGTQ";
6021  }
6022}
6023
6024// isLegalAddressingMode - Return true if the addressing mode represented
6025// by AM is legal for this target, for a load/store of the specified type.
6026bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
6027                                              const Type *Ty) const {
6028  // X86 supports extremely general addressing modes.
6029
6030  // X86 allows a sign-extended 32-bit immediate field as a displacement.
6031  if (AM.BaseOffs <= -(1LL << 32) || AM.BaseOffs >= (1LL << 32)-1)
6032    return false;
6033
6034  if (AM.BaseGV) {
6035    // We can only fold this if we don't need an extra load.
6036    if (Subtarget->GVRequiresExtraLoad(AM.BaseGV, getTargetMachine(), false))
6037      return false;
6038
6039    // X86-64 only supports addr of globals in small code model.
6040    if (Subtarget->is64Bit()) {
6041      if (getTargetMachine().getCodeModel() != CodeModel::Small)
6042        return false;
6043      // If lower 4G is not available, then we must use rip-relative addressing.
6044      if (AM.BaseOffs || AM.Scale > 1)
6045        return false;
6046    }
6047  }
6048
6049  switch (AM.Scale) {
6050  case 0:
6051  case 1:
6052  case 2:
6053  case 4:
6054  case 8:
6055    // These scales always work.
6056    break;
6057  case 3:
6058  case 5:
6059  case 9:
6060    // These scales are formed with basereg+scalereg.  Only accept if there is
6061    // no basereg yet.
6062    if (AM.HasBaseReg)
6063      return false;
6064    break;
6065  default:  // Other stuff never works.
6066    return false;
6067  }
6068
6069  return true;
6070}
6071
6072
6073bool X86TargetLowering::isTruncateFree(const Type *Ty1, const Type *Ty2) const {
6074  if (!Ty1->isInteger() || !Ty2->isInteger())
6075    return false;
6076  unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
6077  unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
6078  if (NumBits1 <= NumBits2)
6079    return false;
6080  return Subtarget->is64Bit() || NumBits1 < 64;
6081}
6082
6083bool X86TargetLowering::isTruncateFree(MVT VT1, MVT VT2) const {
6084  if (!VT1.isInteger() || !VT2.isInteger())
6085    return false;
6086  unsigned NumBits1 = VT1.getSizeInBits();
6087  unsigned NumBits2 = VT2.getSizeInBits();
6088  if (NumBits1 <= NumBits2)
6089    return false;
6090  return Subtarget->is64Bit() || NumBits1 < 64;
6091}
6092
6093/// isShuffleMaskLegal - Targets can use this to indicate that they only
6094/// support *some* VECTOR_SHUFFLE operations, those with specific masks.
6095/// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
6096/// are assumed to be legal.
6097bool
6098X86TargetLowering::isShuffleMaskLegal(SDValue Mask, MVT VT) const {
6099  // Only do shuffles on 128-bit vector types for now.
6100  if (VT.getSizeInBits() == 64) return false;
6101  return (Mask.Val->getNumOperands() <= 4 ||
6102          isIdentityMask(Mask.Val) ||
6103          isIdentityMask(Mask.Val, true) ||
6104          isSplatMask(Mask.Val)  ||
6105          isPSHUFHW_PSHUFLWMask(Mask.Val) ||
6106          X86::isUNPCKLMask(Mask.Val) ||
6107          X86::isUNPCKHMask(Mask.Val) ||
6108          X86::isUNPCKL_v_undef_Mask(Mask.Val) ||
6109          X86::isUNPCKH_v_undef_Mask(Mask.Val));
6110}
6111
6112bool
6113X86TargetLowering::isVectorClearMaskLegal(const std::vector<SDValue> &BVOps,
6114                                          MVT EVT, SelectionDAG &DAG) const {
6115  unsigned NumElts = BVOps.size();
6116  // Only do shuffles on 128-bit vector types for now.
6117  if (EVT.getSizeInBits() * NumElts == 64) return false;
6118  if (NumElts == 2) return true;
6119  if (NumElts == 4) {
6120    return (isMOVLMask(&BVOps[0], 4)  ||
6121            isCommutedMOVL(&BVOps[0], 4, true) ||
6122            isSHUFPMask(&BVOps[0], 4) ||
6123            isCommutedSHUFP(&BVOps[0], 4));
6124  }
6125  return false;
6126}
6127
6128//===----------------------------------------------------------------------===//
6129//                           X86 Scheduler Hooks
6130//===----------------------------------------------------------------------===//
6131
6132// private utility function
6133MachineBasicBlock *
6134X86TargetLowering::EmitAtomicBitwiseWithCustomInserter(MachineInstr *bInstr,
6135                                                       MachineBasicBlock *MBB,
6136                                                       unsigned regOpc,
6137                                                       unsigned immOpc,
6138                                                       bool invSrc) {
6139  // For the atomic bitwise operator, we generate
6140  //   thisMBB:
6141  //   newMBB:
6142  //     ld  t1 = [bitinstr.addr]
6143  //     op  t2 = t1, [bitinstr.val]
6144  //     mov EAX = t1
6145  //     lcs dest = [bitinstr.addr], t2  [EAX is implicit]
6146  //     bz  newMBB
6147  //     fallthrough -->nextMBB
6148  const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6149  const BasicBlock *LLVM_BB = MBB->getBasicBlock();
6150  MachineFunction::iterator MBBIter = MBB;
6151  ++MBBIter;
6152
6153  /// First build the CFG
6154  MachineFunction *F = MBB->getParent();
6155  MachineBasicBlock *thisMBB = MBB;
6156  MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
6157  MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
6158  F->insert(MBBIter, newMBB);
6159  F->insert(MBBIter, nextMBB);
6160
6161  // Move all successors to thisMBB to nextMBB
6162  nextMBB->transferSuccessors(thisMBB);
6163
6164  // Update thisMBB to fall through to newMBB
6165  thisMBB->addSuccessor(newMBB);
6166
6167  // newMBB jumps to itself and fall through to nextMBB
6168  newMBB->addSuccessor(nextMBB);
6169  newMBB->addSuccessor(newMBB);
6170
6171  // Insert instructions into newMBB based on incoming instruction
6172  assert(bInstr->getNumOperands() < 8 && "unexpected number of operands");
6173  MachineOperand& destOper = bInstr->getOperand(0);
6174  MachineOperand* argOpers[6];
6175  int numArgs = bInstr->getNumOperands() - 1;
6176  for (int i=0; i < numArgs; ++i)
6177    argOpers[i] = &bInstr->getOperand(i+1);
6178
6179  // x86 address has 4 operands: base, index, scale, and displacement
6180  int lastAddrIndx = 3; // [0,3]
6181  int valArgIndx = 4;
6182
6183  unsigned t1 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
6184  MachineInstrBuilder MIB = BuildMI(newMBB, TII->get(X86::MOV32rm), t1);
6185  for (int i=0; i <= lastAddrIndx; ++i)
6186    (*MIB).addOperand(*argOpers[i]);
6187
6188  unsigned tt = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
6189  if (invSrc) {
6190    MIB = BuildMI(newMBB, TII->get(X86::NOT32r), tt).addReg(t1);
6191  }
6192  else
6193    tt = t1;
6194
6195  unsigned t2 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
6196  assert(   (argOpers[valArgIndx]->isReg() || argOpers[valArgIndx]->isImm())
6197         && "invalid operand");
6198  if (argOpers[valArgIndx]->isReg())
6199    MIB = BuildMI(newMBB, TII->get(regOpc), t2);
6200  else
6201    MIB = BuildMI(newMBB, TII->get(immOpc), t2);
6202  MIB.addReg(tt);
6203  (*MIB).addOperand(*argOpers[valArgIndx]);
6204
6205  MIB = BuildMI(newMBB, TII->get(X86::MOV32rr), X86::EAX);
6206  MIB.addReg(t1);
6207
6208  MIB = BuildMI(newMBB, TII->get(X86::LCMPXCHG32));
6209  for (int i=0; i <= lastAddrIndx; ++i)
6210    (*MIB).addOperand(*argOpers[i]);
6211  MIB.addReg(t2);
6212  assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
6213  (*MIB).addMemOperand(*F, *bInstr->memoperands_begin());
6214
6215  MIB = BuildMI(newMBB, TII->get(X86::MOV32rr), destOper.getReg());
6216  MIB.addReg(X86::EAX);
6217
6218  // insert branch
6219  BuildMI(newMBB, TII->get(X86::JNE)).addMBB(newMBB);
6220
6221  F->DeleteMachineInstr(bInstr);   // The pseudo instruction is gone now.
6222  return nextMBB;
6223}
6224
6225// private utility function
6226MachineBasicBlock *
6227X86TargetLowering::EmitAtomicMinMaxWithCustomInserter(MachineInstr *mInstr,
6228                                                      MachineBasicBlock *MBB,
6229                                                      unsigned cmovOpc) {
6230  // For the atomic min/max operator, we generate
6231  //   thisMBB:
6232  //   newMBB:
6233  //     ld t1 = [min/max.addr]
6234  //     mov t2 = [min/max.val]
6235  //     cmp  t1, t2
6236  //     cmov[cond] t2 = t1
6237  //     mov EAX = t1
6238  //     lcs dest = [bitinstr.addr], t2  [EAX is implicit]
6239  //     bz   newMBB
6240  //     fallthrough -->nextMBB
6241  //
6242  const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6243  const BasicBlock *LLVM_BB = MBB->getBasicBlock();
6244  MachineFunction::iterator MBBIter = MBB;
6245  ++MBBIter;
6246
6247  /// First build the CFG
6248  MachineFunction *F = MBB->getParent();
6249  MachineBasicBlock *thisMBB = MBB;
6250  MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
6251  MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
6252  F->insert(MBBIter, newMBB);
6253  F->insert(MBBIter, nextMBB);
6254
6255  // Move all successors to thisMBB to nextMBB
6256  nextMBB->transferSuccessors(thisMBB);
6257
6258  // Update thisMBB to fall through to newMBB
6259  thisMBB->addSuccessor(newMBB);
6260
6261  // newMBB jumps to newMBB and fall through to nextMBB
6262  newMBB->addSuccessor(nextMBB);
6263  newMBB->addSuccessor(newMBB);
6264
6265  // Insert instructions into newMBB based on incoming instruction
6266  assert(mInstr->getNumOperands() < 8 && "unexpected number of operands");
6267  MachineOperand& destOper = mInstr->getOperand(0);
6268  MachineOperand* argOpers[6];
6269  int numArgs = mInstr->getNumOperands() - 1;
6270  for (int i=0; i < numArgs; ++i)
6271    argOpers[i] = &mInstr->getOperand(i+1);
6272
6273  // x86 address has 4 operands: base, index, scale, and displacement
6274  int lastAddrIndx = 3; // [0,3]
6275  int valArgIndx = 4;
6276
6277  unsigned t1 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
6278  MachineInstrBuilder MIB = BuildMI(newMBB, TII->get(X86::MOV32rm), t1);
6279  for (int i=0; i <= lastAddrIndx; ++i)
6280    (*MIB).addOperand(*argOpers[i]);
6281
6282  // We only support register and immediate values
6283  assert(   (argOpers[valArgIndx]->isReg() || argOpers[valArgIndx]->isImm())
6284         && "invalid operand");
6285
6286  unsigned t2 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
6287  if (argOpers[valArgIndx]->isReg())
6288    MIB = BuildMI(newMBB, TII->get(X86::MOV32rr), t2);
6289  else
6290    MIB = BuildMI(newMBB, TII->get(X86::MOV32rr), t2);
6291  (*MIB).addOperand(*argOpers[valArgIndx]);
6292
6293  MIB = BuildMI(newMBB, TII->get(X86::MOV32rr), X86::EAX);
6294  MIB.addReg(t1);
6295
6296  MIB = BuildMI(newMBB, TII->get(X86::CMP32rr));
6297  MIB.addReg(t1);
6298  MIB.addReg(t2);
6299
6300  // Generate movc
6301  unsigned t3 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
6302  MIB = BuildMI(newMBB, TII->get(cmovOpc),t3);
6303  MIB.addReg(t2);
6304  MIB.addReg(t1);
6305
6306  // Cmp and exchange if none has modified the memory location
6307  MIB = BuildMI(newMBB, TII->get(X86::LCMPXCHG32));
6308  for (int i=0; i <= lastAddrIndx; ++i)
6309    (*MIB).addOperand(*argOpers[i]);
6310  MIB.addReg(t3);
6311  assert(mInstr->hasOneMemOperand() && "Unexpected number of memoperand");
6312  (*MIB).addMemOperand(*F, *mInstr->memoperands_begin());
6313
6314  MIB = BuildMI(newMBB, TII->get(X86::MOV32rr), destOper.getReg());
6315  MIB.addReg(X86::EAX);
6316
6317  // insert branch
6318  BuildMI(newMBB, TII->get(X86::JNE)).addMBB(newMBB);
6319
6320  F->DeleteMachineInstr(mInstr);   // The pseudo instruction is gone now.
6321  return nextMBB;
6322}
6323
6324
6325MachineBasicBlock *
6326X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
6327                                               MachineBasicBlock *BB) {
6328  const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6329  switch (MI->getOpcode()) {
6330  default: assert(false && "Unexpected instr type to insert");
6331  case X86::CMOV_FR32:
6332  case X86::CMOV_FR64:
6333  case X86::CMOV_V4F32:
6334  case X86::CMOV_V2F64:
6335  case X86::CMOV_V2I64: {
6336    // To "insert" a SELECT_CC instruction, we actually have to insert the
6337    // diamond control-flow pattern.  The incoming instruction knows the
6338    // destination vreg to set, the condition code register to branch on, the
6339    // true/false values to select between, and a branch opcode to use.
6340    const BasicBlock *LLVM_BB = BB->getBasicBlock();
6341    MachineFunction::iterator It = BB;
6342    ++It;
6343
6344    //  thisMBB:
6345    //  ...
6346    //   TrueVal = ...
6347    //   cmpTY ccX, r1, r2
6348    //   bCC copy1MBB
6349    //   fallthrough --> copy0MBB
6350    MachineBasicBlock *thisMBB = BB;
6351    MachineFunction *F = BB->getParent();
6352    MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
6353    MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
6354    unsigned Opc =
6355      X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
6356    BuildMI(BB, TII->get(Opc)).addMBB(sinkMBB);
6357    F->insert(It, copy0MBB);
6358    F->insert(It, sinkMBB);
6359    // Update machine-CFG edges by transferring all successors of the current
6360    // block to the new block which will contain the Phi node for the select.
6361    sinkMBB->transferSuccessors(BB);
6362
6363    // Add the true and fallthrough blocks as its successors.
6364    BB->addSuccessor(copy0MBB);
6365    BB->addSuccessor(sinkMBB);
6366
6367    //  copy0MBB:
6368    //   %FalseValue = ...
6369    //   # fallthrough to sinkMBB
6370    BB = copy0MBB;
6371
6372    // Update machine-CFG edges
6373    BB->addSuccessor(sinkMBB);
6374
6375    //  sinkMBB:
6376    //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
6377    //  ...
6378    BB = sinkMBB;
6379    BuildMI(BB, TII->get(X86::PHI), MI->getOperand(0).getReg())
6380      .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
6381      .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
6382
6383    F->DeleteMachineInstr(MI);   // The pseudo instruction is gone now.
6384    return BB;
6385  }
6386
6387  case X86::FP32_TO_INT16_IN_MEM:
6388  case X86::FP32_TO_INT32_IN_MEM:
6389  case X86::FP32_TO_INT64_IN_MEM:
6390  case X86::FP64_TO_INT16_IN_MEM:
6391  case X86::FP64_TO_INT32_IN_MEM:
6392  case X86::FP64_TO_INT64_IN_MEM:
6393  case X86::FP80_TO_INT16_IN_MEM:
6394  case X86::FP80_TO_INT32_IN_MEM:
6395  case X86::FP80_TO_INT64_IN_MEM: {
6396    // Change the floating point control register to use "round towards zero"
6397    // mode when truncating to an integer value.
6398    MachineFunction *F = BB->getParent();
6399    int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2);
6400    addFrameReference(BuildMI(BB, TII->get(X86::FNSTCW16m)), CWFrameIdx);
6401
6402    // Load the old value of the high byte of the control word...
6403    unsigned OldCW =
6404      F->getRegInfo().createVirtualRegister(X86::GR16RegisterClass);
6405    addFrameReference(BuildMI(BB, TII->get(X86::MOV16rm), OldCW), CWFrameIdx);
6406
6407    // Set the high part to be round to zero...
6408    addFrameReference(BuildMI(BB, TII->get(X86::MOV16mi)), CWFrameIdx)
6409      .addImm(0xC7F);
6410
6411    // Reload the modified control word now...
6412    addFrameReference(BuildMI(BB, TII->get(X86::FLDCW16m)), CWFrameIdx);
6413
6414    // Restore the memory image of control word to original value
6415    addFrameReference(BuildMI(BB, TII->get(X86::MOV16mr)), CWFrameIdx)
6416      .addReg(OldCW);
6417
6418    // Get the X86 opcode to use.
6419    unsigned Opc;
6420    switch (MI->getOpcode()) {
6421    default: assert(0 && "illegal opcode!");
6422    case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
6423    case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
6424    case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
6425    case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
6426    case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
6427    case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
6428    case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
6429    case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
6430    case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
6431    }
6432
6433    X86AddressMode AM;
6434    MachineOperand &Op = MI->getOperand(0);
6435    if (Op.isRegister()) {
6436      AM.BaseType = X86AddressMode::RegBase;
6437      AM.Base.Reg = Op.getReg();
6438    } else {
6439      AM.BaseType = X86AddressMode::FrameIndexBase;
6440      AM.Base.FrameIndex = Op.getIndex();
6441    }
6442    Op = MI->getOperand(1);
6443    if (Op.isImmediate())
6444      AM.Scale = Op.getImm();
6445    Op = MI->getOperand(2);
6446    if (Op.isImmediate())
6447      AM.IndexReg = Op.getImm();
6448    Op = MI->getOperand(3);
6449    if (Op.isGlobalAddress()) {
6450      AM.GV = Op.getGlobal();
6451    } else {
6452      AM.Disp = Op.getImm();
6453    }
6454    addFullAddress(BuildMI(BB, TII->get(Opc)), AM)
6455                      .addReg(MI->getOperand(4).getReg());
6456
6457    // Reload the original control word now.
6458    addFrameReference(BuildMI(BB, TII->get(X86::FLDCW16m)), CWFrameIdx);
6459
6460    F->DeleteMachineInstr(MI);   // The pseudo instruction is gone now.
6461    return BB;
6462  }
6463  case X86::ATOMAND32:
6464    return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
6465                                                       X86::AND32ri);
6466  case X86::ATOMOR32:
6467    return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR32rr,
6468                                                       X86::OR32ri);
6469  case X86::ATOMXOR32:
6470    return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR32rr,
6471                                                       X86::XOR32ri);
6472  case X86::ATOMNAND32:
6473    return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
6474                                               X86::AND32ri, true);
6475  case X86::ATOMMIN32:
6476    return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL32rr);
6477  case X86::ATOMMAX32:
6478    return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG32rr);
6479  case X86::ATOMUMIN32:
6480    return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB32rr);
6481  case X86::ATOMUMAX32:
6482    return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA32rr);
6483  }
6484}
6485
6486//===----------------------------------------------------------------------===//
6487//                           X86 Optimization Hooks
6488//===----------------------------------------------------------------------===//
6489
6490void X86TargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
6491                                                       const APInt &Mask,
6492                                                       APInt &KnownZero,
6493                                                       APInt &KnownOne,
6494                                                       const SelectionDAG &DAG,
6495                                                       unsigned Depth) const {
6496  unsigned Opc = Op.getOpcode();
6497  assert((Opc >= ISD::BUILTIN_OP_END ||
6498          Opc == ISD::INTRINSIC_WO_CHAIN ||
6499          Opc == ISD::INTRINSIC_W_CHAIN ||
6500          Opc == ISD::INTRINSIC_VOID) &&
6501         "Should use MaskedValueIsZero if you don't know whether Op"
6502         " is a target node!");
6503
6504  KnownZero = KnownOne = APInt(Mask.getBitWidth(), 0);   // Don't know anything.
6505  switch (Opc) {
6506  default: break;
6507  case X86ISD::SETCC:
6508    KnownZero |= APInt::getHighBitsSet(Mask.getBitWidth(),
6509                                       Mask.getBitWidth() - 1);
6510    break;
6511  }
6512}
6513
6514/// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
6515/// node is a GlobalAddress + offset.
6516bool X86TargetLowering::isGAPlusOffset(SDNode *N,
6517                                       GlobalValue* &GA, int64_t &Offset) const{
6518  if (N->getOpcode() == X86ISD::Wrapper) {
6519    if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
6520      GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
6521      return true;
6522    }
6523  }
6524  return TargetLowering::isGAPlusOffset(N, GA, Offset);
6525}
6526
6527static bool isBaseAlignmentOfN(unsigned N, SDNode *Base,
6528                               const TargetLowering &TLI) {
6529  GlobalValue *GV;
6530  int64_t Offset = 0;
6531  if (TLI.isGAPlusOffset(Base, GV, Offset))
6532    return (GV->getAlignment() >= N && (Offset % N) == 0);
6533  // DAG combine handles the stack object case.
6534  return false;
6535}
6536
6537static bool EltsFromConsecutiveLoads(SDNode *N, SDValue PermMask,
6538                                     unsigned NumElems, MVT EVT,
6539                                     SDNode *&Base,
6540                                     SelectionDAG &DAG, MachineFrameInfo *MFI,
6541                                     const TargetLowering &TLI) {
6542  Base = NULL;
6543  for (unsigned i = 0; i < NumElems; ++i) {
6544    SDValue Idx = PermMask.getOperand(i);
6545    if (Idx.getOpcode() == ISD::UNDEF) {
6546      if (!Base)
6547        return false;
6548      continue;
6549    }
6550
6551    SDValue Elt = DAG.getShuffleScalarElt(N, i);
6552    if (!Elt.Val ||
6553        (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.Val)))
6554      return false;
6555    if (!Base) {
6556      Base = Elt.Val;
6557      if (Base->getOpcode() == ISD::UNDEF)
6558        return false;
6559      continue;
6560    }
6561    if (Elt.getOpcode() == ISD::UNDEF)
6562      continue;
6563
6564    if (!TLI.isConsecutiveLoad(Elt.Val, Base,
6565                               EVT.getSizeInBits()/8, i, MFI))
6566      return false;
6567  }
6568  return true;
6569}
6570
6571/// PerformShuffleCombine - Combine a vector_shuffle that is equal to
6572/// build_vector load1, load2, load3, load4, <0, 1, 2, 3> into a 128-bit load
6573/// if the load addresses are consecutive, non-overlapping, and in the right
6574/// order.
6575static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
6576                                       const TargetLowering &TLI) {
6577  MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
6578  MVT VT = N->getValueType(0);
6579  MVT EVT = VT.getVectorElementType();
6580  SDValue PermMask = N->getOperand(2);
6581  unsigned NumElems = PermMask.getNumOperands();
6582  SDNode *Base = NULL;
6583  if (!EltsFromConsecutiveLoads(N, PermMask, NumElems, EVT, Base,
6584                                DAG, MFI, TLI))
6585    return SDValue();
6586
6587  LoadSDNode *LD = cast<LoadSDNode>(Base);
6588  if (isBaseAlignmentOfN(16, Base->getOperand(1).Val, TLI))
6589    return DAG.getLoad(VT, LD->getChain(), LD->getBasePtr(), LD->getSrcValue(),
6590                       LD->getSrcValueOffset(), LD->isVolatile());
6591  return DAG.getLoad(VT, LD->getChain(), LD->getBasePtr(), LD->getSrcValue(),
6592                     LD->getSrcValueOffset(), LD->isVolatile(),
6593                     LD->getAlignment());
6594}
6595
6596/// PerformBuildVectorCombine - build_vector 0,(load i64 / f64) -> movq / movsd.
6597static SDValue PerformBuildVectorCombine(SDNode *N, SelectionDAG &DAG,
6598                                           const X86Subtarget *Subtarget,
6599                                           const TargetLowering &TLI) {
6600  unsigned NumOps = N->getNumOperands();
6601
6602  // Ignore single operand BUILD_VECTOR.
6603  if (NumOps == 1)
6604    return SDValue();
6605
6606  MVT VT = N->getValueType(0);
6607  MVT EVT = VT.getVectorElementType();
6608  if ((EVT != MVT::i64 && EVT != MVT::f64) || Subtarget->is64Bit())
6609    // We are looking for load i64 and zero extend. We want to transform
6610    // it before legalizer has a chance to expand it. Also look for i64
6611    // BUILD_PAIR bit casted to f64.
6612    return SDValue();
6613  // This must be an insertion into a zero vector.
6614  SDValue HighElt = N->getOperand(1);
6615  if (!isZeroNode(HighElt))
6616    return SDValue();
6617
6618  // Value must be a load.
6619  SDNode *Base = N->getOperand(0).Val;
6620  if (!isa<LoadSDNode>(Base)) {
6621    if (Base->getOpcode() != ISD::BIT_CONVERT)
6622      return SDValue();
6623    Base = Base->getOperand(0).Val;
6624    if (!isa<LoadSDNode>(Base))
6625      return SDValue();
6626  }
6627
6628  // Transform it into VZEXT_LOAD addr.
6629  LoadSDNode *LD = cast<LoadSDNode>(Base);
6630
6631  // Load must not be an extload.
6632  if (LD->getExtensionType() != ISD::NON_EXTLOAD)
6633    return SDValue();
6634
6635  return DAG.getNode(X86ISD::VZEXT_LOAD, VT, LD->getChain(), LD->getBasePtr());
6636}
6637
6638/// PerformSELECTCombine - Do target-specific dag combines on SELECT nodes.
6639static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
6640                                      const X86Subtarget *Subtarget) {
6641  SDValue Cond = N->getOperand(0);
6642
6643  // If we have SSE[12] support, try to form min/max nodes.
6644  if (Subtarget->hasSSE2() &&
6645      (N->getValueType(0) == MVT::f32 || N->getValueType(0) == MVT::f64)) {
6646    if (Cond.getOpcode() == ISD::SETCC) {
6647      // Get the LHS/RHS of the select.
6648      SDValue LHS = N->getOperand(1);
6649      SDValue RHS = N->getOperand(2);
6650      ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
6651
6652      unsigned Opcode = 0;
6653      if (LHS == Cond.getOperand(0) && RHS == Cond.getOperand(1)) {
6654        switch (CC) {
6655        default: break;
6656        case ISD::SETOLE: // (X <= Y) ? X : Y -> min
6657        case ISD::SETULE:
6658        case ISD::SETLE:
6659          if (!UnsafeFPMath) break;
6660          // FALL THROUGH.
6661        case ISD::SETOLT:  // (X olt/lt Y) ? X : Y -> min
6662        case ISD::SETLT:
6663          Opcode = X86ISD::FMIN;
6664          break;
6665
6666        case ISD::SETOGT: // (X > Y) ? X : Y -> max
6667        case ISD::SETUGT:
6668        case ISD::SETGT:
6669          if (!UnsafeFPMath) break;
6670          // FALL THROUGH.
6671        case ISD::SETUGE:  // (X uge/ge Y) ? X : Y -> max
6672        case ISD::SETGE:
6673          Opcode = X86ISD::FMAX;
6674          break;
6675        }
6676      } else if (LHS == Cond.getOperand(1) && RHS == Cond.getOperand(0)) {
6677        switch (CC) {
6678        default: break;
6679        case ISD::SETOGT: // (X > Y) ? Y : X -> min
6680        case ISD::SETUGT:
6681        case ISD::SETGT:
6682          if (!UnsafeFPMath) break;
6683          // FALL THROUGH.
6684        case ISD::SETUGE:  // (X uge/ge Y) ? Y : X -> min
6685        case ISD::SETGE:
6686          Opcode = X86ISD::FMIN;
6687          break;
6688
6689        case ISD::SETOLE:   // (X <= Y) ? Y : X -> max
6690        case ISD::SETULE:
6691        case ISD::SETLE:
6692          if (!UnsafeFPMath) break;
6693          // FALL THROUGH.
6694        case ISD::SETOLT:   // (X olt/lt Y) ? Y : X -> max
6695        case ISD::SETLT:
6696          Opcode = X86ISD::FMAX;
6697          break;
6698        }
6699      }
6700
6701      if (Opcode)
6702        return DAG.getNode(Opcode, N->getValueType(0), LHS, RHS);
6703    }
6704
6705  }
6706
6707  return SDValue();
6708}
6709
6710/// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
6711static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
6712                                     const X86Subtarget *Subtarget) {
6713  // Turn load->store of MMX types into GPR load/stores.  This avoids clobbering
6714  // the FP state in cases where an emms may be missing.
6715  // A preferable solution to the general problem is to figure out the right
6716  // places to insert EMMS.  This qualifies as a quick hack.
6717  StoreSDNode *St = cast<StoreSDNode>(N);
6718  if (St->getValue().getValueType().isVector() &&
6719      St->getValue().getValueType().getSizeInBits() == 64 &&
6720      isa<LoadSDNode>(St->getValue()) &&
6721      !cast<LoadSDNode>(St->getValue())->isVolatile() &&
6722      St->getChain().hasOneUse() && !St->isVolatile()) {
6723    SDNode* LdVal = St->getValue().Val;
6724    LoadSDNode *Ld = 0;
6725    int TokenFactorIndex = -1;
6726    SmallVector<SDValue, 8> Ops;
6727    SDNode* ChainVal = St->getChain().Val;
6728    // Must be a store of a load.  We currently handle two cases:  the load
6729    // is a direct child, and it's under an intervening TokenFactor.  It is
6730    // possible to dig deeper under nested TokenFactors.
6731    if (ChainVal == LdVal)
6732      Ld = cast<LoadSDNode>(St->getChain());
6733    else if (St->getValue().hasOneUse() &&
6734             ChainVal->getOpcode() == ISD::TokenFactor) {
6735      for (unsigned i=0, e = ChainVal->getNumOperands(); i != e; ++i) {
6736        if (ChainVal->getOperand(i).Val == LdVal) {
6737          TokenFactorIndex = i;
6738          Ld = cast<LoadSDNode>(St->getValue());
6739        } else
6740          Ops.push_back(ChainVal->getOperand(i));
6741      }
6742    }
6743    if (Ld) {
6744      // If we are a 64-bit capable x86, lower to a single movq load/store pair.
6745      if (Subtarget->is64Bit()) {
6746        SDValue NewLd = DAG.getLoad(MVT::i64, Ld->getChain(),
6747                                      Ld->getBasePtr(), Ld->getSrcValue(),
6748                                      Ld->getSrcValueOffset(), Ld->isVolatile(),
6749                                      Ld->getAlignment());
6750        SDValue NewChain = NewLd.getValue(1);
6751        if (TokenFactorIndex != -1) {
6752          Ops.push_back(NewChain);
6753          NewChain = DAG.getNode(ISD::TokenFactor, MVT::Other, &Ops[0],
6754                                 Ops.size());
6755        }
6756        return DAG.getStore(NewChain, NewLd, St->getBasePtr(),
6757                            St->getSrcValue(), St->getSrcValueOffset(),
6758                            St->isVolatile(), St->getAlignment());
6759      }
6760
6761      // Otherwise, lower to two 32-bit copies.
6762      SDValue LoAddr = Ld->getBasePtr();
6763      SDValue HiAddr = DAG.getNode(ISD::ADD, MVT::i32, LoAddr,
6764                                     DAG.getConstant(4, MVT::i32));
6765
6766      SDValue LoLd = DAG.getLoad(MVT::i32, Ld->getChain(), LoAddr,
6767                                   Ld->getSrcValue(), Ld->getSrcValueOffset(),
6768                                   Ld->isVolatile(), Ld->getAlignment());
6769      SDValue HiLd = DAG.getLoad(MVT::i32, Ld->getChain(), HiAddr,
6770                                   Ld->getSrcValue(), Ld->getSrcValueOffset()+4,
6771                                   Ld->isVolatile(),
6772                                   MinAlign(Ld->getAlignment(), 4));
6773
6774      SDValue NewChain = LoLd.getValue(1);
6775      if (TokenFactorIndex != -1) {
6776        Ops.push_back(LoLd);
6777        Ops.push_back(HiLd);
6778        NewChain = DAG.getNode(ISD::TokenFactor, MVT::Other, &Ops[0],
6779                               Ops.size());
6780      }
6781
6782      LoAddr = St->getBasePtr();
6783      HiAddr = DAG.getNode(ISD::ADD, MVT::i32, LoAddr,
6784                           DAG.getConstant(4, MVT::i32));
6785
6786      SDValue LoSt = DAG.getStore(NewChain, LoLd, LoAddr,
6787                          St->getSrcValue(), St->getSrcValueOffset(),
6788                          St->isVolatile(), St->getAlignment());
6789      SDValue HiSt = DAG.getStore(NewChain, HiLd, HiAddr,
6790                                    St->getSrcValue(), St->getSrcValueOffset()+4,
6791                                    St->isVolatile(),
6792                                    MinAlign(St->getAlignment(), 4));
6793      return DAG.getNode(ISD::TokenFactor, MVT::Other, LoSt, HiSt);
6794    }
6795  }
6796  return SDValue();
6797}
6798
6799/// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
6800/// X86ISD::FXOR nodes.
6801static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
6802  assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
6803  // F[X]OR(0.0, x) -> x
6804  // F[X]OR(x, 0.0) -> x
6805  if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
6806    if (C->getValueAPF().isPosZero())
6807      return N->getOperand(1);
6808  if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
6809    if (C->getValueAPF().isPosZero())
6810      return N->getOperand(0);
6811  return SDValue();
6812}
6813
6814/// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
6815static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
6816  // FAND(0.0, x) -> 0.0
6817  // FAND(x, 0.0) -> 0.0
6818  if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
6819    if (C->getValueAPF().isPosZero())
6820      return N->getOperand(0);
6821  if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
6822    if (C->getValueAPF().isPosZero())
6823      return N->getOperand(1);
6824  return SDValue();
6825}
6826
6827
6828SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
6829                                               DAGCombinerInfo &DCI) const {
6830  SelectionDAG &DAG = DCI.DAG;
6831  switch (N->getOpcode()) {
6832  default: break;
6833  case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, *this);
6834  case ISD::BUILD_VECTOR:
6835    return PerformBuildVectorCombine(N, DAG, Subtarget, *this);
6836  case ISD::SELECT:         return PerformSELECTCombine(N, DAG, Subtarget);
6837  case ISD::STORE:          return PerformSTORECombine(N, DAG, Subtarget);
6838  case X86ISD::FXOR:
6839  case X86ISD::FOR:         return PerformFORCombine(N, DAG);
6840  case X86ISD::FAND:        return PerformFANDCombine(N, DAG);
6841  }
6842
6843  return SDValue();
6844}
6845
6846//===----------------------------------------------------------------------===//
6847//                           X86 Inline Assembly Support
6848//===----------------------------------------------------------------------===//
6849
6850/// getConstraintType - Given a constraint letter, return the type of
6851/// constraint it is for this target.
6852X86TargetLowering::ConstraintType
6853X86TargetLowering::getConstraintType(const std::string &Constraint) const {
6854  if (Constraint.size() == 1) {
6855    switch (Constraint[0]) {
6856    case 'A':
6857    case 'f':
6858    case 'r':
6859    case 'R':
6860    case 'l':
6861    case 'q':
6862    case 'Q':
6863    case 'x':
6864    case 'y':
6865    case 'Y':
6866      return C_RegisterClass;
6867    default:
6868      break;
6869    }
6870  }
6871  return TargetLowering::getConstraintType(Constraint);
6872}
6873
6874/// LowerXConstraint - try to replace an X constraint, which matches anything,
6875/// with another that has more specific requirements based on the type of the
6876/// corresponding operand.
6877const char *X86TargetLowering::
6878LowerXConstraint(MVT ConstraintVT) const {
6879  // FP X constraints get lowered to SSE1/2 registers if available, otherwise
6880  // 'f' like normal targets.
6881  if (ConstraintVT.isFloatingPoint()) {
6882    if (Subtarget->hasSSE2())
6883      return "Y";
6884    if (Subtarget->hasSSE1())
6885      return "x";
6886  }
6887
6888  return TargetLowering::LowerXConstraint(ConstraintVT);
6889}
6890
6891/// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
6892/// vector.  If it is invalid, don't add anything to Ops.
6893void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
6894                                                     char Constraint,
6895                                                     std::vector<SDValue>&Ops,
6896                                                     SelectionDAG &DAG) const {
6897  SDValue Result(0, 0);
6898
6899  switch (Constraint) {
6900  default: break;
6901  case 'I':
6902    if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
6903      if (C->getValue() <= 31) {
6904        Result = DAG.getTargetConstant(C->getValue(), Op.getValueType());
6905        break;
6906      }
6907    }
6908    return;
6909  case 'N':
6910    if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
6911      if (C->getValue() <= 255) {
6912        Result = DAG.getTargetConstant(C->getValue(), Op.getValueType());
6913        break;
6914      }
6915    }
6916    return;
6917  case 'i': {
6918    // Literal immediates are always ok.
6919    if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
6920      Result = DAG.getTargetConstant(CST->getValue(), Op.getValueType());
6921      break;
6922    }
6923
6924    // If we are in non-pic codegen mode, we allow the address of a global (with
6925    // an optional displacement) to be used with 'i'.
6926    GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Op);
6927    int64_t Offset = 0;
6928
6929    // Match either (GA) or (GA+C)
6930    if (GA) {
6931      Offset = GA->getOffset();
6932    } else if (Op.getOpcode() == ISD::ADD) {
6933      ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
6934      GA = dyn_cast<GlobalAddressSDNode>(Op.getOperand(0));
6935      if (C && GA) {
6936        Offset = GA->getOffset()+C->getValue();
6937      } else {
6938        C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
6939        GA = dyn_cast<GlobalAddressSDNode>(Op.getOperand(0));
6940        if (C && GA)
6941          Offset = GA->getOffset()+C->getValue();
6942        else
6943          C = 0, GA = 0;
6944      }
6945    }
6946
6947    if (GA) {
6948      // If addressing this global requires a load (e.g. in PIC mode), we can't
6949      // match.
6950      if (Subtarget->GVRequiresExtraLoad(GA->getGlobal(), getTargetMachine(),
6951                                         false))
6952        return;
6953
6954      Op = DAG.getTargetGlobalAddress(GA->getGlobal(), GA->getValueType(0),
6955                                      Offset);
6956      Result = Op;
6957      break;
6958    }
6959
6960    // Otherwise, not valid for this mode.
6961    return;
6962  }
6963  }
6964
6965  if (Result.Val) {
6966    Ops.push_back(Result);
6967    return;
6968  }
6969  return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
6970}
6971
6972std::vector<unsigned> X86TargetLowering::
6973getRegClassForInlineAsmConstraint(const std::string &Constraint,
6974                                  MVT VT) const {
6975  if (Constraint.size() == 1) {
6976    // FIXME: not handling fp-stack yet!
6977    switch (Constraint[0]) {      // GCC X86 Constraint Letters
6978    default: break;  // Unknown constraint letter
6979    case 'A':   // EAX/EDX
6980      if (VT == MVT::i32 || VT == MVT::i64)
6981        return make_vector<unsigned>(X86::EAX, X86::EDX, 0);
6982      break;
6983    case 'q':   // Q_REGS (GENERAL_REGS in 64-bit mode)
6984    case 'Q':   // Q_REGS
6985      if (VT == MVT::i32)
6986        return make_vector<unsigned>(X86::EAX, X86::EDX, X86::ECX, X86::EBX, 0);
6987      else if (VT == MVT::i16)
6988        return make_vector<unsigned>(X86::AX, X86::DX, X86::CX, X86::BX, 0);
6989      else if (VT == MVT::i8)
6990        return make_vector<unsigned>(X86::AL, X86::DL, X86::CL, X86::BL, 0);
6991      else if (VT == MVT::i64)
6992        return make_vector<unsigned>(X86::RAX, X86::RDX, X86::RCX, X86::RBX, 0);
6993      break;
6994    }
6995  }
6996
6997  return std::vector<unsigned>();
6998}
6999
7000std::pair<unsigned, const TargetRegisterClass*>
7001X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
7002                                                MVT VT) const {
7003  // First, see if this is a constraint that directly corresponds to an LLVM
7004  // register class.
7005  if (Constraint.size() == 1) {
7006    // GCC Constraint Letters
7007    switch (Constraint[0]) {
7008    default: break;
7009    case 'r':   // GENERAL_REGS
7010    case 'R':   // LEGACY_REGS
7011    case 'l':   // INDEX_REGS
7012      if (VT == MVT::i64 && Subtarget->is64Bit())
7013        return std::make_pair(0U, X86::GR64RegisterClass);
7014      if (VT == MVT::i32)
7015        return std::make_pair(0U, X86::GR32RegisterClass);
7016      else if (VT == MVT::i16)
7017        return std::make_pair(0U, X86::GR16RegisterClass);
7018      else if (VT == MVT::i8)
7019        return std::make_pair(0U, X86::GR8RegisterClass);
7020      break;
7021    case 'f':  // FP Stack registers.
7022      // If SSE is enabled for this VT, use f80 to ensure the isel moves the
7023      // value to the correct fpstack register class.
7024      if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
7025        return std::make_pair(0U, X86::RFP32RegisterClass);
7026      if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
7027        return std::make_pair(0U, X86::RFP64RegisterClass);
7028      return std::make_pair(0U, X86::RFP80RegisterClass);
7029    case 'y':   // MMX_REGS if MMX allowed.
7030      if (!Subtarget->hasMMX()) break;
7031      return std::make_pair(0U, X86::VR64RegisterClass);
7032      break;
7033    case 'Y':   // SSE_REGS if SSE2 allowed
7034      if (!Subtarget->hasSSE2()) break;
7035      // FALL THROUGH.
7036    case 'x':   // SSE_REGS if SSE1 allowed
7037      if (!Subtarget->hasSSE1()) break;
7038
7039      switch (VT.getSimpleVT()) {
7040      default: break;
7041      // Scalar SSE types.
7042      case MVT::f32:
7043      case MVT::i32:
7044        return std::make_pair(0U, X86::FR32RegisterClass);
7045      case MVT::f64:
7046      case MVT::i64:
7047        return std::make_pair(0U, X86::FR64RegisterClass);
7048      // Vector types.
7049      case MVT::v16i8:
7050      case MVT::v8i16:
7051      case MVT::v4i32:
7052      case MVT::v2i64:
7053      case MVT::v4f32:
7054      case MVT::v2f64:
7055        return std::make_pair(0U, X86::VR128RegisterClass);
7056      }
7057      break;
7058    }
7059  }
7060
7061  // Use the default implementation in TargetLowering to convert the register
7062  // constraint into a member of a register class.
7063  std::pair<unsigned, const TargetRegisterClass*> Res;
7064  Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
7065
7066  // Not found as a standard register?
7067  if (Res.second == 0) {
7068    // GCC calls "st(0)" just plain "st".
7069    if (StringsEqualNoCase("{st}", Constraint)) {
7070      Res.first = X86::ST0;
7071      Res.second = X86::RFP80RegisterClass;
7072    }
7073
7074    return Res;
7075  }
7076
7077  // Otherwise, check to see if this is a register class of the wrong value
7078  // type.  For example, we want to map "{ax},i32" -> {eax}, we don't want it to
7079  // turn into {ax},{dx}.
7080  if (Res.second->hasType(VT))
7081    return Res;   // Correct type already, nothing to do.
7082
7083  // All of the single-register GCC register classes map their values onto
7084  // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp".  If we
7085  // really want an 8-bit or 32-bit register, map to the appropriate register
7086  // class and return the appropriate register.
7087  if (Res.second != X86::GR16RegisterClass)
7088    return Res;
7089
7090  if (VT == MVT::i8) {
7091    unsigned DestReg = 0;
7092    switch (Res.first) {
7093    default: break;
7094    case X86::AX: DestReg = X86::AL; break;
7095    case X86::DX: DestReg = X86::DL; break;
7096    case X86::CX: DestReg = X86::CL; break;
7097    case X86::BX: DestReg = X86::BL; break;
7098    }
7099    if (DestReg) {
7100      Res.first = DestReg;
7101      Res.second = Res.second = X86::GR8RegisterClass;
7102    }
7103  } else if (VT == MVT::i32) {
7104    unsigned DestReg = 0;
7105    switch (Res.first) {
7106    default: break;
7107    case X86::AX: DestReg = X86::EAX; break;
7108    case X86::DX: DestReg = X86::EDX; break;
7109    case X86::CX: DestReg = X86::ECX; break;
7110    case X86::BX: DestReg = X86::EBX; break;
7111    case X86::SI: DestReg = X86::ESI; break;
7112    case X86::DI: DestReg = X86::EDI; break;
7113    case X86::BP: DestReg = X86::EBP; break;
7114    case X86::SP: DestReg = X86::ESP; break;
7115    }
7116    if (DestReg) {
7117      Res.first = DestReg;
7118      Res.second = Res.second = X86::GR32RegisterClass;
7119    }
7120  } else if (VT == MVT::i64) {
7121    unsigned DestReg = 0;
7122    switch (Res.first) {
7123    default: break;
7124    case X86::AX: DestReg = X86::RAX; break;
7125    case X86::DX: DestReg = X86::RDX; break;
7126    case X86::CX: DestReg = X86::RCX; break;
7127    case X86::BX: DestReg = X86::RBX; break;
7128    case X86::SI: DestReg = X86::RSI; break;
7129    case X86::DI: DestReg = X86::RDI; break;
7130    case X86::BP: DestReg = X86::RBP; break;
7131    case X86::SP: DestReg = X86::RSP; break;
7132    }
7133    if (DestReg) {
7134      Res.first = DestReg;
7135      Res.second = Res.second = X86::GR64RegisterClass;
7136    }
7137  }
7138
7139  return Res;
7140}
7141