X86ISelLowering.cpp revision d850ac79b57e6e0bf68ee93a94d0b3dcd9f6ca35
1//===-- X86ISelLowering.cpp - X86 DAG Lowering Implementation -------------===//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file defines the interfaces that X86 uses to lower LLVM code into a
11// selection DAG.
12//
13//===----------------------------------------------------------------------===//
14
15#define DEBUG_TYPE "x86-isel"
16#include "X86.h"
17#include "X86InstrBuilder.h"
18#include "X86ISelLowering.h"
19#include "X86TargetMachine.h"
20#include "X86TargetObjectFile.h"
21#include "llvm/CallingConv.h"
22#include "llvm/Constants.h"
23#include "llvm/DerivedTypes.h"
24#include "llvm/GlobalAlias.h"
25#include "llvm/GlobalVariable.h"
26#include "llvm/Function.h"
27#include "llvm/Instructions.h"
28#include "llvm/Intrinsics.h"
29#include "llvm/LLVMContext.h"
30#include "llvm/CodeGen/MachineFrameInfo.h"
31#include "llvm/CodeGen/MachineFunction.h"
32#include "llvm/CodeGen/MachineInstrBuilder.h"
33#include "llvm/CodeGen/MachineJumpTableInfo.h"
34#include "llvm/CodeGen/MachineModuleInfo.h"
35#include "llvm/CodeGen/MachineRegisterInfo.h"
36#include "llvm/CodeGen/PseudoSourceValue.h"
37#include "llvm/MC/MCAsmInfo.h"
38#include "llvm/MC/MCContext.h"
39#include "llvm/MC/MCExpr.h"
40#include "llvm/MC/MCSymbol.h"
41#include "llvm/ADT/BitVector.h"
42#include "llvm/ADT/SmallSet.h"
43#include "llvm/ADT/Statistic.h"
44#include "llvm/ADT/StringExtras.h"
45#include "llvm/ADT/VectorExtras.h"
46#include "llvm/Support/CommandLine.h"
47#include "llvm/Support/Debug.h"
48#include "llvm/Support/Dwarf.h"
49#include "llvm/Support/ErrorHandling.h"
50#include "llvm/Support/MathExtras.h"
51#include "llvm/Support/raw_ostream.h"
52using namespace llvm;
53using namespace dwarf;
54
55STATISTIC(NumTailCalls, "Number of tail calls");
56
57static cl::opt<bool>
58DisableMMX("disable-mmx", cl::Hidden, cl::desc("Disable use of MMX"));
59
60// Disable16Bit - 16-bit operations typically have a larger encoding than
61// corresponding 32-bit instructions, and 16-bit code is slow on some
62// processors. This is an experimental flag to disable 16-bit operations
63// (which forces them to be Legalized to 32-bit operations).
64static cl::opt<bool>
65Disable16Bit("disable-16bit", cl::Hidden,
66             cl::desc("Disable use of 16-bit instructions"));
67
68// Forward declarations.
69static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
70                       SDValue V2);
71
72static TargetLoweringObjectFile *createTLOF(X86TargetMachine &TM) {
73  switch (TM.getSubtarget<X86Subtarget>().TargetType) {
74  default: llvm_unreachable("unknown subtarget type");
75  case X86Subtarget::isDarwin:
76    if (TM.getSubtarget<X86Subtarget>().is64Bit())
77      return new X8664_MachoTargetObjectFile();
78    return new TargetLoweringObjectFileMachO();
79  case X86Subtarget::isELF:
80   if (TM.getSubtarget<X86Subtarget>().is64Bit())
81     return new X8664_ELFTargetObjectFile(TM);
82    return new X8632_ELFTargetObjectFile(TM);
83  case X86Subtarget::isMingw:
84  case X86Subtarget::isCygwin:
85  case X86Subtarget::isWindows:
86    return new TargetLoweringObjectFileCOFF();
87  }
88}
89
90X86TargetLowering::X86TargetLowering(X86TargetMachine &TM)
91  : TargetLowering(TM, createTLOF(TM)) {
92  Subtarget = &TM.getSubtarget<X86Subtarget>();
93  X86ScalarSSEf64 = Subtarget->hasSSE2();
94  X86ScalarSSEf32 = Subtarget->hasSSE1();
95  X86StackPtr = Subtarget->is64Bit() ? X86::RSP : X86::ESP;
96
97  RegInfo = TM.getRegisterInfo();
98  TD = getTargetData();
99
100  // Set up the TargetLowering object.
101
102  // X86 is weird, it always uses i8 for shift amounts and setcc results.
103  setShiftAmountType(MVT::i8);
104  setBooleanContents(ZeroOrOneBooleanContent);
105  setSchedulingPreference(SchedulingForRegPressure);
106  setStackPointerRegisterToSaveRestore(X86StackPtr);
107
108  if (Subtarget->isTargetDarwin()) {
109    // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
110    setUseUnderscoreSetJmp(false);
111    setUseUnderscoreLongJmp(false);
112  } else if (Subtarget->isTargetMingw()) {
113    // MS runtime is weird: it exports _setjmp, but longjmp!
114    setUseUnderscoreSetJmp(true);
115    setUseUnderscoreLongJmp(false);
116  } else {
117    setUseUnderscoreSetJmp(true);
118    setUseUnderscoreLongJmp(true);
119  }
120
121  // Set up the register classes.
122  addRegisterClass(MVT::i8, X86::GR8RegisterClass);
123  if (!Disable16Bit)
124    addRegisterClass(MVT::i16, X86::GR16RegisterClass);
125  addRegisterClass(MVT::i32, X86::GR32RegisterClass);
126  if (Subtarget->is64Bit())
127    addRegisterClass(MVT::i64, X86::GR64RegisterClass);
128
129  setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
130
131  // We don't accept any truncstore of integer registers.
132  setTruncStoreAction(MVT::i64, MVT::i32, Expand);
133  if (!Disable16Bit)
134    setTruncStoreAction(MVT::i64, MVT::i16, Expand);
135  setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
136  if (!Disable16Bit)
137    setTruncStoreAction(MVT::i32, MVT::i16, Expand);
138  setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
139  setTruncStoreAction(MVT::i16, MVT::i8,  Expand);
140
141  // SETOEQ and SETUNE require checking two conditions.
142  setCondCodeAction(ISD::SETOEQ, MVT::f32, Expand);
143  setCondCodeAction(ISD::SETOEQ, MVT::f64, Expand);
144  setCondCodeAction(ISD::SETOEQ, MVT::f80, Expand);
145  setCondCodeAction(ISD::SETUNE, MVT::f32, Expand);
146  setCondCodeAction(ISD::SETUNE, MVT::f64, Expand);
147  setCondCodeAction(ISD::SETUNE, MVT::f80, Expand);
148
149  // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
150  // operation.
151  setOperationAction(ISD::UINT_TO_FP       , MVT::i1   , Promote);
152  setOperationAction(ISD::UINT_TO_FP       , MVT::i8   , Promote);
153  setOperationAction(ISD::UINT_TO_FP       , MVT::i16  , Promote);
154
155  if (Subtarget->is64Bit()) {
156    setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Promote);
157    setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Expand);
158  } else if (!UseSoftFloat) {
159    if (X86ScalarSSEf64) {
160      // We have an impenetrably clever algorithm for ui64->double only.
161      setOperationAction(ISD::UINT_TO_FP   , MVT::i64  , Custom);
162    }
163    // We have an algorithm for SSE2, and we turn this into a 64-bit
164    // FILD for other targets.
165    setOperationAction(ISD::UINT_TO_FP   , MVT::i32  , Custom);
166  }
167
168  // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
169  // this operation.
170  setOperationAction(ISD::SINT_TO_FP       , MVT::i1   , Promote);
171  setOperationAction(ISD::SINT_TO_FP       , MVT::i8   , Promote);
172
173  if (!UseSoftFloat) {
174    // SSE has no i16 to fp conversion, only i32
175    if (X86ScalarSSEf32) {
176      setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
177      // f32 and f64 cases are Legal, f80 case is not
178      setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
179    } else {
180      setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Custom);
181      setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
182    }
183  } else {
184    setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
185    setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Promote);
186  }
187
188  // In 32-bit mode these are custom lowered.  In 64-bit mode F32 and F64
189  // are Legal, f80 is custom lowered.
190  setOperationAction(ISD::FP_TO_SINT     , MVT::i64  , Custom);
191  setOperationAction(ISD::SINT_TO_FP     , MVT::i64  , Custom);
192
193  // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
194  // this operation.
195  setOperationAction(ISD::FP_TO_SINT       , MVT::i1   , Promote);
196  setOperationAction(ISD::FP_TO_SINT       , MVT::i8   , Promote);
197
198  if (X86ScalarSSEf32) {
199    setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Promote);
200    // f32 and f64 cases are Legal, f80 case is not
201    setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
202  } else {
203    setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Custom);
204    setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
205  }
206
207  // Handle FP_TO_UINT by promoting the destination to a larger signed
208  // conversion.
209  setOperationAction(ISD::FP_TO_UINT       , MVT::i1   , Promote);
210  setOperationAction(ISD::FP_TO_UINT       , MVT::i8   , Promote);
211  setOperationAction(ISD::FP_TO_UINT       , MVT::i16  , Promote);
212
213  if (Subtarget->is64Bit()) {
214    setOperationAction(ISD::FP_TO_UINT     , MVT::i64  , Expand);
215    setOperationAction(ISD::FP_TO_UINT     , MVT::i32  , Promote);
216  } else if (!UseSoftFloat) {
217    if (X86ScalarSSEf32 && !Subtarget->hasSSE3())
218      // Expand FP_TO_UINT into a select.
219      // FIXME: We would like to use a Custom expander here eventually to do
220      // the optimal thing for SSE vs. the default expansion in the legalizer.
221      setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Expand);
222    else
223      // With SSE3 we can use fisttpll to convert to a signed i64; without
224      // SSE, we're stuck with a fistpll.
225      setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Custom);
226  }
227
228  // TODO: when we have SSE, these could be more efficient, by using movd/movq.
229  if (!X86ScalarSSEf64) {
230    setOperationAction(ISD::BIT_CONVERT      , MVT::f32  , Expand);
231    setOperationAction(ISD::BIT_CONVERT      , MVT::i32  , Expand);
232  }
233
234  // Scalar integer divide and remainder are lowered to use operations that
235  // produce two results, to match the available instructions. This exposes
236  // the two-result form to trivial CSE, which is able to combine x/y and x%y
237  // into a single instruction.
238  //
239  // Scalar integer multiply-high is also lowered to use two-result
240  // operations, to match the available instructions. However, plain multiply
241  // (low) operations are left as Legal, as there are single-result
242  // instructions for this in x86. Using the two-result multiply instructions
243  // when both high and low results are needed must be arranged by dagcombine.
244  setOperationAction(ISD::MULHS           , MVT::i8    , Expand);
245  setOperationAction(ISD::MULHU           , MVT::i8    , Expand);
246  setOperationAction(ISD::SDIV            , MVT::i8    , Expand);
247  setOperationAction(ISD::UDIV            , MVT::i8    , Expand);
248  setOperationAction(ISD::SREM            , MVT::i8    , Expand);
249  setOperationAction(ISD::UREM            , MVT::i8    , Expand);
250  setOperationAction(ISD::MULHS           , MVT::i16   , Expand);
251  setOperationAction(ISD::MULHU           , MVT::i16   , Expand);
252  setOperationAction(ISD::SDIV            , MVT::i16   , Expand);
253  setOperationAction(ISD::UDIV            , MVT::i16   , Expand);
254  setOperationAction(ISD::SREM            , MVT::i16   , Expand);
255  setOperationAction(ISD::UREM            , MVT::i16   , Expand);
256  setOperationAction(ISD::MULHS           , MVT::i32   , Expand);
257  setOperationAction(ISD::MULHU           , MVT::i32   , Expand);
258  setOperationAction(ISD::SDIV            , MVT::i32   , Expand);
259  setOperationAction(ISD::UDIV            , MVT::i32   , Expand);
260  setOperationAction(ISD::SREM            , MVT::i32   , Expand);
261  setOperationAction(ISD::UREM            , MVT::i32   , Expand);
262  setOperationAction(ISD::MULHS           , MVT::i64   , Expand);
263  setOperationAction(ISD::MULHU           , MVT::i64   , Expand);
264  setOperationAction(ISD::SDIV            , MVT::i64   , Expand);
265  setOperationAction(ISD::UDIV            , MVT::i64   , Expand);
266  setOperationAction(ISD::SREM            , MVT::i64   , Expand);
267  setOperationAction(ISD::UREM            , MVT::i64   , Expand);
268
269  setOperationAction(ISD::BR_JT            , MVT::Other, Expand);
270  setOperationAction(ISD::BRCOND           , MVT::Other, Custom);
271  setOperationAction(ISD::BR_CC            , MVT::Other, Expand);
272  setOperationAction(ISD::SELECT_CC        , MVT::Other, Expand);
273  if (Subtarget->is64Bit())
274    setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
275  setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16  , Legal);
276  setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8   , Legal);
277  setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1   , Expand);
278  setOperationAction(ISD::FP_ROUND_INREG   , MVT::f32  , Expand);
279  setOperationAction(ISD::FREM             , MVT::f32  , Expand);
280  setOperationAction(ISD::FREM             , MVT::f64  , Expand);
281  setOperationAction(ISD::FREM             , MVT::f80  , Expand);
282  setOperationAction(ISD::FLT_ROUNDS_      , MVT::i32  , Custom);
283
284  setOperationAction(ISD::CTPOP            , MVT::i8   , Expand);
285  setOperationAction(ISD::CTTZ             , MVT::i8   , Custom);
286  setOperationAction(ISD::CTLZ             , MVT::i8   , Custom);
287  setOperationAction(ISD::CTPOP            , MVT::i16  , Expand);
288  if (Disable16Bit) {
289    setOperationAction(ISD::CTTZ           , MVT::i16  , Expand);
290    setOperationAction(ISD::CTLZ           , MVT::i16  , Expand);
291  } else {
292    setOperationAction(ISD::CTTZ           , MVT::i16  , Custom);
293    setOperationAction(ISD::CTLZ           , MVT::i16  , Custom);
294  }
295  setOperationAction(ISD::CTPOP            , MVT::i32  , Expand);
296  setOperationAction(ISD::CTTZ             , MVT::i32  , Custom);
297  setOperationAction(ISD::CTLZ             , MVT::i32  , Custom);
298  if (Subtarget->is64Bit()) {
299    setOperationAction(ISD::CTPOP          , MVT::i64  , Expand);
300    setOperationAction(ISD::CTTZ           , MVT::i64  , Custom);
301    setOperationAction(ISD::CTLZ           , MVT::i64  , Custom);
302  }
303
304  setOperationAction(ISD::READCYCLECOUNTER , MVT::i64  , Custom);
305  setOperationAction(ISD::BSWAP            , MVT::i16  , Expand);
306
307  // These should be promoted to a larger select which is supported.
308  setOperationAction(ISD::SELECT          , MVT::i1   , Promote);
309  // X86 wants to expand cmov itself.
310  setOperationAction(ISD::SELECT          , MVT::i8   , Custom);
311  if (Disable16Bit)
312    setOperationAction(ISD::SELECT        , MVT::i16  , Expand);
313  else
314    setOperationAction(ISD::SELECT        , MVT::i16  , Custom);
315  setOperationAction(ISD::SELECT          , MVT::i32  , Custom);
316  setOperationAction(ISD::SELECT          , MVT::f32  , Custom);
317  setOperationAction(ISD::SELECT          , MVT::f64  , Custom);
318  setOperationAction(ISD::SELECT          , MVT::f80  , Custom);
319  setOperationAction(ISD::SETCC           , MVT::i8   , Custom);
320  if (Disable16Bit)
321    setOperationAction(ISD::SETCC         , MVT::i16  , Expand);
322  else
323    setOperationAction(ISD::SETCC         , MVT::i16  , Custom);
324  setOperationAction(ISD::SETCC           , MVT::i32  , Custom);
325  setOperationAction(ISD::SETCC           , MVT::f32  , Custom);
326  setOperationAction(ISD::SETCC           , MVT::f64  , Custom);
327  setOperationAction(ISD::SETCC           , MVT::f80  , Custom);
328  if (Subtarget->is64Bit()) {
329    setOperationAction(ISD::SELECT        , MVT::i64  , Custom);
330    setOperationAction(ISD::SETCC         , MVT::i64  , Custom);
331  }
332  setOperationAction(ISD::EH_RETURN       , MVT::Other, Custom);
333
334  // Darwin ABI issue.
335  setOperationAction(ISD::ConstantPool    , MVT::i32  , Custom);
336  setOperationAction(ISD::JumpTable       , MVT::i32  , Custom);
337  setOperationAction(ISD::GlobalAddress   , MVT::i32  , Custom);
338  setOperationAction(ISD::GlobalTLSAddress, MVT::i32  , Custom);
339  if (Subtarget->is64Bit())
340    setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
341  setOperationAction(ISD::ExternalSymbol  , MVT::i32  , Custom);
342  setOperationAction(ISD::BlockAddress    , MVT::i32  , Custom);
343  if (Subtarget->is64Bit()) {
344    setOperationAction(ISD::ConstantPool  , MVT::i64  , Custom);
345    setOperationAction(ISD::JumpTable     , MVT::i64  , Custom);
346    setOperationAction(ISD::GlobalAddress , MVT::i64  , Custom);
347    setOperationAction(ISD::ExternalSymbol, MVT::i64  , Custom);
348    setOperationAction(ISD::BlockAddress  , MVT::i64  , Custom);
349  }
350  // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
351  setOperationAction(ISD::SHL_PARTS       , MVT::i32  , Custom);
352  setOperationAction(ISD::SRA_PARTS       , MVT::i32  , Custom);
353  setOperationAction(ISD::SRL_PARTS       , MVT::i32  , Custom);
354  if (Subtarget->is64Bit()) {
355    setOperationAction(ISD::SHL_PARTS     , MVT::i64  , Custom);
356    setOperationAction(ISD::SRA_PARTS     , MVT::i64  , Custom);
357    setOperationAction(ISD::SRL_PARTS     , MVT::i64  , Custom);
358  }
359
360  if (Subtarget->hasSSE1())
361    setOperationAction(ISD::PREFETCH      , MVT::Other, Legal);
362
363  if (!Subtarget->hasSSE2())
364    setOperationAction(ISD::MEMBARRIER    , MVT::Other, Expand);
365
366  // Expand certain atomics
367  setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i8, Custom);
368  setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i16, Custom);
369  setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Custom);
370  setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i64, Custom);
371
372  setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i8, Custom);
373  setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i16, Custom);
374  setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i32, Custom);
375  setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
376
377  if (!Subtarget->is64Bit()) {
378    setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i64, Custom);
379    setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
380    setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i64, Custom);
381    setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i64, Custom);
382    setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i64, Custom);
383    setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i64, Custom);
384    setOperationAction(ISD::ATOMIC_SWAP, MVT::i64, Custom);
385  }
386
387  // FIXME - use subtarget debug flags
388  if (!Subtarget->isTargetDarwin() &&
389      !Subtarget->isTargetELF() &&
390      !Subtarget->isTargetCygMing()) {
391    setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
392  }
393
394  setOperationAction(ISD::EXCEPTIONADDR, MVT::i64, Expand);
395  setOperationAction(ISD::EHSELECTION,   MVT::i64, Expand);
396  setOperationAction(ISD::EXCEPTIONADDR, MVT::i32, Expand);
397  setOperationAction(ISD::EHSELECTION,   MVT::i32, Expand);
398  if (Subtarget->is64Bit()) {
399    setExceptionPointerRegister(X86::RAX);
400    setExceptionSelectorRegister(X86::RDX);
401  } else {
402    setExceptionPointerRegister(X86::EAX);
403    setExceptionSelectorRegister(X86::EDX);
404  }
405  setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
406  setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
407
408  setOperationAction(ISD::TRAMPOLINE, MVT::Other, Custom);
409
410  setOperationAction(ISD::TRAP, MVT::Other, Legal);
411
412  // VASTART needs to be custom lowered to use the VarArgsFrameIndex
413  setOperationAction(ISD::VASTART           , MVT::Other, Custom);
414  setOperationAction(ISD::VAEND             , MVT::Other, Expand);
415  if (Subtarget->is64Bit()) {
416    setOperationAction(ISD::VAARG           , MVT::Other, Custom);
417    setOperationAction(ISD::VACOPY          , MVT::Other, Custom);
418  } else {
419    setOperationAction(ISD::VAARG           , MVT::Other, Expand);
420    setOperationAction(ISD::VACOPY          , MVT::Other, Expand);
421  }
422
423  setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
424  setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
425  if (Subtarget->is64Bit())
426    setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64, Expand);
427  if (Subtarget->isTargetCygMing())
428    setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Custom);
429  else
430    setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
431
432  if (!UseSoftFloat && X86ScalarSSEf64) {
433    // f32 and f64 use SSE.
434    // Set up the FP register classes.
435    addRegisterClass(MVT::f32, X86::FR32RegisterClass);
436    addRegisterClass(MVT::f64, X86::FR64RegisterClass);
437
438    // Use ANDPD to simulate FABS.
439    setOperationAction(ISD::FABS , MVT::f64, Custom);
440    setOperationAction(ISD::FABS , MVT::f32, Custom);
441
442    // Use XORP to simulate FNEG.
443    setOperationAction(ISD::FNEG , MVT::f64, Custom);
444    setOperationAction(ISD::FNEG , MVT::f32, Custom);
445
446    // Use ANDPD and ORPD to simulate FCOPYSIGN.
447    setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
448    setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
449
450    // We don't support sin/cos/fmod
451    setOperationAction(ISD::FSIN , MVT::f64, Expand);
452    setOperationAction(ISD::FCOS , MVT::f64, Expand);
453    setOperationAction(ISD::FSIN , MVT::f32, Expand);
454    setOperationAction(ISD::FCOS , MVT::f32, Expand);
455
456    // Expand FP immediates into loads from the stack, except for the special
457    // cases we handle.
458    addLegalFPImmediate(APFloat(+0.0)); // xorpd
459    addLegalFPImmediate(APFloat(+0.0f)); // xorps
460  } else if (!UseSoftFloat && X86ScalarSSEf32) {
461    // Use SSE for f32, x87 for f64.
462    // Set up the FP register classes.
463    addRegisterClass(MVT::f32, X86::FR32RegisterClass);
464    addRegisterClass(MVT::f64, X86::RFP64RegisterClass);
465
466    // Use ANDPS to simulate FABS.
467    setOperationAction(ISD::FABS , MVT::f32, Custom);
468
469    // Use XORP to simulate FNEG.
470    setOperationAction(ISD::FNEG , MVT::f32, Custom);
471
472    setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
473
474    // Use ANDPS and ORPS to simulate FCOPYSIGN.
475    setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
476    setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
477
478    // We don't support sin/cos/fmod
479    setOperationAction(ISD::FSIN , MVT::f32, Expand);
480    setOperationAction(ISD::FCOS , MVT::f32, Expand);
481
482    // Special cases we handle for FP constants.
483    addLegalFPImmediate(APFloat(+0.0f)); // xorps
484    addLegalFPImmediate(APFloat(+0.0)); // FLD0
485    addLegalFPImmediate(APFloat(+1.0)); // FLD1
486    addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
487    addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
488
489    if (!UnsafeFPMath) {
490      setOperationAction(ISD::FSIN           , MVT::f64  , Expand);
491      setOperationAction(ISD::FCOS           , MVT::f64  , Expand);
492    }
493  } else if (!UseSoftFloat) {
494    // f32 and f64 in x87.
495    // Set up the FP register classes.
496    addRegisterClass(MVT::f64, X86::RFP64RegisterClass);
497    addRegisterClass(MVT::f32, X86::RFP32RegisterClass);
498
499    setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
500    setOperationAction(ISD::UNDEF,     MVT::f32, Expand);
501    setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
502    setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
503
504    if (!UnsafeFPMath) {
505      setOperationAction(ISD::FSIN           , MVT::f64  , Expand);
506      setOperationAction(ISD::FCOS           , MVT::f64  , Expand);
507    }
508    addLegalFPImmediate(APFloat(+0.0)); // FLD0
509    addLegalFPImmediate(APFloat(+1.0)); // FLD1
510    addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
511    addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
512    addLegalFPImmediate(APFloat(+0.0f)); // FLD0
513    addLegalFPImmediate(APFloat(+1.0f)); // FLD1
514    addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
515    addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
516  }
517
518  // Long double always uses X87.
519  if (!UseSoftFloat) {
520    addRegisterClass(MVT::f80, X86::RFP80RegisterClass);
521    setOperationAction(ISD::UNDEF,     MVT::f80, Expand);
522    setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
523    {
524      bool ignored;
525      APFloat TmpFlt(+0.0);
526      TmpFlt.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
527                     &ignored);
528      addLegalFPImmediate(TmpFlt);  // FLD0
529      TmpFlt.changeSign();
530      addLegalFPImmediate(TmpFlt);  // FLD0/FCHS
531      APFloat TmpFlt2(+1.0);
532      TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
533                      &ignored);
534      addLegalFPImmediate(TmpFlt2);  // FLD1
535      TmpFlt2.changeSign();
536      addLegalFPImmediate(TmpFlt2);  // FLD1/FCHS
537    }
538
539    if (!UnsafeFPMath) {
540      setOperationAction(ISD::FSIN           , MVT::f80  , Expand);
541      setOperationAction(ISD::FCOS           , MVT::f80  , Expand);
542    }
543  }
544
545  // Always use a library call for pow.
546  setOperationAction(ISD::FPOW             , MVT::f32  , Expand);
547  setOperationAction(ISD::FPOW             , MVT::f64  , Expand);
548  setOperationAction(ISD::FPOW             , MVT::f80  , Expand);
549
550  setOperationAction(ISD::FLOG, MVT::f80, Expand);
551  setOperationAction(ISD::FLOG2, MVT::f80, Expand);
552  setOperationAction(ISD::FLOG10, MVT::f80, Expand);
553  setOperationAction(ISD::FEXP, MVT::f80, Expand);
554  setOperationAction(ISD::FEXP2, MVT::f80, Expand);
555
556  // First set operation action for all vector types to either promote
557  // (for widening) or expand (for scalarization). Then we will selectively
558  // turn on ones that can be effectively codegen'd.
559  for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
560       VT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++VT) {
561    setOperationAction(ISD::ADD , (MVT::SimpleValueType)VT, Expand);
562    setOperationAction(ISD::SUB , (MVT::SimpleValueType)VT, Expand);
563    setOperationAction(ISD::FADD, (MVT::SimpleValueType)VT, Expand);
564    setOperationAction(ISD::FNEG, (MVT::SimpleValueType)VT, Expand);
565    setOperationAction(ISD::FSUB, (MVT::SimpleValueType)VT, Expand);
566    setOperationAction(ISD::MUL , (MVT::SimpleValueType)VT, Expand);
567    setOperationAction(ISD::FMUL, (MVT::SimpleValueType)VT, Expand);
568    setOperationAction(ISD::SDIV, (MVT::SimpleValueType)VT, Expand);
569    setOperationAction(ISD::UDIV, (MVT::SimpleValueType)VT, Expand);
570    setOperationAction(ISD::FDIV, (MVT::SimpleValueType)VT, Expand);
571    setOperationAction(ISD::SREM, (MVT::SimpleValueType)VT, Expand);
572    setOperationAction(ISD::UREM, (MVT::SimpleValueType)VT, Expand);
573    setOperationAction(ISD::LOAD, (MVT::SimpleValueType)VT, Expand);
574    setOperationAction(ISD::VECTOR_SHUFFLE, (MVT::SimpleValueType)VT, Expand);
575    setOperationAction(ISD::EXTRACT_VECTOR_ELT,(MVT::SimpleValueType)VT,Expand);
576    setOperationAction(ISD::EXTRACT_SUBVECTOR,(MVT::SimpleValueType)VT,Expand);
577    setOperationAction(ISD::INSERT_VECTOR_ELT,(MVT::SimpleValueType)VT, Expand);
578    setOperationAction(ISD::FABS, (MVT::SimpleValueType)VT, Expand);
579    setOperationAction(ISD::FSIN, (MVT::SimpleValueType)VT, Expand);
580    setOperationAction(ISD::FCOS, (MVT::SimpleValueType)VT, Expand);
581    setOperationAction(ISD::FREM, (MVT::SimpleValueType)VT, Expand);
582    setOperationAction(ISD::FPOWI, (MVT::SimpleValueType)VT, Expand);
583    setOperationAction(ISD::FSQRT, (MVT::SimpleValueType)VT, Expand);
584    setOperationAction(ISD::FCOPYSIGN, (MVT::SimpleValueType)VT, Expand);
585    setOperationAction(ISD::SMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
586    setOperationAction(ISD::UMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
587    setOperationAction(ISD::SDIVREM, (MVT::SimpleValueType)VT, Expand);
588    setOperationAction(ISD::UDIVREM, (MVT::SimpleValueType)VT, Expand);
589    setOperationAction(ISD::FPOW, (MVT::SimpleValueType)VT, Expand);
590    setOperationAction(ISD::CTPOP, (MVT::SimpleValueType)VT, Expand);
591    setOperationAction(ISD::CTTZ, (MVT::SimpleValueType)VT, Expand);
592    setOperationAction(ISD::CTLZ, (MVT::SimpleValueType)VT, Expand);
593    setOperationAction(ISD::SHL, (MVT::SimpleValueType)VT, Expand);
594    setOperationAction(ISD::SRA, (MVT::SimpleValueType)VT, Expand);
595    setOperationAction(ISD::SRL, (MVT::SimpleValueType)VT, Expand);
596    setOperationAction(ISD::ROTL, (MVT::SimpleValueType)VT, Expand);
597    setOperationAction(ISD::ROTR, (MVT::SimpleValueType)VT, Expand);
598    setOperationAction(ISD::BSWAP, (MVT::SimpleValueType)VT, Expand);
599    setOperationAction(ISD::VSETCC, (MVT::SimpleValueType)VT, Expand);
600    setOperationAction(ISD::FLOG, (MVT::SimpleValueType)VT, Expand);
601    setOperationAction(ISD::FLOG2, (MVT::SimpleValueType)VT, Expand);
602    setOperationAction(ISD::FLOG10, (MVT::SimpleValueType)VT, Expand);
603    setOperationAction(ISD::FEXP, (MVT::SimpleValueType)VT, Expand);
604    setOperationAction(ISD::FEXP2, (MVT::SimpleValueType)VT, Expand);
605    setOperationAction(ISD::FP_TO_UINT, (MVT::SimpleValueType)VT, Expand);
606    setOperationAction(ISD::FP_TO_SINT, (MVT::SimpleValueType)VT, Expand);
607    setOperationAction(ISD::UINT_TO_FP, (MVT::SimpleValueType)VT, Expand);
608    setOperationAction(ISD::SINT_TO_FP, (MVT::SimpleValueType)VT, Expand);
609    setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,Expand);
610    setOperationAction(ISD::TRUNCATE,  (MVT::SimpleValueType)VT, Expand);
611    setOperationAction(ISD::SIGN_EXTEND,  (MVT::SimpleValueType)VT, Expand);
612    setOperationAction(ISD::ZERO_EXTEND,  (MVT::SimpleValueType)VT, Expand);
613    setOperationAction(ISD::ANY_EXTEND,  (MVT::SimpleValueType)VT, Expand);
614    for (unsigned InnerVT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
615         InnerVT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
616      setTruncStoreAction((MVT::SimpleValueType)VT,
617                          (MVT::SimpleValueType)InnerVT, Expand);
618    setLoadExtAction(ISD::SEXTLOAD, (MVT::SimpleValueType)VT, Expand);
619    setLoadExtAction(ISD::ZEXTLOAD, (MVT::SimpleValueType)VT, Expand);
620    setLoadExtAction(ISD::EXTLOAD, (MVT::SimpleValueType)VT, Expand);
621  }
622
623  // FIXME: In order to prevent SSE instructions being expanded to MMX ones
624  // with -msoft-float, disable use of MMX as well.
625  if (!UseSoftFloat && !DisableMMX && Subtarget->hasMMX()) {
626    addRegisterClass(MVT::v8i8,  X86::VR64RegisterClass);
627    addRegisterClass(MVT::v4i16, X86::VR64RegisterClass);
628    addRegisterClass(MVT::v2i32, X86::VR64RegisterClass);
629    addRegisterClass(MVT::v2f32, X86::VR64RegisterClass);
630    addRegisterClass(MVT::v1i64, X86::VR64RegisterClass);
631
632    setOperationAction(ISD::ADD,                MVT::v8i8,  Legal);
633    setOperationAction(ISD::ADD,                MVT::v4i16, Legal);
634    setOperationAction(ISD::ADD,                MVT::v2i32, Legal);
635    setOperationAction(ISD::ADD,                MVT::v1i64, Legal);
636
637    setOperationAction(ISD::SUB,                MVT::v8i8,  Legal);
638    setOperationAction(ISD::SUB,                MVT::v4i16, Legal);
639    setOperationAction(ISD::SUB,                MVT::v2i32, Legal);
640    setOperationAction(ISD::SUB,                MVT::v1i64, Legal);
641
642    setOperationAction(ISD::MULHS,              MVT::v4i16, Legal);
643    setOperationAction(ISD::MUL,                MVT::v4i16, Legal);
644
645    setOperationAction(ISD::AND,                MVT::v8i8,  Promote);
646    AddPromotedToType (ISD::AND,                MVT::v8i8,  MVT::v1i64);
647    setOperationAction(ISD::AND,                MVT::v4i16, Promote);
648    AddPromotedToType (ISD::AND,                MVT::v4i16, MVT::v1i64);
649    setOperationAction(ISD::AND,                MVT::v2i32, Promote);
650    AddPromotedToType (ISD::AND,                MVT::v2i32, MVT::v1i64);
651    setOperationAction(ISD::AND,                MVT::v1i64, Legal);
652
653    setOperationAction(ISD::OR,                 MVT::v8i8,  Promote);
654    AddPromotedToType (ISD::OR,                 MVT::v8i8,  MVT::v1i64);
655    setOperationAction(ISD::OR,                 MVT::v4i16, Promote);
656    AddPromotedToType (ISD::OR,                 MVT::v4i16, MVT::v1i64);
657    setOperationAction(ISD::OR,                 MVT::v2i32, Promote);
658    AddPromotedToType (ISD::OR,                 MVT::v2i32, MVT::v1i64);
659    setOperationAction(ISD::OR,                 MVT::v1i64, Legal);
660
661    setOperationAction(ISD::XOR,                MVT::v8i8,  Promote);
662    AddPromotedToType (ISD::XOR,                MVT::v8i8,  MVT::v1i64);
663    setOperationAction(ISD::XOR,                MVT::v4i16, Promote);
664    AddPromotedToType (ISD::XOR,                MVT::v4i16, MVT::v1i64);
665    setOperationAction(ISD::XOR,                MVT::v2i32, Promote);
666    AddPromotedToType (ISD::XOR,                MVT::v2i32, MVT::v1i64);
667    setOperationAction(ISD::XOR,                MVT::v1i64, Legal);
668
669    setOperationAction(ISD::LOAD,               MVT::v8i8,  Promote);
670    AddPromotedToType (ISD::LOAD,               MVT::v8i8,  MVT::v1i64);
671    setOperationAction(ISD::LOAD,               MVT::v4i16, Promote);
672    AddPromotedToType (ISD::LOAD,               MVT::v4i16, MVT::v1i64);
673    setOperationAction(ISD::LOAD,               MVT::v2i32, Promote);
674    AddPromotedToType (ISD::LOAD,               MVT::v2i32, MVT::v1i64);
675    setOperationAction(ISD::LOAD,               MVT::v2f32, Promote);
676    AddPromotedToType (ISD::LOAD,               MVT::v2f32, MVT::v1i64);
677    setOperationAction(ISD::LOAD,               MVT::v1i64, Legal);
678
679    setOperationAction(ISD::BUILD_VECTOR,       MVT::v8i8,  Custom);
680    setOperationAction(ISD::BUILD_VECTOR,       MVT::v4i16, Custom);
681    setOperationAction(ISD::BUILD_VECTOR,       MVT::v2i32, Custom);
682    setOperationAction(ISD::BUILD_VECTOR,       MVT::v2f32, Custom);
683    setOperationAction(ISD::BUILD_VECTOR,       MVT::v1i64, Custom);
684
685    setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v8i8,  Custom);
686    setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4i16, Custom);
687    setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2i32, Custom);
688    setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v1i64, Custom);
689
690    setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v2f32, Custom);
691    setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i8,  Custom);
692    setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v4i16, Custom);
693    setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v1i64, Custom);
694
695    setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i16, Custom);
696
697    setOperationAction(ISD::SELECT,             MVT::v8i8, Promote);
698    setOperationAction(ISD::SELECT,             MVT::v4i16, Promote);
699    setOperationAction(ISD::SELECT,             MVT::v2i32, Promote);
700    setOperationAction(ISD::SELECT,             MVT::v1i64, Custom);
701    setOperationAction(ISD::VSETCC,             MVT::v8i8, Custom);
702    setOperationAction(ISD::VSETCC,             MVT::v4i16, Custom);
703    setOperationAction(ISD::VSETCC,             MVT::v2i32, Custom);
704  }
705
706  if (!UseSoftFloat && Subtarget->hasSSE1()) {
707    addRegisterClass(MVT::v4f32, X86::VR128RegisterClass);
708
709    setOperationAction(ISD::FADD,               MVT::v4f32, Legal);
710    setOperationAction(ISD::FSUB,               MVT::v4f32, Legal);
711    setOperationAction(ISD::FMUL,               MVT::v4f32, Legal);
712    setOperationAction(ISD::FDIV,               MVT::v4f32, Legal);
713    setOperationAction(ISD::FSQRT,              MVT::v4f32, Legal);
714    setOperationAction(ISD::FNEG,               MVT::v4f32, Custom);
715    setOperationAction(ISD::LOAD,               MVT::v4f32, Legal);
716    setOperationAction(ISD::BUILD_VECTOR,       MVT::v4f32, Custom);
717    setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4f32, Custom);
718    setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
719    setOperationAction(ISD::SELECT,             MVT::v4f32, Custom);
720    setOperationAction(ISD::VSETCC,             MVT::v4f32, Custom);
721  }
722
723  if (!UseSoftFloat && Subtarget->hasSSE2()) {
724    addRegisterClass(MVT::v2f64, X86::VR128RegisterClass);
725
726    // FIXME: Unfortunately -soft-float and -no-implicit-float means XMM
727    // registers cannot be used even for integer operations.
728    addRegisterClass(MVT::v16i8, X86::VR128RegisterClass);
729    addRegisterClass(MVT::v8i16, X86::VR128RegisterClass);
730    addRegisterClass(MVT::v4i32, X86::VR128RegisterClass);
731    addRegisterClass(MVT::v2i64, X86::VR128RegisterClass);
732
733    setOperationAction(ISD::ADD,                MVT::v16i8, Legal);
734    setOperationAction(ISD::ADD,                MVT::v8i16, Legal);
735    setOperationAction(ISD::ADD,                MVT::v4i32, Legal);
736    setOperationAction(ISD::ADD,                MVT::v2i64, Legal);
737    setOperationAction(ISD::MUL,                MVT::v2i64, Custom);
738    setOperationAction(ISD::SUB,                MVT::v16i8, Legal);
739    setOperationAction(ISD::SUB,                MVT::v8i16, Legal);
740    setOperationAction(ISD::SUB,                MVT::v4i32, Legal);
741    setOperationAction(ISD::SUB,                MVT::v2i64, Legal);
742    setOperationAction(ISD::MUL,                MVT::v8i16, Legal);
743    setOperationAction(ISD::FADD,               MVT::v2f64, Legal);
744    setOperationAction(ISD::FSUB,               MVT::v2f64, Legal);
745    setOperationAction(ISD::FMUL,               MVT::v2f64, Legal);
746    setOperationAction(ISD::FDIV,               MVT::v2f64, Legal);
747    setOperationAction(ISD::FSQRT,              MVT::v2f64, Legal);
748    setOperationAction(ISD::FNEG,               MVT::v2f64, Custom);
749
750    setOperationAction(ISD::VSETCC,             MVT::v2f64, Custom);
751    setOperationAction(ISD::VSETCC,             MVT::v16i8, Custom);
752    setOperationAction(ISD::VSETCC,             MVT::v8i16, Custom);
753    setOperationAction(ISD::VSETCC,             MVT::v4i32, Custom);
754
755    setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v16i8, Custom);
756    setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i16, Custom);
757    setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
758    setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
759    setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
760
761    setOperationAction(ISD::CONCAT_VECTORS,     MVT::v2f64, Custom);
762    setOperationAction(ISD::CONCAT_VECTORS,     MVT::v2i64, Custom);
763    setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i8, Custom);
764    setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i16, Custom);
765    setOperationAction(ISD::CONCAT_VECTORS,     MVT::v4i32, Custom);
766
767    // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
768    for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v2i64; ++i) {
769      EVT VT = (MVT::SimpleValueType)i;
770      // Do not attempt to custom lower non-power-of-2 vectors
771      if (!isPowerOf2_32(VT.getVectorNumElements()))
772        continue;
773      // Do not attempt to custom lower non-128-bit vectors
774      if (!VT.is128BitVector())
775        continue;
776      setOperationAction(ISD::BUILD_VECTOR,
777                         VT.getSimpleVT().SimpleTy, Custom);
778      setOperationAction(ISD::VECTOR_SHUFFLE,
779                         VT.getSimpleVT().SimpleTy, Custom);
780      setOperationAction(ISD::EXTRACT_VECTOR_ELT,
781                         VT.getSimpleVT().SimpleTy, Custom);
782    }
783
784    setOperationAction(ISD::BUILD_VECTOR,       MVT::v2f64, Custom);
785    setOperationAction(ISD::BUILD_VECTOR,       MVT::v2i64, Custom);
786    setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2f64, Custom);
787    setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2i64, Custom);
788    setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2f64, Custom);
789    setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
790
791    if (Subtarget->is64Bit()) {
792      setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
793      setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
794    }
795
796    // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
797    for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v2i64; i++) {
798      MVT::SimpleValueType SVT = (MVT::SimpleValueType)i;
799      EVT VT = SVT;
800
801      // Do not attempt to promote non-128-bit vectors
802      if (!VT.is128BitVector()) {
803        continue;
804      }
805
806      setOperationAction(ISD::AND,    SVT, Promote);
807      AddPromotedToType (ISD::AND,    SVT, MVT::v2i64);
808      setOperationAction(ISD::OR,     SVT, Promote);
809      AddPromotedToType (ISD::OR,     SVT, MVT::v2i64);
810      setOperationAction(ISD::XOR,    SVT, Promote);
811      AddPromotedToType (ISD::XOR,    SVT, MVT::v2i64);
812      setOperationAction(ISD::LOAD,   SVT, Promote);
813      AddPromotedToType (ISD::LOAD,   SVT, MVT::v2i64);
814      setOperationAction(ISD::SELECT, SVT, Promote);
815      AddPromotedToType (ISD::SELECT, SVT, MVT::v2i64);
816    }
817
818    setTruncStoreAction(MVT::f64, MVT::f32, Expand);
819
820    // Custom lower v2i64 and v2f64 selects.
821    setOperationAction(ISD::LOAD,               MVT::v2f64, Legal);
822    setOperationAction(ISD::LOAD,               MVT::v2i64, Legal);
823    setOperationAction(ISD::SELECT,             MVT::v2f64, Custom);
824    setOperationAction(ISD::SELECT,             MVT::v2i64, Custom);
825
826    setOperationAction(ISD::FP_TO_SINT,         MVT::v4i32, Legal);
827    setOperationAction(ISD::SINT_TO_FP,         MVT::v4i32, Legal);
828    if (!DisableMMX && Subtarget->hasMMX()) {
829      setOperationAction(ISD::FP_TO_SINT,         MVT::v2i32, Custom);
830      setOperationAction(ISD::SINT_TO_FP,         MVT::v2i32, Custom);
831    }
832  }
833
834  if (Subtarget->hasSSE41()) {
835    // FIXME: Do we need to handle scalar-to-vector here?
836    setOperationAction(ISD::MUL,                MVT::v4i32, Legal);
837
838    // i8 and i16 vectors are custom , because the source register and source
839    // source memory operand types are not the same width.  f32 vectors are
840    // custom since the immediate controlling the insert encodes additional
841    // information.
842    setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i8, Custom);
843    setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
844    setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
845    setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
846
847    setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
848    setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
849    setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
850    setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
851
852    if (Subtarget->is64Bit()) {
853      setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Legal);
854      setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Legal);
855    }
856  }
857
858  if (Subtarget->hasSSE42()) {
859    setOperationAction(ISD::VSETCC,             MVT::v2i64, Custom);
860  }
861
862  if (!UseSoftFloat && Subtarget->hasAVX()) {
863    addRegisterClass(MVT::v8f32, X86::VR256RegisterClass);
864    addRegisterClass(MVT::v4f64, X86::VR256RegisterClass);
865    addRegisterClass(MVT::v8i32, X86::VR256RegisterClass);
866    addRegisterClass(MVT::v4i64, X86::VR256RegisterClass);
867
868    setOperationAction(ISD::LOAD,               MVT::v8f32, Legal);
869    setOperationAction(ISD::LOAD,               MVT::v8i32, Legal);
870    setOperationAction(ISD::LOAD,               MVT::v4f64, Legal);
871    setOperationAction(ISD::LOAD,               MVT::v4i64, Legal);
872    setOperationAction(ISD::FADD,               MVT::v8f32, Legal);
873    setOperationAction(ISD::FSUB,               MVT::v8f32, Legal);
874    setOperationAction(ISD::FMUL,               MVT::v8f32, Legal);
875    setOperationAction(ISD::FDIV,               MVT::v8f32, Legal);
876    setOperationAction(ISD::FSQRT,              MVT::v8f32, Legal);
877    setOperationAction(ISD::FNEG,               MVT::v8f32, Custom);
878    //setOperationAction(ISD::BUILD_VECTOR,       MVT::v8f32, Custom);
879    //setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v8f32, Custom);
880    //setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8f32, Custom);
881    //setOperationAction(ISD::SELECT,             MVT::v8f32, Custom);
882    //setOperationAction(ISD::VSETCC,             MVT::v8f32, Custom);
883
884    // Operations to consider commented out -v16i16 v32i8
885    //setOperationAction(ISD::ADD,                MVT::v16i16, Legal);
886    setOperationAction(ISD::ADD,                MVT::v8i32, Custom);
887    setOperationAction(ISD::ADD,                MVT::v4i64, Custom);
888    //setOperationAction(ISD::SUB,                MVT::v32i8, Legal);
889    //setOperationAction(ISD::SUB,                MVT::v16i16, Legal);
890    setOperationAction(ISD::SUB,                MVT::v8i32, Custom);
891    setOperationAction(ISD::SUB,                MVT::v4i64, Custom);
892    //setOperationAction(ISD::MUL,                MVT::v16i16, Legal);
893    setOperationAction(ISD::FADD,               MVT::v4f64, Legal);
894    setOperationAction(ISD::FSUB,               MVT::v4f64, Legal);
895    setOperationAction(ISD::FMUL,               MVT::v4f64, Legal);
896    setOperationAction(ISD::FDIV,               MVT::v4f64, Legal);
897    setOperationAction(ISD::FSQRT,              MVT::v4f64, Legal);
898    setOperationAction(ISD::FNEG,               MVT::v4f64, Custom);
899
900    setOperationAction(ISD::VSETCC,             MVT::v4f64, Custom);
901    // setOperationAction(ISD::VSETCC,             MVT::v32i8, Custom);
902    // setOperationAction(ISD::VSETCC,             MVT::v16i16, Custom);
903    setOperationAction(ISD::VSETCC,             MVT::v8i32, Custom);
904
905    // setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v32i8, Custom);
906    // setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v16i16, Custom);
907    // setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i16, Custom);
908    setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i32, Custom);
909    setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8f32, Custom);
910
911    setOperationAction(ISD::BUILD_VECTOR,       MVT::v4f64, Custom);
912    setOperationAction(ISD::BUILD_VECTOR,       MVT::v4i64, Custom);
913    setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4f64, Custom);
914    setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4i64, Custom);
915    setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f64, Custom);
916    setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f64, Custom);
917
918#if 0
919    // Not sure we want to do this since there are no 256-bit integer
920    // operations in AVX
921
922    // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
923    // This includes 256-bit vectors
924    for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v4i64; ++i) {
925      EVT VT = (MVT::SimpleValueType)i;
926
927      // Do not attempt to custom lower non-power-of-2 vectors
928      if (!isPowerOf2_32(VT.getVectorNumElements()))
929        continue;
930
931      setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
932      setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
933      setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
934    }
935
936    if (Subtarget->is64Bit()) {
937      setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i64, Custom);
938      setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i64, Custom);
939    }
940#endif
941
942#if 0
943    // Not sure we want to do this since there are no 256-bit integer
944    // operations in AVX
945
946    // Promote v32i8, v16i16, v8i32 load, select, and, or, xor to v4i64.
947    // Including 256-bit vectors
948    for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v4i64; i++) {
949      EVT VT = (MVT::SimpleValueType)i;
950
951      if (!VT.is256BitVector()) {
952        continue;
953      }
954      setOperationAction(ISD::AND,    VT, Promote);
955      AddPromotedToType (ISD::AND,    VT, MVT::v4i64);
956      setOperationAction(ISD::OR,     VT, Promote);
957      AddPromotedToType (ISD::OR,     VT, MVT::v4i64);
958      setOperationAction(ISD::XOR,    VT, Promote);
959      AddPromotedToType (ISD::XOR,    VT, MVT::v4i64);
960      setOperationAction(ISD::LOAD,   VT, Promote);
961      AddPromotedToType (ISD::LOAD,   VT, MVT::v4i64);
962      setOperationAction(ISD::SELECT, VT, Promote);
963      AddPromotedToType (ISD::SELECT, VT, MVT::v4i64);
964    }
965
966    setTruncStoreAction(MVT::f64, MVT::f32, Expand);
967#endif
968  }
969
970  // We want to custom lower some of our intrinsics.
971  setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
972
973  // Add/Sub/Mul with overflow operations are custom lowered.
974  setOperationAction(ISD::SADDO, MVT::i32, Custom);
975  setOperationAction(ISD::SADDO, MVT::i64, Custom);
976  setOperationAction(ISD::UADDO, MVT::i32, Custom);
977  setOperationAction(ISD::UADDO, MVT::i64, Custom);
978  setOperationAction(ISD::SSUBO, MVT::i32, Custom);
979  setOperationAction(ISD::SSUBO, MVT::i64, Custom);
980  setOperationAction(ISD::USUBO, MVT::i32, Custom);
981  setOperationAction(ISD::USUBO, MVT::i64, Custom);
982  setOperationAction(ISD::SMULO, MVT::i32, Custom);
983  setOperationAction(ISD::SMULO, MVT::i64, Custom);
984
985  if (!Subtarget->is64Bit()) {
986    // These libcalls are not available in 32-bit.
987    setLibcallName(RTLIB::SHL_I128, 0);
988    setLibcallName(RTLIB::SRL_I128, 0);
989    setLibcallName(RTLIB::SRA_I128, 0);
990  }
991
992  // We have target-specific dag combine patterns for the following nodes:
993  setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
994  setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
995  setTargetDAGCombine(ISD::BUILD_VECTOR);
996  setTargetDAGCombine(ISD::SELECT);
997  setTargetDAGCombine(ISD::SHL);
998  setTargetDAGCombine(ISD::SRA);
999  setTargetDAGCombine(ISD::SRL);
1000  setTargetDAGCombine(ISD::OR);
1001  setTargetDAGCombine(ISD::STORE);
1002  setTargetDAGCombine(ISD::MEMBARRIER);
1003  setTargetDAGCombine(ISD::ZERO_EXTEND);
1004  if (Subtarget->is64Bit())
1005    setTargetDAGCombine(ISD::MUL);
1006
1007  computeRegisterProperties();
1008
1009  // FIXME: These should be based on subtarget info. Plus, the values should
1010  // be smaller when we are in optimizing for size mode.
1011  maxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1012  maxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1013  maxStoresPerMemmove = 3; // For @llvm.memmove -> sequence of stores
1014  setPrefLoopAlignment(16);
1015  benefitFromCodePlacementOpt = true;
1016}
1017
1018
1019MVT::SimpleValueType X86TargetLowering::getSetCCResultType(EVT VT) const {
1020  return MVT::i8;
1021}
1022
1023
1024/// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1025/// the desired ByVal argument alignment.
1026static void getMaxByValAlign(const Type *Ty, unsigned &MaxAlign) {
1027  if (MaxAlign == 16)
1028    return;
1029  if (const VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1030    if (VTy->getBitWidth() == 128)
1031      MaxAlign = 16;
1032  } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1033    unsigned EltAlign = 0;
1034    getMaxByValAlign(ATy->getElementType(), EltAlign);
1035    if (EltAlign > MaxAlign)
1036      MaxAlign = EltAlign;
1037  } else if (const StructType *STy = dyn_cast<StructType>(Ty)) {
1038    for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1039      unsigned EltAlign = 0;
1040      getMaxByValAlign(STy->getElementType(i), EltAlign);
1041      if (EltAlign > MaxAlign)
1042        MaxAlign = EltAlign;
1043      if (MaxAlign == 16)
1044        break;
1045    }
1046  }
1047  return;
1048}
1049
1050/// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1051/// function arguments in the caller parameter area. For X86, aggregates
1052/// that contain SSE vectors are placed at 16-byte boundaries while the rest
1053/// are at 4-byte boundaries.
1054unsigned X86TargetLowering::getByValTypeAlignment(const Type *Ty) const {
1055  if (Subtarget->is64Bit()) {
1056    // Max of 8 and alignment of type.
1057    unsigned TyAlign = TD->getABITypeAlignment(Ty);
1058    if (TyAlign > 8)
1059      return TyAlign;
1060    return 8;
1061  }
1062
1063  unsigned Align = 4;
1064  if (Subtarget->hasSSE1())
1065    getMaxByValAlign(Ty, Align);
1066  return Align;
1067}
1068
1069/// getOptimalMemOpType - Returns the target specific optimal type for load
1070/// and store operations as a result of memset, memcpy, and memmove lowering.
1071/// If DstAlign is zero that means it's safe to destination alignment can
1072/// satisfy any constraint. Similarly if SrcAlign is zero it means there
1073/// isn't a need to check it against alignment requirement, probably because
1074/// the source does not need to be loaded. If 'NonScalarIntSafe' is true, that
1075/// means it's safe to return a non-scalar-integer type, e.g. constant string
1076/// source or loaded from memory. It returns EVT::Other if SelectionDAG should
1077/// be responsible for determining it.
1078EVT
1079X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1080                                       unsigned DstAlign, unsigned SrcAlign,
1081                                       bool NonScalarIntSafe,
1082                                       SelectionDAG &DAG) const {
1083  // FIXME: This turns off use of xmm stores for memset/memcpy on targets like
1084  // linux.  This is because the stack realignment code can't handle certain
1085  // cases like PR2962.  This should be removed when PR2962 is fixed.
1086  const Function *F = DAG.getMachineFunction().getFunction();
1087  if (NonScalarIntSafe &&
1088      !F->hasFnAttr(Attribute::NoImplicitFloat)) {
1089    if (Size >= 16 &&
1090        (Subtarget->isUnalignedMemAccessFast() ||
1091         ((DstAlign == 0 || DstAlign >= 16) &&
1092          (SrcAlign == 0 || SrcAlign >= 16))) &&
1093        Subtarget->getStackAlignment() >= 16) {
1094      if (Subtarget->hasSSE2())
1095        return MVT::v4i32;
1096      if (Subtarget->hasSSE1())
1097        return MVT::v4f32;
1098    } else if (Size >= 8 &&
1099               !Subtarget->is64Bit() &&
1100               Subtarget->getStackAlignment() >= 8 &&
1101               Subtarget->hasSSE2())
1102      return MVT::f64;
1103  }
1104  if (Subtarget->is64Bit() && Size >= 8)
1105    return MVT::i64;
1106  return MVT::i32;
1107}
1108
1109/// getJumpTableEncoding - Return the entry encoding for a jump table in the
1110/// current function.  The returned value is a member of the
1111/// MachineJumpTableInfo::JTEntryKind enum.
1112unsigned X86TargetLowering::getJumpTableEncoding() const {
1113  // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1114  // symbol.
1115  if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1116      Subtarget->isPICStyleGOT())
1117    return MachineJumpTableInfo::EK_Custom32;
1118
1119  // Otherwise, use the normal jump table encoding heuristics.
1120  return TargetLowering::getJumpTableEncoding();
1121}
1122
1123/// getPICBaseSymbol - Return the X86-32 PIC base.
1124MCSymbol *
1125X86TargetLowering::getPICBaseSymbol(const MachineFunction *MF,
1126                                    MCContext &Ctx) const {
1127  const MCAsmInfo &MAI = *getTargetMachine().getMCAsmInfo();
1128  return Ctx.GetOrCreateSymbol(Twine(MAI.getPrivateGlobalPrefix())+
1129                               Twine(MF->getFunctionNumber())+"$pb");
1130}
1131
1132
1133const MCExpr *
1134X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1135                                             const MachineBasicBlock *MBB,
1136                                             unsigned uid,MCContext &Ctx) const{
1137  assert(getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1138         Subtarget->isPICStyleGOT());
1139  // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1140  // entries.
1141  return MCSymbolRefExpr::Create(MBB->getSymbol(),
1142                                 MCSymbolRefExpr::VK_GOTOFF, Ctx);
1143}
1144
1145/// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
1146/// jumptable.
1147SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1148                                                    SelectionDAG &DAG) const {
1149  if (!Subtarget->is64Bit())
1150    // This doesn't have DebugLoc associated with it, but is not really the
1151    // same as a Register.
1152    return DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), getPointerTy());
1153  return Table;
1154}
1155
1156/// getPICJumpTableRelocBaseExpr - This returns the relocation base for the
1157/// given PIC jumptable, the same as getPICJumpTableRelocBase, but as an
1158/// MCExpr.
1159const MCExpr *X86TargetLowering::
1160getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1161                             MCContext &Ctx) const {
1162  // X86-64 uses RIP relative addressing based on the jump table label.
1163  if (Subtarget->isPICStyleRIPRel())
1164    return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1165
1166  // Otherwise, the reference is relative to the PIC base.
1167  return MCSymbolRefExpr::Create(getPICBaseSymbol(MF, Ctx), Ctx);
1168}
1169
1170/// getFunctionAlignment - Return the Log2 alignment of this function.
1171unsigned X86TargetLowering::getFunctionAlignment(const Function *F) const {
1172  return F->hasFnAttr(Attribute::OptimizeForSize) ? 0 : 4;
1173}
1174
1175//===----------------------------------------------------------------------===//
1176//               Return Value Calling Convention Implementation
1177//===----------------------------------------------------------------------===//
1178
1179#include "X86GenCallingConv.inc"
1180
1181bool
1182X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv, bool isVarArg,
1183                        const SmallVectorImpl<EVT> &OutTys,
1184                        const SmallVectorImpl<ISD::ArgFlagsTy> &ArgsFlags,
1185                        SelectionDAG &DAG) {
1186  SmallVector<CCValAssign, 16> RVLocs;
1187  CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1188                 RVLocs, *DAG.getContext());
1189  return CCInfo.CheckReturn(OutTys, ArgsFlags, RetCC_X86);
1190}
1191
1192SDValue
1193X86TargetLowering::LowerReturn(SDValue Chain,
1194                               CallingConv::ID CallConv, bool isVarArg,
1195                               const SmallVectorImpl<ISD::OutputArg> &Outs,
1196                               DebugLoc dl, SelectionDAG &DAG) {
1197
1198  SmallVector<CCValAssign, 16> RVLocs;
1199  CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1200                 RVLocs, *DAG.getContext());
1201  CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1202
1203  // Add the regs to the liveout set for the function.
1204  MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
1205  for (unsigned i = 0; i != RVLocs.size(); ++i)
1206    if (RVLocs[i].isRegLoc() && !MRI.isLiveOut(RVLocs[i].getLocReg()))
1207      MRI.addLiveOut(RVLocs[i].getLocReg());
1208
1209  SDValue Flag;
1210
1211  SmallVector<SDValue, 6> RetOps;
1212  RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1213  // Operand #1 = Bytes To Pop
1214  RetOps.push_back(DAG.getTargetConstant(getBytesToPopOnReturn(), MVT::i16));
1215
1216  // Copy the result values into the output registers.
1217  for (unsigned i = 0; i != RVLocs.size(); ++i) {
1218    CCValAssign &VA = RVLocs[i];
1219    assert(VA.isRegLoc() && "Can only return in registers!");
1220    SDValue ValToCopy = Outs[i].Val;
1221
1222    // Returns in ST0/ST1 are handled specially: these are pushed as operands to
1223    // the RET instruction and handled by the FP Stackifier.
1224    if (VA.getLocReg() == X86::ST0 ||
1225        VA.getLocReg() == X86::ST1) {
1226      // If this is a copy from an xmm register to ST(0), use an FPExtend to
1227      // change the value to the FP stack register class.
1228      if (isScalarFPTypeInSSEReg(VA.getValVT()))
1229        ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
1230      RetOps.push_back(ValToCopy);
1231      // Don't emit a copytoreg.
1232      continue;
1233    }
1234
1235    // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
1236    // which is returned in RAX / RDX.
1237    if (Subtarget->is64Bit()) {
1238      EVT ValVT = ValToCopy.getValueType();
1239      if (ValVT.isVector() && ValVT.getSizeInBits() == 64) {
1240        ValToCopy = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i64, ValToCopy);
1241        if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1)
1242          ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, ValToCopy);
1243      }
1244    }
1245
1246    Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
1247    Flag = Chain.getValue(1);
1248  }
1249
1250  // The x86-64 ABI for returning structs by value requires that we copy
1251  // the sret argument into %rax for the return. We saved the argument into
1252  // a virtual register in the entry block, so now we copy the value out
1253  // and into %rax.
1254  if (Subtarget->is64Bit() &&
1255      DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
1256    MachineFunction &MF = DAG.getMachineFunction();
1257    X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1258    unsigned Reg = FuncInfo->getSRetReturnReg();
1259    if (!Reg) {
1260      Reg = MRI.createVirtualRegister(getRegClassFor(MVT::i64));
1261      FuncInfo->setSRetReturnReg(Reg);
1262    }
1263    SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
1264
1265    Chain = DAG.getCopyToReg(Chain, dl, X86::RAX, Val, Flag);
1266    Flag = Chain.getValue(1);
1267
1268    // RAX now acts like a return value.
1269    MRI.addLiveOut(X86::RAX);
1270  }
1271
1272  RetOps[0] = Chain;  // Update chain.
1273
1274  // Add the flag if we have it.
1275  if (Flag.getNode())
1276    RetOps.push_back(Flag);
1277
1278  return DAG.getNode(X86ISD::RET_FLAG, dl,
1279                     MVT::Other, &RetOps[0], RetOps.size());
1280}
1281
1282/// LowerCallResult - Lower the result values of a call into the
1283/// appropriate copies out of appropriate physical registers.
1284///
1285SDValue
1286X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1287                                   CallingConv::ID CallConv, bool isVarArg,
1288                                   const SmallVectorImpl<ISD::InputArg> &Ins,
1289                                   DebugLoc dl, SelectionDAG &DAG,
1290                                   SmallVectorImpl<SDValue> &InVals) {
1291
1292  // Assign locations to each value returned by this call.
1293  SmallVector<CCValAssign, 16> RVLocs;
1294  bool Is64Bit = Subtarget->is64Bit();
1295  CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1296                 RVLocs, *DAG.getContext());
1297  CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
1298
1299  // Copy all of the result registers out of their specified physreg.
1300  for (unsigned i = 0; i != RVLocs.size(); ++i) {
1301    CCValAssign &VA = RVLocs[i];
1302    EVT CopyVT = VA.getValVT();
1303
1304    // If this is x86-64, and we disabled SSE, we can't return FP values
1305    if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
1306        ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
1307      llvm_report_error("SSE register return with SSE disabled");
1308    }
1309
1310    // If this is a call to a function that returns an fp value on the floating
1311    // point stack, but where we prefer to use the value in xmm registers, copy
1312    // it out as F80 and use a truncate to move it from fp stack reg to xmm reg.
1313    if ((VA.getLocReg() == X86::ST0 ||
1314         VA.getLocReg() == X86::ST1) &&
1315        isScalarFPTypeInSSEReg(VA.getValVT())) {
1316      CopyVT = MVT::f80;
1317    }
1318
1319    SDValue Val;
1320    if (Is64Bit && CopyVT.isVector() && CopyVT.getSizeInBits() == 64) {
1321      // For x86-64, MMX values are returned in XMM0 / XMM1 except for v1i64.
1322      if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1323        Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1324                                   MVT::v2i64, InFlag).getValue(1);
1325        Val = Chain.getValue(0);
1326        Val = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64,
1327                          Val, DAG.getConstant(0, MVT::i64));
1328      } else {
1329        Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1330                                   MVT::i64, InFlag).getValue(1);
1331        Val = Chain.getValue(0);
1332      }
1333      Val = DAG.getNode(ISD::BIT_CONVERT, dl, CopyVT, Val);
1334    } else {
1335      Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1336                                 CopyVT, InFlag).getValue(1);
1337      Val = Chain.getValue(0);
1338    }
1339    InFlag = Chain.getValue(2);
1340
1341    if (CopyVT != VA.getValVT()) {
1342      // Round the F80 the right size, which also moves to the appropriate xmm
1343      // register.
1344      Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
1345                        // This truncation won't change the value.
1346                        DAG.getIntPtrConstant(1));
1347    }
1348
1349    InVals.push_back(Val);
1350  }
1351
1352  return Chain;
1353}
1354
1355
1356//===----------------------------------------------------------------------===//
1357//                C & StdCall & Fast Calling Convention implementation
1358//===----------------------------------------------------------------------===//
1359//  StdCall calling convention seems to be standard for many Windows' API
1360//  routines and around. It differs from C calling convention just a little:
1361//  callee should clean up the stack, not caller. Symbols should be also
1362//  decorated in some fancy way :) It doesn't support any vector arguments.
1363//  For info on fast calling convention see Fast Calling Convention (tail call)
1364//  implementation LowerX86_32FastCCCallTo.
1365
1366/// CallIsStructReturn - Determines whether a call uses struct return
1367/// semantics.
1368static bool CallIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
1369  if (Outs.empty())
1370    return false;
1371
1372  return Outs[0].Flags.isSRet();
1373}
1374
1375/// ArgsAreStructReturn - Determines whether a function uses struct
1376/// return semantics.
1377static bool
1378ArgsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
1379  if (Ins.empty())
1380    return false;
1381
1382  return Ins[0].Flags.isSRet();
1383}
1384
1385/// IsCalleePop - Determines whether the callee is required to pop its
1386/// own arguments. Callee pop is necessary to support tail calls.
1387bool X86TargetLowering::IsCalleePop(bool IsVarArg, CallingConv::ID CallingConv){
1388  if (IsVarArg)
1389    return false;
1390
1391  switch (CallingConv) {
1392  default:
1393    return false;
1394  case CallingConv::X86_StdCall:
1395    return !Subtarget->is64Bit();
1396  case CallingConv::X86_FastCall:
1397    return !Subtarget->is64Bit();
1398  case CallingConv::Fast:
1399    return GuaranteedTailCallOpt;
1400  case CallingConv::GHC:
1401    return GuaranteedTailCallOpt;
1402  }
1403}
1404
1405/// CCAssignFnForNode - Selects the correct CCAssignFn for a the
1406/// given CallingConvention value.
1407CCAssignFn *X86TargetLowering::CCAssignFnForNode(CallingConv::ID CC) const {
1408  if (Subtarget->is64Bit()) {
1409    if (CC == CallingConv::GHC)
1410      return CC_X86_64_GHC;
1411    else if (Subtarget->isTargetWin64())
1412      return CC_X86_Win64_C;
1413    else
1414      return CC_X86_64_C;
1415  }
1416
1417  if (CC == CallingConv::X86_FastCall)
1418    return CC_X86_32_FastCall;
1419  else if (CC == CallingConv::Fast)
1420    return CC_X86_32_FastCC;
1421  else if (CC == CallingConv::GHC)
1422    return CC_X86_32_GHC;
1423  else
1424    return CC_X86_32_C;
1425}
1426
1427/// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
1428/// by "Src" to address "Dst" with size and alignment information specified by
1429/// the specific parameter attribute. The copy will be passed as a byval
1430/// function parameter.
1431static SDValue
1432CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
1433                          ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
1434                          DebugLoc dl) {
1435  SDValue SizeNode     = DAG.getConstant(Flags.getByValSize(), MVT::i32);
1436  return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
1437                       /*isVolatile*/false, /*AlwaysInline=*/true,
1438                       NULL, 0, NULL, 0);
1439}
1440
1441/// IsTailCallConvention - Return true if the calling convention is one that
1442/// supports tail call optimization.
1443static bool IsTailCallConvention(CallingConv::ID CC) {
1444  return (CC == CallingConv::Fast || CC == CallingConv::GHC);
1445}
1446
1447/// FuncIsMadeTailCallSafe - Return true if the function is being made into
1448/// a tailcall target by changing its ABI.
1449static bool FuncIsMadeTailCallSafe(CallingConv::ID CC) {
1450  return GuaranteedTailCallOpt && IsTailCallConvention(CC);
1451}
1452
1453SDValue
1454X86TargetLowering::LowerMemArgument(SDValue Chain,
1455                                    CallingConv::ID CallConv,
1456                                    const SmallVectorImpl<ISD::InputArg> &Ins,
1457                                    DebugLoc dl, SelectionDAG &DAG,
1458                                    const CCValAssign &VA,
1459                                    MachineFrameInfo *MFI,
1460                                    unsigned i) {
1461  // Create the nodes corresponding to a load from this parameter slot.
1462  ISD::ArgFlagsTy Flags = Ins[i].Flags;
1463  bool AlwaysUseMutable = FuncIsMadeTailCallSafe(CallConv);
1464  bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
1465  EVT ValVT;
1466
1467  // If value is passed by pointer we have address passed instead of the value
1468  // itself.
1469  if (VA.getLocInfo() == CCValAssign::Indirect)
1470    ValVT = VA.getLocVT();
1471  else
1472    ValVT = VA.getValVT();
1473
1474  // FIXME: For now, all byval parameter objects are marked mutable. This can be
1475  // changed with more analysis.
1476  // In case of tail call optimization mark all arguments mutable. Since they
1477  // could be overwritten by lowering of arguments in case of a tail call.
1478  if (Flags.isByVal()) {
1479    int FI = MFI->CreateFixedObject(Flags.getByValSize(),
1480                                    VA.getLocMemOffset(), isImmutable, false);
1481    return DAG.getFrameIndex(FI, getPointerTy());
1482  } else {
1483    int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
1484                                    VA.getLocMemOffset(), isImmutable, false);
1485    SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
1486    return DAG.getLoad(ValVT, dl, Chain, FIN,
1487                       PseudoSourceValue::getFixedStack(FI), 0,
1488                       false, false, 0);
1489  }
1490}
1491
1492SDValue
1493X86TargetLowering::LowerFormalArguments(SDValue Chain,
1494                                        CallingConv::ID CallConv,
1495                                        bool isVarArg,
1496                                      const SmallVectorImpl<ISD::InputArg> &Ins,
1497                                        DebugLoc dl,
1498                                        SelectionDAG &DAG,
1499                                        SmallVectorImpl<SDValue> &InVals) {
1500  MachineFunction &MF = DAG.getMachineFunction();
1501  X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1502
1503  const Function* Fn = MF.getFunction();
1504  if (Fn->hasExternalLinkage() &&
1505      Subtarget->isTargetCygMing() &&
1506      Fn->getName() == "main")
1507    FuncInfo->setForceFramePointer(true);
1508
1509  MachineFrameInfo *MFI = MF.getFrameInfo();
1510  bool Is64Bit = Subtarget->is64Bit();
1511  bool IsWin64 = Subtarget->isTargetWin64();
1512
1513  assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
1514         "Var args not supported with calling convention fastcc or ghc");
1515
1516  // Assign locations to all of the incoming arguments.
1517  SmallVector<CCValAssign, 16> ArgLocs;
1518  CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1519                 ArgLocs, *DAG.getContext());
1520  CCInfo.AnalyzeFormalArguments(Ins, CCAssignFnForNode(CallConv));
1521
1522  unsigned LastVal = ~0U;
1523  SDValue ArgValue;
1524  for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1525    CCValAssign &VA = ArgLocs[i];
1526    // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
1527    // places.
1528    assert(VA.getValNo() != LastVal &&
1529           "Don't support value assigned to multiple locs yet");
1530    LastVal = VA.getValNo();
1531
1532    if (VA.isRegLoc()) {
1533      EVT RegVT = VA.getLocVT();
1534      TargetRegisterClass *RC = NULL;
1535      if (RegVT == MVT::i32)
1536        RC = X86::GR32RegisterClass;
1537      else if (Is64Bit && RegVT == MVT::i64)
1538        RC = X86::GR64RegisterClass;
1539      else if (RegVT == MVT::f32)
1540        RC = X86::FR32RegisterClass;
1541      else if (RegVT == MVT::f64)
1542        RC = X86::FR64RegisterClass;
1543      else if (RegVT.isVector() && RegVT.getSizeInBits() == 128)
1544        RC = X86::VR128RegisterClass;
1545      else if (RegVT.isVector() && RegVT.getSizeInBits() == 64)
1546        RC = X86::VR64RegisterClass;
1547      else
1548        llvm_unreachable("Unknown argument type!");
1549
1550      unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
1551      ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
1552
1553      // If this is an 8 or 16-bit value, it is really passed promoted to 32
1554      // bits.  Insert an assert[sz]ext to capture this, then truncate to the
1555      // right size.
1556      if (VA.getLocInfo() == CCValAssign::SExt)
1557        ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
1558                               DAG.getValueType(VA.getValVT()));
1559      else if (VA.getLocInfo() == CCValAssign::ZExt)
1560        ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
1561                               DAG.getValueType(VA.getValVT()));
1562      else if (VA.getLocInfo() == CCValAssign::BCvt)
1563        ArgValue = DAG.getNode(ISD::BIT_CONVERT, dl, VA.getValVT(), ArgValue);
1564
1565      if (VA.isExtInLoc()) {
1566        // Handle MMX values passed in XMM regs.
1567        if (RegVT.isVector()) {
1568          ArgValue = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64,
1569                                 ArgValue, DAG.getConstant(0, MVT::i64));
1570          ArgValue = DAG.getNode(ISD::BIT_CONVERT, dl, VA.getValVT(), ArgValue);
1571        } else
1572          ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
1573      }
1574    } else {
1575      assert(VA.isMemLoc());
1576      ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
1577    }
1578
1579    // If value is passed via pointer - do a load.
1580    if (VA.getLocInfo() == CCValAssign::Indirect)
1581      ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue, NULL, 0,
1582                             false, false, 0);
1583
1584    InVals.push_back(ArgValue);
1585  }
1586
1587  // The x86-64 ABI for returning structs by value requires that we copy
1588  // the sret argument into %rax for the return. Save the argument into
1589  // a virtual register so that we can access it from the return points.
1590  if (Is64Bit && MF.getFunction()->hasStructRetAttr()) {
1591    X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1592    unsigned Reg = FuncInfo->getSRetReturnReg();
1593    if (!Reg) {
1594      Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(MVT::i64));
1595      FuncInfo->setSRetReturnReg(Reg);
1596    }
1597    SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[0]);
1598    Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
1599  }
1600
1601  unsigned StackSize = CCInfo.getNextStackOffset();
1602  // Align stack specially for tail calls.
1603  if (FuncIsMadeTailCallSafe(CallConv))
1604    StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
1605
1606  // If the function takes variable number of arguments, make a frame index for
1607  // the start of the first vararg value... for expansion of llvm.va_start.
1608  if (isVarArg) {
1609    if (Is64Bit || CallConv != CallingConv::X86_FastCall) {
1610      VarArgsFrameIndex = MFI->CreateFixedObject(1, StackSize, true, false);
1611    }
1612    if (Is64Bit) {
1613      unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
1614
1615      // FIXME: We should really autogenerate these arrays
1616      static const unsigned GPR64ArgRegsWin64[] = {
1617        X86::RCX, X86::RDX, X86::R8,  X86::R9
1618      };
1619      static const unsigned XMMArgRegsWin64[] = {
1620        X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3
1621      };
1622      static const unsigned GPR64ArgRegs64Bit[] = {
1623        X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
1624      };
1625      static const unsigned XMMArgRegs64Bit[] = {
1626        X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
1627        X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
1628      };
1629      const unsigned *GPR64ArgRegs, *XMMArgRegs;
1630
1631      if (IsWin64) {
1632        TotalNumIntRegs = 4; TotalNumXMMRegs = 4;
1633        GPR64ArgRegs = GPR64ArgRegsWin64;
1634        XMMArgRegs = XMMArgRegsWin64;
1635      } else {
1636        TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
1637        GPR64ArgRegs = GPR64ArgRegs64Bit;
1638        XMMArgRegs = XMMArgRegs64Bit;
1639      }
1640      unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
1641                                                       TotalNumIntRegs);
1642      unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs,
1643                                                       TotalNumXMMRegs);
1644
1645      bool NoImplicitFloatOps = Fn->hasFnAttr(Attribute::NoImplicitFloat);
1646      assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
1647             "SSE register cannot be used when SSE is disabled!");
1648      assert(!(NumXMMRegs && UseSoftFloat && NoImplicitFloatOps) &&
1649             "SSE register cannot be used when SSE is disabled!");
1650      if (UseSoftFloat || NoImplicitFloatOps || !Subtarget->hasSSE1())
1651        // Kernel mode asks for SSE to be disabled, so don't push them
1652        // on the stack.
1653        TotalNumXMMRegs = 0;
1654
1655      // For X86-64, if there are vararg parameters that are passed via
1656      // registers, then we must store them to their spots on the stack so they
1657      // may be loaded by deferencing the result of va_next.
1658      VarArgsGPOffset = NumIntRegs * 8;
1659      VarArgsFPOffset = TotalNumIntRegs * 8 + NumXMMRegs * 16;
1660      RegSaveFrameIndex = MFI->CreateStackObject(TotalNumIntRegs * 8 +
1661                                                 TotalNumXMMRegs * 16, 16,
1662                                                 false);
1663
1664      // Store the integer parameter registers.
1665      SmallVector<SDValue, 8> MemOps;
1666      SDValue RSFIN = DAG.getFrameIndex(RegSaveFrameIndex, getPointerTy());
1667      unsigned Offset = VarArgsGPOffset;
1668      for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
1669        SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
1670                                  DAG.getIntPtrConstant(Offset));
1671        unsigned VReg = MF.addLiveIn(GPR64ArgRegs[NumIntRegs],
1672                                     X86::GR64RegisterClass);
1673        SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
1674        SDValue Store =
1675          DAG.getStore(Val.getValue(1), dl, Val, FIN,
1676                       PseudoSourceValue::getFixedStack(RegSaveFrameIndex),
1677                       Offset, false, false, 0);
1678        MemOps.push_back(Store);
1679        Offset += 8;
1680      }
1681
1682      if (TotalNumXMMRegs != 0 && NumXMMRegs != TotalNumXMMRegs) {
1683        // Now store the XMM (fp + vector) parameter registers.
1684        SmallVector<SDValue, 11> SaveXMMOps;
1685        SaveXMMOps.push_back(Chain);
1686
1687        unsigned AL = MF.addLiveIn(X86::AL, X86::GR8RegisterClass);
1688        SDValue ALVal = DAG.getCopyFromReg(DAG.getEntryNode(), dl, AL, MVT::i8);
1689        SaveXMMOps.push_back(ALVal);
1690
1691        SaveXMMOps.push_back(DAG.getIntPtrConstant(RegSaveFrameIndex));
1692        SaveXMMOps.push_back(DAG.getIntPtrConstant(VarArgsFPOffset));
1693
1694        for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
1695          unsigned VReg = MF.addLiveIn(XMMArgRegs[NumXMMRegs],
1696                                       X86::VR128RegisterClass);
1697          SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::v4f32);
1698          SaveXMMOps.push_back(Val);
1699        }
1700        MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
1701                                     MVT::Other,
1702                                     &SaveXMMOps[0], SaveXMMOps.size()));
1703      }
1704
1705      if (!MemOps.empty())
1706        Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1707                            &MemOps[0], MemOps.size());
1708    }
1709  }
1710
1711  // Some CCs need callee pop.
1712  if (IsCalleePop(isVarArg, CallConv)) {
1713    BytesToPopOnReturn  = StackSize; // Callee pops everything.
1714  } else {
1715    BytesToPopOnReturn  = 0; // Callee pops nothing.
1716    // If this is an sret function, the return should pop the hidden pointer.
1717    if (!Is64Bit && !IsTailCallConvention(CallConv) && ArgsAreStructReturn(Ins))
1718      BytesToPopOnReturn = 4;
1719  }
1720
1721  if (!Is64Bit) {
1722    RegSaveFrameIndex = 0xAAAAAAA;   // RegSaveFrameIndex is X86-64 only.
1723    if (CallConv == CallingConv::X86_FastCall)
1724      VarArgsFrameIndex = 0xAAAAAAA;   // fastcc functions can't have varargs.
1725  }
1726
1727  FuncInfo->setBytesToPopOnReturn(BytesToPopOnReturn);
1728
1729  return Chain;
1730}
1731
1732SDValue
1733X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
1734                                    SDValue StackPtr, SDValue Arg,
1735                                    DebugLoc dl, SelectionDAG &DAG,
1736                                    const CCValAssign &VA,
1737                                    ISD::ArgFlagsTy Flags) {
1738  const unsigned FirstStackArgOffset = (Subtarget->isTargetWin64() ? 32 : 0);
1739  unsigned LocMemOffset = FirstStackArgOffset + VA.getLocMemOffset();
1740  SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
1741  PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
1742  if (Flags.isByVal()) {
1743    return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
1744  }
1745  return DAG.getStore(Chain, dl, Arg, PtrOff,
1746                      PseudoSourceValue::getStack(), LocMemOffset,
1747                      false, false, 0);
1748}
1749
1750/// EmitTailCallLoadRetAddr - Emit a load of return address if tail call
1751/// optimization is performed and it is required.
1752SDValue
1753X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
1754                                           SDValue &OutRetAddr, SDValue Chain,
1755                                           bool IsTailCall, bool Is64Bit,
1756                                           int FPDiff, DebugLoc dl) {
1757  // Adjust the Return address stack slot.
1758  EVT VT = getPointerTy();
1759  OutRetAddr = getReturnAddressFrameIndex(DAG);
1760
1761  // Load the "old" Return address.
1762  OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, NULL, 0, false, false, 0);
1763  return SDValue(OutRetAddr.getNode(), 1);
1764}
1765
1766/// EmitTailCallStoreRetAddr - Emit a store of the return adress if tail call
1767/// optimization is performed and it is required (FPDiff!=0).
1768static SDValue
1769EmitTailCallStoreRetAddr(SelectionDAG & DAG, MachineFunction &MF,
1770                         SDValue Chain, SDValue RetAddrFrIdx,
1771                         bool Is64Bit, int FPDiff, DebugLoc dl) {
1772  // Store the return address to the appropriate stack slot.
1773  if (!FPDiff) return Chain;
1774  // Calculate the new stack slot for the return address.
1775  int SlotSize = Is64Bit ? 8 : 4;
1776  int NewReturnAddrFI =
1777    MF.getFrameInfo()->CreateFixedObject(SlotSize, FPDiff-SlotSize, false, false);
1778  EVT VT = Is64Bit ? MVT::i64 : MVT::i32;
1779  SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, VT);
1780  Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
1781                       PseudoSourceValue::getFixedStack(NewReturnAddrFI), 0,
1782                       false, false, 0);
1783  return Chain;
1784}
1785
1786SDValue
1787X86TargetLowering::LowerCall(SDValue Chain, SDValue Callee,
1788                             CallingConv::ID CallConv, bool isVarArg,
1789                             bool &isTailCall,
1790                             const SmallVectorImpl<ISD::OutputArg> &Outs,
1791                             const SmallVectorImpl<ISD::InputArg> &Ins,
1792                             DebugLoc dl, SelectionDAG &DAG,
1793                             SmallVectorImpl<SDValue> &InVals) {
1794  MachineFunction &MF = DAG.getMachineFunction();
1795  bool Is64Bit        = Subtarget->is64Bit();
1796  bool IsStructRet    = CallIsStructReturn(Outs);
1797  bool IsSibcall      = false;
1798
1799  if (isTailCall) {
1800    // Check if it's really possible to do a tail call.
1801    isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
1802                    isVarArg, IsStructRet, MF.getFunction()->hasStructRetAttr(),
1803                                                   Outs, Ins, DAG);
1804
1805    // Sibcalls are automatically detected tailcalls which do not require
1806    // ABI changes.
1807    if (!GuaranteedTailCallOpt && isTailCall)
1808      IsSibcall = true;
1809
1810    if (isTailCall)
1811      ++NumTailCalls;
1812  }
1813
1814  assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
1815         "Var args not supported with calling convention fastcc or ghc");
1816
1817  // Analyze operands of the call, assigning locations to each operand.
1818  SmallVector<CCValAssign, 16> ArgLocs;
1819  CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1820                 ArgLocs, *DAG.getContext());
1821  CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForNode(CallConv));
1822
1823  // Get a count of how many bytes are to be pushed on the stack.
1824  unsigned NumBytes = CCInfo.getNextStackOffset();
1825  if (IsSibcall)
1826    // This is a sibcall. The memory operands are available in caller's
1827    // own caller's stack.
1828    NumBytes = 0;
1829  else if (GuaranteedTailCallOpt && IsTailCallConvention(CallConv))
1830    NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
1831
1832  int FPDiff = 0;
1833  if (isTailCall && !IsSibcall) {
1834    // Lower arguments at fp - stackoffset + fpdiff.
1835    unsigned NumBytesCallerPushed =
1836      MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn();
1837    FPDiff = NumBytesCallerPushed - NumBytes;
1838
1839    // Set the delta of movement of the returnaddr stackslot.
1840    // But only set if delta is greater than previous delta.
1841    if (FPDiff < (MF.getInfo<X86MachineFunctionInfo>()->getTCReturnAddrDelta()))
1842      MF.getInfo<X86MachineFunctionInfo>()->setTCReturnAddrDelta(FPDiff);
1843  }
1844
1845  if (!IsSibcall)
1846    Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true));
1847
1848  SDValue RetAddrFrIdx;
1849  // Load return adress for tail calls.
1850  if (isTailCall && FPDiff)
1851    Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
1852                                    Is64Bit, FPDiff, dl);
1853
1854  SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
1855  SmallVector<SDValue, 8> MemOpChains;
1856  SDValue StackPtr;
1857
1858  // Walk the register/memloc assignments, inserting copies/loads.  In the case
1859  // of tail call optimization arguments are handle later.
1860  for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1861    CCValAssign &VA = ArgLocs[i];
1862    EVT RegVT = VA.getLocVT();
1863    SDValue Arg = Outs[i].Val;
1864    ISD::ArgFlagsTy Flags = Outs[i].Flags;
1865    bool isByVal = Flags.isByVal();
1866
1867    // Promote the value if needed.
1868    switch (VA.getLocInfo()) {
1869    default: llvm_unreachable("Unknown loc info!");
1870    case CCValAssign::Full: break;
1871    case CCValAssign::SExt:
1872      Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
1873      break;
1874    case CCValAssign::ZExt:
1875      Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
1876      break;
1877    case CCValAssign::AExt:
1878      if (RegVT.isVector() && RegVT.getSizeInBits() == 128) {
1879        // Special case: passing MMX values in XMM registers.
1880        Arg = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i64, Arg);
1881        Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
1882        Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
1883      } else
1884        Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
1885      break;
1886    case CCValAssign::BCvt:
1887      Arg = DAG.getNode(ISD::BIT_CONVERT, dl, RegVT, Arg);
1888      break;
1889    case CCValAssign::Indirect: {
1890      // Store the argument.
1891      SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
1892      int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
1893      Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
1894                           PseudoSourceValue::getFixedStack(FI), 0,
1895                           false, false, 0);
1896      Arg = SpillSlot;
1897      break;
1898    }
1899    }
1900
1901    if (VA.isRegLoc()) {
1902      RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1903    } else if (!IsSibcall && (!isTailCall || isByVal)) {
1904      assert(VA.isMemLoc());
1905      if (StackPtr.getNode() == 0)
1906        StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr, getPointerTy());
1907      MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
1908                                             dl, DAG, VA, Flags));
1909    }
1910  }
1911
1912  if (!MemOpChains.empty())
1913    Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1914                        &MemOpChains[0], MemOpChains.size());
1915
1916  // Build a sequence of copy-to-reg nodes chained together with token chain
1917  // and flag operands which copy the outgoing args into registers.
1918  SDValue InFlag;
1919  // Tail call byval lowering might overwrite argument registers so in case of
1920  // tail call optimization the copies to registers are lowered later.
1921  if (!isTailCall)
1922    for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1923      Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1924                               RegsToPass[i].second, InFlag);
1925      InFlag = Chain.getValue(1);
1926    }
1927
1928  if (Subtarget->isPICStyleGOT()) {
1929    // ELF / PIC requires GOT in the EBX register before function calls via PLT
1930    // GOT pointer.
1931    if (!isTailCall) {
1932      Chain = DAG.getCopyToReg(Chain, dl, X86::EBX,
1933                               DAG.getNode(X86ISD::GlobalBaseReg,
1934                                           DebugLoc(), getPointerTy()),
1935                               InFlag);
1936      InFlag = Chain.getValue(1);
1937    } else {
1938      // If we are tail calling and generating PIC/GOT style code load the
1939      // address of the callee into ECX. The value in ecx is used as target of
1940      // the tail jump. This is done to circumvent the ebx/callee-saved problem
1941      // for tail calls on PIC/GOT architectures. Normally we would just put the
1942      // address of GOT into ebx and then call target@PLT. But for tail calls
1943      // ebx would be restored (since ebx is callee saved) before jumping to the
1944      // target@PLT.
1945
1946      // Note: The actual moving to ECX is done further down.
1947      GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
1948      if (G && !G->getGlobal()->hasHiddenVisibility() &&
1949          !G->getGlobal()->hasProtectedVisibility())
1950        Callee = LowerGlobalAddress(Callee, DAG);
1951      else if (isa<ExternalSymbolSDNode>(Callee))
1952        Callee = LowerExternalSymbol(Callee, DAG);
1953    }
1954  }
1955
1956  if (Is64Bit && isVarArg) {
1957    // From AMD64 ABI document:
1958    // For calls that may call functions that use varargs or stdargs
1959    // (prototype-less calls or calls to functions containing ellipsis (...) in
1960    // the declaration) %al is used as hidden argument to specify the number
1961    // of SSE registers used. The contents of %al do not need to match exactly
1962    // the number of registers, but must be an ubound on the number of SSE
1963    // registers used and is in the range 0 - 8 inclusive.
1964
1965    // FIXME: Verify this on Win64
1966    // Count the number of XMM registers allocated.
1967    static const unsigned XMMArgRegs[] = {
1968      X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
1969      X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
1970    };
1971    unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
1972    assert((Subtarget->hasSSE1() || !NumXMMRegs)
1973           && "SSE registers cannot be used when SSE is disabled");
1974
1975    Chain = DAG.getCopyToReg(Chain, dl, X86::AL,
1976                             DAG.getConstant(NumXMMRegs, MVT::i8), InFlag);
1977    InFlag = Chain.getValue(1);
1978  }
1979
1980
1981  // For tail calls lower the arguments to the 'real' stack slot.
1982  if (isTailCall) {
1983    // Force all the incoming stack arguments to be loaded from the stack
1984    // before any new outgoing arguments are stored to the stack, because the
1985    // outgoing stack slots may alias the incoming argument stack slots, and
1986    // the alias isn't otherwise explicit. This is slightly more conservative
1987    // than necessary, because it means that each store effectively depends
1988    // on every argument instead of just those arguments it would clobber.
1989    SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
1990
1991    SmallVector<SDValue, 8> MemOpChains2;
1992    SDValue FIN;
1993    int FI = 0;
1994    // Do not flag preceeding copytoreg stuff together with the following stuff.
1995    InFlag = SDValue();
1996    if (GuaranteedTailCallOpt) {
1997      for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1998        CCValAssign &VA = ArgLocs[i];
1999        if (VA.isRegLoc())
2000          continue;
2001        assert(VA.isMemLoc());
2002        SDValue Arg = Outs[i].Val;
2003        ISD::ArgFlagsTy Flags = Outs[i].Flags;
2004        // Create frame index.
2005        int32_t Offset = VA.getLocMemOffset()+FPDiff;
2006        uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
2007        FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true, false);
2008        FIN = DAG.getFrameIndex(FI, getPointerTy());
2009
2010        if (Flags.isByVal()) {
2011          // Copy relative to framepointer.
2012          SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
2013          if (StackPtr.getNode() == 0)
2014            StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr,
2015                                          getPointerTy());
2016          Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
2017
2018          MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
2019                                                           ArgChain,
2020                                                           Flags, DAG, dl));
2021        } else {
2022          // Store relative to framepointer.
2023          MemOpChains2.push_back(
2024            DAG.getStore(ArgChain, dl, Arg, FIN,
2025                         PseudoSourceValue::getFixedStack(FI), 0,
2026                         false, false, 0));
2027        }
2028      }
2029    }
2030
2031    if (!MemOpChains2.empty())
2032      Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2033                          &MemOpChains2[0], MemOpChains2.size());
2034
2035    // Copy arguments to their registers.
2036    for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2037      Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2038                               RegsToPass[i].second, InFlag);
2039      InFlag = Chain.getValue(1);
2040    }
2041    InFlag =SDValue();
2042
2043    // Store the return address to the appropriate stack slot.
2044    Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx, Is64Bit,
2045                                     FPDiff, dl);
2046  }
2047
2048  bool WasGlobalOrExternal = false;
2049  if (getTargetMachine().getCodeModel() == CodeModel::Large) {
2050    assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
2051    // In the 64-bit large code model, we have to make all calls
2052    // through a register, since the call instruction's 32-bit
2053    // pc-relative offset may not be large enough to hold the whole
2054    // address.
2055  } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2056    WasGlobalOrExternal = true;
2057    // If the callee is a GlobalAddress node (quite common, every direct call
2058    // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
2059    // it.
2060
2061    // We should use extra load for direct calls to dllimported functions in
2062    // non-JIT mode.
2063    GlobalValue *GV = G->getGlobal();
2064    if (!GV->hasDLLImportLinkage()) {
2065      unsigned char OpFlags = 0;
2066
2067      // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
2068      // external symbols most go through the PLT in PIC mode.  If the symbol
2069      // has hidden or protected visibility, or if it is static or local, then
2070      // we don't need to use the PLT - we can directly call it.
2071      if (Subtarget->isTargetELF() &&
2072          getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
2073          GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
2074        OpFlags = X86II::MO_PLT;
2075      } else if (Subtarget->isPICStyleStubAny() &&
2076               (GV->isDeclaration() || GV->isWeakForLinker()) &&
2077               Subtarget->getDarwinVers() < 9) {
2078        // PC-relative references to external symbols should go through $stub,
2079        // unless we're building with the leopard linker or later, which
2080        // automatically synthesizes these stubs.
2081        OpFlags = X86II::MO_DARWIN_STUB;
2082      }
2083
2084      Callee = DAG.getTargetGlobalAddress(GV, getPointerTy(),
2085                                          G->getOffset(), OpFlags);
2086    }
2087  } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2088    WasGlobalOrExternal = true;
2089    unsigned char OpFlags = 0;
2090
2091    // On ELF targets, in either X86-64 or X86-32 mode, direct calls to external
2092    // symbols should go through the PLT.
2093    if (Subtarget->isTargetELF() &&
2094        getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2095      OpFlags = X86II::MO_PLT;
2096    } else if (Subtarget->isPICStyleStubAny() &&
2097             Subtarget->getDarwinVers() < 9) {
2098      // PC-relative references to external symbols should go through $stub,
2099      // unless we're building with the leopard linker or later, which
2100      // automatically synthesizes these stubs.
2101      OpFlags = X86II::MO_DARWIN_STUB;
2102    }
2103
2104    Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
2105                                         OpFlags);
2106  }
2107
2108  // Returns a chain & a flag for retval copy to use.
2109  SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
2110  SmallVector<SDValue, 8> Ops;
2111
2112  if (!IsSibcall && isTailCall) {
2113    Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
2114                           DAG.getIntPtrConstant(0, true), InFlag);
2115    InFlag = Chain.getValue(1);
2116  }
2117
2118  Ops.push_back(Chain);
2119  Ops.push_back(Callee);
2120
2121  if (isTailCall)
2122    Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
2123
2124  // Add argument registers to the end of the list so that they are known live
2125  // into the call.
2126  for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2127    Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2128                                  RegsToPass[i].second.getValueType()));
2129
2130  // Add an implicit use GOT pointer in EBX.
2131  if (!isTailCall && Subtarget->isPICStyleGOT())
2132    Ops.push_back(DAG.getRegister(X86::EBX, getPointerTy()));
2133
2134  // Add an implicit use of AL for x86 vararg functions.
2135  if (Is64Bit && isVarArg)
2136    Ops.push_back(DAG.getRegister(X86::AL, MVT::i8));
2137
2138  if (InFlag.getNode())
2139    Ops.push_back(InFlag);
2140
2141  if (isTailCall) {
2142    // If this is the first return lowered for this function, add the regs
2143    // to the liveout set for the function.
2144    if (MF.getRegInfo().liveout_empty()) {
2145      SmallVector<CCValAssign, 16> RVLocs;
2146      CCState CCInfo(CallConv, isVarArg, getTargetMachine(), RVLocs,
2147                     *DAG.getContext());
2148      CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2149      for (unsigned i = 0; i != RVLocs.size(); ++i)
2150        if (RVLocs[i].isRegLoc())
2151          MF.getRegInfo().addLiveOut(RVLocs[i].getLocReg());
2152    }
2153    return DAG.getNode(X86ISD::TC_RETURN, dl,
2154                       NodeTys, &Ops[0], Ops.size());
2155  }
2156
2157  Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, &Ops[0], Ops.size());
2158  InFlag = Chain.getValue(1);
2159
2160  // Create the CALLSEQ_END node.
2161  unsigned NumBytesForCalleeToPush;
2162  if (IsCalleePop(isVarArg, CallConv))
2163    NumBytesForCalleeToPush = NumBytes;    // Callee pops everything
2164  else if (!Is64Bit && !IsTailCallConvention(CallConv) && IsStructRet)
2165    // If this is a call to a struct-return function, the callee
2166    // pops the hidden struct pointer, so we have to push it back.
2167    // This is common for Darwin/X86, Linux & Mingw32 targets.
2168    NumBytesForCalleeToPush = 4;
2169  else
2170    NumBytesForCalleeToPush = 0;  // Callee pops nothing.
2171
2172  // Returns a flag for retval copy to use.
2173  if (!IsSibcall) {
2174    Chain = DAG.getCALLSEQ_END(Chain,
2175                               DAG.getIntPtrConstant(NumBytes, true),
2176                               DAG.getIntPtrConstant(NumBytesForCalleeToPush,
2177                                                     true),
2178                               InFlag);
2179    InFlag = Chain.getValue(1);
2180  }
2181
2182  // Handle result values, copying them out of physregs into vregs that we
2183  // return.
2184  return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
2185                         Ins, dl, DAG, InVals);
2186}
2187
2188
2189//===----------------------------------------------------------------------===//
2190//                Fast Calling Convention (tail call) implementation
2191//===----------------------------------------------------------------------===//
2192
2193//  Like std call, callee cleans arguments, convention except that ECX is
2194//  reserved for storing the tail called function address. Only 2 registers are
2195//  free for argument passing (inreg). Tail call optimization is performed
2196//  provided:
2197//                * tailcallopt is enabled
2198//                * caller/callee are fastcc
2199//  On X86_64 architecture with GOT-style position independent code only local
2200//  (within module) calls are supported at the moment.
2201//  To keep the stack aligned according to platform abi the function
2202//  GetAlignedArgumentStackSize ensures that argument delta is always multiples
2203//  of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
2204//  If a tail called function callee has more arguments than the caller the
2205//  caller needs to make sure that there is room to move the RETADDR to. This is
2206//  achieved by reserving an area the size of the argument delta right after the
2207//  original REtADDR, but before the saved framepointer or the spilled registers
2208//  e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
2209//  stack layout:
2210//    arg1
2211//    arg2
2212//    RETADDR
2213//    [ new RETADDR
2214//      move area ]
2215//    (possible EBP)
2216//    ESI
2217//    EDI
2218//    local1 ..
2219
2220/// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
2221/// for a 16 byte align requirement.
2222unsigned X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
2223                                                        SelectionDAG& DAG) {
2224  MachineFunction &MF = DAG.getMachineFunction();
2225  const TargetMachine &TM = MF.getTarget();
2226  const TargetFrameInfo &TFI = *TM.getFrameInfo();
2227  unsigned StackAlignment = TFI.getStackAlignment();
2228  uint64_t AlignMask = StackAlignment - 1;
2229  int64_t Offset = StackSize;
2230  uint64_t SlotSize = TD->getPointerSize();
2231  if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
2232    // Number smaller than 12 so just add the difference.
2233    Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
2234  } else {
2235    // Mask out lower bits, add stackalignment once plus the 12 bytes.
2236    Offset = ((~AlignMask) & Offset) + StackAlignment +
2237      (StackAlignment-SlotSize);
2238  }
2239  return Offset;
2240}
2241
2242/// MatchingStackOffset - Return true if the given stack call argument is
2243/// already available in the same position (relatively) of the caller's
2244/// incoming argument stack.
2245static
2246bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
2247                         MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
2248                         const X86InstrInfo *TII) {
2249  unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
2250  int FI = INT_MAX;
2251  if (Arg.getOpcode() == ISD::CopyFromReg) {
2252    unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
2253    if (!VR || TargetRegisterInfo::isPhysicalRegister(VR))
2254      return false;
2255    MachineInstr *Def = MRI->getVRegDef(VR);
2256    if (!Def)
2257      return false;
2258    if (!Flags.isByVal()) {
2259      if (!TII->isLoadFromStackSlot(Def, FI))
2260        return false;
2261    } else {
2262      unsigned Opcode = Def->getOpcode();
2263      if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r) &&
2264          Def->getOperand(1).isFI()) {
2265        FI = Def->getOperand(1).getIndex();
2266        Bytes = Flags.getByValSize();
2267      } else
2268        return false;
2269    }
2270  } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
2271    if (Flags.isByVal())
2272      // ByVal argument is passed in as a pointer but it's now being
2273      // dereferenced. e.g.
2274      // define @foo(%struct.X* %A) {
2275      //   tail call @bar(%struct.X* byval %A)
2276      // }
2277      return false;
2278    SDValue Ptr = Ld->getBasePtr();
2279    FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
2280    if (!FINode)
2281      return false;
2282    FI = FINode->getIndex();
2283  } else
2284    return false;
2285
2286  assert(FI != INT_MAX);
2287  if (!MFI->isFixedObjectIndex(FI))
2288    return false;
2289  return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
2290}
2291
2292/// IsEligibleForTailCallOptimization - Check whether the call is eligible
2293/// for tail call optimization. Targets which want to do tail call
2294/// optimization should implement this function.
2295bool
2296X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
2297                                                     CallingConv::ID CalleeCC,
2298                                                     bool isVarArg,
2299                                                     bool isCalleeStructRet,
2300                                                     bool isCallerStructRet,
2301                                    const SmallVectorImpl<ISD::OutputArg> &Outs,
2302                                    const SmallVectorImpl<ISD::InputArg> &Ins,
2303                                                     SelectionDAG& DAG) const {
2304  if (!IsTailCallConvention(CalleeCC) &&
2305      CalleeCC != CallingConv::C)
2306    return false;
2307
2308  // If -tailcallopt is specified, make fastcc functions tail-callable.
2309  const MachineFunction &MF = DAG.getMachineFunction();
2310  const Function *CallerF = DAG.getMachineFunction().getFunction();
2311  if (GuaranteedTailCallOpt) {
2312    if (IsTailCallConvention(CalleeCC) &&
2313        CallerF->getCallingConv() == CalleeCC)
2314      return true;
2315    return false;
2316  }
2317
2318  // Look for obvious safe cases to perform tail call optimization that does not
2319  // requite ABI changes. This is what gcc calls sibcall.
2320
2321  // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
2322  // emit a special epilogue.
2323  if (RegInfo->needsStackRealignment(MF))
2324    return false;
2325
2326  // Do not sibcall optimize vararg calls unless the call site is not passing any
2327  // arguments.
2328  if (isVarArg && !Outs.empty())
2329    return false;
2330
2331  // Also avoid sibcall optimization if either caller or callee uses struct
2332  // return semantics.
2333  if (isCalleeStructRet || isCallerStructRet)
2334    return false;
2335
2336  // If the call result is in ST0 / ST1, it needs to be popped off the x87 stack.
2337  // Therefore if it's not used by the call it is not safe to optimize this into
2338  // a sibcall.
2339  bool Unused = false;
2340  for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
2341    if (!Ins[i].Used) {
2342      Unused = true;
2343      break;
2344    }
2345  }
2346  if (Unused) {
2347    SmallVector<CCValAssign, 16> RVLocs;
2348    CCState CCInfo(CalleeCC, false, getTargetMachine(),
2349                   RVLocs, *DAG.getContext());
2350    CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2351    for (unsigned i = 0; i != RVLocs.size(); ++i) {
2352      CCValAssign &VA = RVLocs[i];
2353      if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1)
2354        return false;
2355    }
2356  }
2357
2358  // If the callee takes no arguments then go on to check the results of the
2359  // call.
2360  if (!Outs.empty()) {
2361    // Check if stack adjustment is needed. For now, do not do this if any
2362    // argument is passed on the stack.
2363    SmallVector<CCValAssign, 16> ArgLocs;
2364    CCState CCInfo(CalleeCC, isVarArg, getTargetMachine(),
2365                   ArgLocs, *DAG.getContext());
2366    CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForNode(CalleeCC));
2367    if (CCInfo.getNextStackOffset()) {
2368      MachineFunction &MF = DAG.getMachineFunction();
2369      if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
2370        return false;
2371      if (Subtarget->isTargetWin64())
2372        // Win64 ABI has additional complications.
2373        return false;
2374
2375      // Check if the arguments are already laid out in the right way as
2376      // the caller's fixed stack objects.
2377      MachineFrameInfo *MFI = MF.getFrameInfo();
2378      const MachineRegisterInfo *MRI = &MF.getRegInfo();
2379      const X86InstrInfo *TII =
2380        ((X86TargetMachine&)getTargetMachine()).getInstrInfo();
2381      for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2382        CCValAssign &VA = ArgLocs[i];
2383        EVT RegVT = VA.getLocVT();
2384        SDValue Arg = Outs[i].Val;
2385        ISD::ArgFlagsTy Flags = Outs[i].Flags;
2386        if (VA.getLocInfo() == CCValAssign::Indirect)
2387          return false;
2388        if (!VA.isRegLoc()) {
2389          if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2390                                   MFI, MRI, TII))
2391            return false;
2392        }
2393      }
2394    }
2395  }
2396
2397  return true;
2398}
2399
2400FastISel *
2401X86TargetLowering::createFastISel(MachineFunction &mf, MachineModuleInfo *mmo,
2402                            DenseMap<const Value *, unsigned> &vm,
2403                            DenseMap<const BasicBlock*, MachineBasicBlock*> &bm,
2404                            DenseMap<const AllocaInst *, int> &am
2405#ifndef NDEBUG
2406                          , SmallSet<Instruction*, 8> &cil
2407#endif
2408                                  ) {
2409  return X86::createFastISel(mf, mmo, vm, bm, am
2410#ifndef NDEBUG
2411                             , cil
2412#endif
2413                             );
2414}
2415
2416
2417//===----------------------------------------------------------------------===//
2418//                           Other Lowering Hooks
2419//===----------------------------------------------------------------------===//
2420
2421
2422SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) {
2423  MachineFunction &MF = DAG.getMachineFunction();
2424  X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2425  int ReturnAddrIndex = FuncInfo->getRAIndex();
2426
2427  if (ReturnAddrIndex == 0) {
2428    // Set up a frame object for the return address.
2429    uint64_t SlotSize = TD->getPointerSize();
2430    ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize, -SlotSize,
2431                                                           false, false);
2432    FuncInfo->setRAIndex(ReturnAddrIndex);
2433  }
2434
2435  return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
2436}
2437
2438
2439bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
2440                                       bool hasSymbolicDisplacement) {
2441  // Offset should fit into 32 bit immediate field.
2442  if (!isInt<32>(Offset))
2443    return false;
2444
2445  // If we don't have a symbolic displacement - we don't have any extra
2446  // restrictions.
2447  if (!hasSymbolicDisplacement)
2448    return true;
2449
2450  // FIXME: Some tweaks might be needed for medium code model.
2451  if (M != CodeModel::Small && M != CodeModel::Kernel)
2452    return false;
2453
2454  // For small code model we assume that latest object is 16MB before end of 31
2455  // bits boundary. We may also accept pretty large negative constants knowing
2456  // that all objects are in the positive half of address space.
2457  if (M == CodeModel::Small && Offset < 16*1024*1024)
2458    return true;
2459
2460  // For kernel code model we know that all object resist in the negative half
2461  // of 32bits address space. We may not accept negative offsets, since they may
2462  // be just off and we may accept pretty large positive ones.
2463  if (M == CodeModel::Kernel && Offset > 0)
2464    return true;
2465
2466  return false;
2467}
2468
2469/// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
2470/// specific condition code, returning the condition code and the LHS/RHS of the
2471/// comparison to make.
2472static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
2473                               SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
2474  if (!isFP) {
2475    if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
2476      if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
2477        // X > -1   -> X == 0, jump !sign.
2478        RHS = DAG.getConstant(0, RHS.getValueType());
2479        return X86::COND_NS;
2480      } else if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
2481        // X < 0   -> X == 0, jump on sign.
2482        return X86::COND_S;
2483      } else if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
2484        // X < 1   -> X <= 0
2485        RHS = DAG.getConstant(0, RHS.getValueType());
2486        return X86::COND_LE;
2487      }
2488    }
2489
2490    switch (SetCCOpcode) {
2491    default: llvm_unreachable("Invalid integer condition!");
2492    case ISD::SETEQ:  return X86::COND_E;
2493    case ISD::SETGT:  return X86::COND_G;
2494    case ISD::SETGE:  return X86::COND_GE;
2495    case ISD::SETLT:  return X86::COND_L;
2496    case ISD::SETLE:  return X86::COND_LE;
2497    case ISD::SETNE:  return X86::COND_NE;
2498    case ISD::SETULT: return X86::COND_B;
2499    case ISD::SETUGT: return X86::COND_A;
2500    case ISD::SETULE: return X86::COND_BE;
2501    case ISD::SETUGE: return X86::COND_AE;
2502    }
2503  }
2504
2505  // First determine if it is required or is profitable to flip the operands.
2506
2507  // If LHS is a foldable load, but RHS is not, flip the condition.
2508  if ((ISD::isNON_EXTLoad(LHS.getNode()) && LHS.hasOneUse()) &&
2509      !(ISD::isNON_EXTLoad(RHS.getNode()) && RHS.hasOneUse())) {
2510    SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
2511    std::swap(LHS, RHS);
2512  }
2513
2514  switch (SetCCOpcode) {
2515  default: break;
2516  case ISD::SETOLT:
2517  case ISD::SETOLE:
2518  case ISD::SETUGT:
2519  case ISD::SETUGE:
2520    std::swap(LHS, RHS);
2521    break;
2522  }
2523
2524  // On a floating point condition, the flags are set as follows:
2525  // ZF  PF  CF   op
2526  //  0 | 0 | 0 | X > Y
2527  //  0 | 0 | 1 | X < Y
2528  //  1 | 0 | 0 | X == Y
2529  //  1 | 1 | 1 | unordered
2530  switch (SetCCOpcode) {
2531  default: llvm_unreachable("Condcode should be pre-legalized away");
2532  case ISD::SETUEQ:
2533  case ISD::SETEQ:   return X86::COND_E;
2534  case ISD::SETOLT:              // flipped
2535  case ISD::SETOGT:
2536  case ISD::SETGT:   return X86::COND_A;
2537  case ISD::SETOLE:              // flipped
2538  case ISD::SETOGE:
2539  case ISD::SETGE:   return X86::COND_AE;
2540  case ISD::SETUGT:              // flipped
2541  case ISD::SETULT:
2542  case ISD::SETLT:   return X86::COND_B;
2543  case ISD::SETUGE:              // flipped
2544  case ISD::SETULE:
2545  case ISD::SETLE:   return X86::COND_BE;
2546  case ISD::SETONE:
2547  case ISD::SETNE:   return X86::COND_NE;
2548  case ISD::SETUO:   return X86::COND_P;
2549  case ISD::SETO:    return X86::COND_NP;
2550  case ISD::SETOEQ:
2551  case ISD::SETUNE:  return X86::COND_INVALID;
2552  }
2553}
2554
2555/// hasFPCMov - is there a floating point cmov for the specific X86 condition
2556/// code. Current x86 isa includes the following FP cmov instructions:
2557/// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
2558static bool hasFPCMov(unsigned X86CC) {
2559  switch (X86CC) {
2560  default:
2561    return false;
2562  case X86::COND_B:
2563  case X86::COND_BE:
2564  case X86::COND_E:
2565  case X86::COND_P:
2566  case X86::COND_A:
2567  case X86::COND_AE:
2568  case X86::COND_NE:
2569  case X86::COND_NP:
2570    return true;
2571  }
2572}
2573
2574/// isFPImmLegal - Returns true if the target can instruction select the
2575/// specified FP immediate natively. If false, the legalizer will
2576/// materialize the FP immediate as a load from a constant pool.
2577bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
2578  for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
2579    if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
2580      return true;
2581  }
2582  return false;
2583}
2584
2585/// isUndefOrInRange - Return true if Val is undef or if its value falls within
2586/// the specified range (L, H].
2587static bool isUndefOrInRange(int Val, int Low, int Hi) {
2588  return (Val < 0) || (Val >= Low && Val < Hi);
2589}
2590
2591/// isUndefOrEqual - Val is either less than zero (undef) or equal to the
2592/// specified value.
2593static bool isUndefOrEqual(int Val, int CmpVal) {
2594  if (Val < 0 || Val == CmpVal)
2595    return true;
2596  return false;
2597}
2598
2599/// isPSHUFDMask - Return true if the node specifies a shuffle of elements that
2600/// is suitable for input to PSHUFD or PSHUFW.  That is, it doesn't reference
2601/// the second operand.
2602static bool isPSHUFDMask(const SmallVectorImpl<int> &Mask, EVT VT) {
2603  if (VT == MVT::v4f32 || VT == MVT::v4i32 || VT == MVT::v4i16)
2604    return (Mask[0] < 4 && Mask[1] < 4 && Mask[2] < 4 && Mask[3] < 4);
2605  if (VT == MVT::v2f64 || VT == MVT::v2i64)
2606    return (Mask[0] < 2 && Mask[1] < 2);
2607  return false;
2608}
2609
2610bool X86::isPSHUFDMask(ShuffleVectorSDNode *N) {
2611  SmallVector<int, 8> M;
2612  N->getMask(M);
2613  return ::isPSHUFDMask(M, N->getValueType(0));
2614}
2615
2616/// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that
2617/// is suitable for input to PSHUFHW.
2618static bool isPSHUFHWMask(const SmallVectorImpl<int> &Mask, EVT VT) {
2619  if (VT != MVT::v8i16)
2620    return false;
2621
2622  // Lower quadword copied in order or undef.
2623  for (int i = 0; i != 4; ++i)
2624    if (Mask[i] >= 0 && Mask[i] != i)
2625      return false;
2626
2627  // Upper quadword shuffled.
2628  for (int i = 4; i != 8; ++i)
2629    if (Mask[i] >= 0 && (Mask[i] < 4 || Mask[i] > 7))
2630      return false;
2631
2632  return true;
2633}
2634
2635bool X86::isPSHUFHWMask(ShuffleVectorSDNode *N) {
2636  SmallVector<int, 8> M;
2637  N->getMask(M);
2638  return ::isPSHUFHWMask(M, N->getValueType(0));
2639}
2640
2641/// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that
2642/// is suitable for input to PSHUFLW.
2643static bool isPSHUFLWMask(const SmallVectorImpl<int> &Mask, EVT VT) {
2644  if (VT != MVT::v8i16)
2645    return false;
2646
2647  // Upper quadword copied in order.
2648  for (int i = 4; i != 8; ++i)
2649    if (Mask[i] >= 0 && Mask[i] != i)
2650      return false;
2651
2652  // Lower quadword shuffled.
2653  for (int i = 0; i != 4; ++i)
2654    if (Mask[i] >= 4)
2655      return false;
2656
2657  return true;
2658}
2659
2660bool X86::isPSHUFLWMask(ShuffleVectorSDNode *N) {
2661  SmallVector<int, 8> M;
2662  N->getMask(M);
2663  return ::isPSHUFLWMask(M, N->getValueType(0));
2664}
2665
2666/// isPALIGNRMask - Return true if the node specifies a shuffle of elements that
2667/// is suitable for input to PALIGNR.
2668static bool isPALIGNRMask(const SmallVectorImpl<int> &Mask, EVT VT,
2669                          bool hasSSSE3) {
2670  int i, e = VT.getVectorNumElements();
2671
2672  // Do not handle v2i64 / v2f64 shuffles with palignr.
2673  if (e < 4 || !hasSSSE3)
2674    return false;
2675
2676  for (i = 0; i != e; ++i)
2677    if (Mask[i] >= 0)
2678      break;
2679
2680  // All undef, not a palignr.
2681  if (i == e)
2682    return false;
2683
2684  // Determine if it's ok to perform a palignr with only the LHS, since we
2685  // don't have access to the actual shuffle elements to see if RHS is undef.
2686  bool Unary = Mask[i] < (int)e;
2687  bool NeedsUnary = false;
2688
2689  int s = Mask[i] - i;
2690
2691  // Check the rest of the elements to see if they are consecutive.
2692  for (++i; i != e; ++i) {
2693    int m = Mask[i];
2694    if (m < 0)
2695      continue;
2696
2697    Unary = Unary && (m < (int)e);
2698    NeedsUnary = NeedsUnary || (m < s);
2699
2700    if (NeedsUnary && !Unary)
2701      return false;
2702    if (Unary && m != ((s+i) & (e-1)))
2703      return false;
2704    if (!Unary && m != (s+i))
2705      return false;
2706  }
2707  return true;
2708}
2709
2710bool X86::isPALIGNRMask(ShuffleVectorSDNode *N) {
2711  SmallVector<int, 8> M;
2712  N->getMask(M);
2713  return ::isPALIGNRMask(M, N->getValueType(0), true);
2714}
2715
2716/// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
2717/// specifies a shuffle of elements that is suitable for input to SHUFP*.
2718static bool isSHUFPMask(const SmallVectorImpl<int> &Mask, EVT VT) {
2719  int NumElems = VT.getVectorNumElements();
2720  if (NumElems != 2 && NumElems != 4)
2721    return false;
2722
2723  int Half = NumElems / 2;
2724  for (int i = 0; i < Half; ++i)
2725    if (!isUndefOrInRange(Mask[i], 0, NumElems))
2726      return false;
2727  for (int i = Half; i < NumElems; ++i)
2728    if (!isUndefOrInRange(Mask[i], NumElems, NumElems*2))
2729      return false;
2730
2731  return true;
2732}
2733
2734bool X86::isSHUFPMask(ShuffleVectorSDNode *N) {
2735  SmallVector<int, 8> M;
2736  N->getMask(M);
2737  return ::isSHUFPMask(M, N->getValueType(0));
2738}
2739
2740/// isCommutedSHUFP - Returns true if the shuffle mask is exactly
2741/// the reverse of what x86 shuffles want. x86 shuffles requires the lower
2742/// half elements to come from vector 1 (which would equal the dest.) and
2743/// the upper half to come from vector 2.
2744static bool isCommutedSHUFPMask(const SmallVectorImpl<int> &Mask, EVT VT) {
2745  int NumElems = VT.getVectorNumElements();
2746
2747  if (NumElems != 2 && NumElems != 4)
2748    return false;
2749
2750  int Half = NumElems / 2;
2751  for (int i = 0; i < Half; ++i)
2752    if (!isUndefOrInRange(Mask[i], NumElems, NumElems*2))
2753      return false;
2754  for (int i = Half; i < NumElems; ++i)
2755    if (!isUndefOrInRange(Mask[i], 0, NumElems))
2756      return false;
2757  return true;
2758}
2759
2760static bool isCommutedSHUFP(ShuffleVectorSDNode *N) {
2761  SmallVector<int, 8> M;
2762  N->getMask(M);
2763  return isCommutedSHUFPMask(M, N->getValueType(0));
2764}
2765
2766/// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
2767/// specifies a shuffle of elements that is suitable for input to MOVHLPS.
2768bool X86::isMOVHLPSMask(ShuffleVectorSDNode *N) {
2769  if (N->getValueType(0).getVectorNumElements() != 4)
2770    return false;
2771
2772  // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
2773  return isUndefOrEqual(N->getMaskElt(0), 6) &&
2774         isUndefOrEqual(N->getMaskElt(1), 7) &&
2775         isUndefOrEqual(N->getMaskElt(2), 2) &&
2776         isUndefOrEqual(N->getMaskElt(3), 3);
2777}
2778
2779/// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
2780/// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
2781/// <2, 3, 2, 3>
2782bool X86::isMOVHLPS_v_undef_Mask(ShuffleVectorSDNode *N) {
2783  unsigned NumElems = N->getValueType(0).getVectorNumElements();
2784
2785  if (NumElems != 4)
2786    return false;
2787
2788  return isUndefOrEqual(N->getMaskElt(0), 2) &&
2789  isUndefOrEqual(N->getMaskElt(1), 3) &&
2790  isUndefOrEqual(N->getMaskElt(2), 2) &&
2791  isUndefOrEqual(N->getMaskElt(3), 3);
2792}
2793
2794/// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
2795/// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
2796bool X86::isMOVLPMask(ShuffleVectorSDNode *N) {
2797  unsigned NumElems = N->getValueType(0).getVectorNumElements();
2798
2799  if (NumElems != 2 && NumElems != 4)
2800    return false;
2801
2802  for (unsigned i = 0; i < NumElems/2; ++i)
2803    if (!isUndefOrEqual(N->getMaskElt(i), i + NumElems))
2804      return false;
2805
2806  for (unsigned i = NumElems/2; i < NumElems; ++i)
2807    if (!isUndefOrEqual(N->getMaskElt(i), i))
2808      return false;
2809
2810  return true;
2811}
2812
2813/// isMOVLHPSMask - Return true if the specified VECTOR_SHUFFLE operand
2814/// specifies a shuffle of elements that is suitable for input to MOVLHPS.
2815bool X86::isMOVLHPSMask(ShuffleVectorSDNode *N) {
2816  unsigned NumElems = N->getValueType(0).getVectorNumElements();
2817
2818  if (NumElems != 2 && NumElems != 4)
2819    return false;
2820
2821  for (unsigned i = 0; i < NumElems/2; ++i)
2822    if (!isUndefOrEqual(N->getMaskElt(i), i))
2823      return false;
2824
2825  for (unsigned i = 0; i < NumElems/2; ++i)
2826    if (!isUndefOrEqual(N->getMaskElt(i + NumElems/2), i + NumElems))
2827      return false;
2828
2829  return true;
2830}
2831
2832/// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
2833/// specifies a shuffle of elements that is suitable for input to UNPCKL.
2834static bool isUNPCKLMask(const SmallVectorImpl<int> &Mask, EVT VT,
2835                         bool V2IsSplat = false) {
2836  int NumElts = VT.getVectorNumElements();
2837  if (NumElts != 2 && NumElts != 4 && NumElts != 8 && NumElts != 16)
2838    return false;
2839
2840  for (int i = 0, j = 0; i != NumElts; i += 2, ++j) {
2841    int BitI  = Mask[i];
2842    int BitI1 = Mask[i+1];
2843    if (!isUndefOrEqual(BitI, j))
2844      return false;
2845    if (V2IsSplat) {
2846      if (!isUndefOrEqual(BitI1, NumElts))
2847        return false;
2848    } else {
2849      if (!isUndefOrEqual(BitI1, j + NumElts))
2850        return false;
2851    }
2852  }
2853  return true;
2854}
2855
2856bool X86::isUNPCKLMask(ShuffleVectorSDNode *N, bool V2IsSplat) {
2857  SmallVector<int, 8> M;
2858  N->getMask(M);
2859  return ::isUNPCKLMask(M, N->getValueType(0), V2IsSplat);
2860}
2861
2862/// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
2863/// specifies a shuffle of elements that is suitable for input to UNPCKH.
2864static bool isUNPCKHMask(const SmallVectorImpl<int> &Mask, EVT VT,
2865                         bool V2IsSplat = false) {
2866  int NumElts = VT.getVectorNumElements();
2867  if (NumElts != 2 && NumElts != 4 && NumElts != 8 && NumElts != 16)
2868    return false;
2869
2870  for (int i = 0, j = 0; i != NumElts; i += 2, ++j) {
2871    int BitI  = Mask[i];
2872    int BitI1 = Mask[i+1];
2873    if (!isUndefOrEqual(BitI, j + NumElts/2))
2874      return false;
2875    if (V2IsSplat) {
2876      if (isUndefOrEqual(BitI1, NumElts))
2877        return false;
2878    } else {
2879      if (!isUndefOrEqual(BitI1, j + NumElts/2 + NumElts))
2880        return false;
2881    }
2882  }
2883  return true;
2884}
2885
2886bool X86::isUNPCKHMask(ShuffleVectorSDNode *N, bool V2IsSplat) {
2887  SmallVector<int, 8> M;
2888  N->getMask(M);
2889  return ::isUNPCKHMask(M, N->getValueType(0), V2IsSplat);
2890}
2891
2892/// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
2893/// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
2894/// <0, 0, 1, 1>
2895static bool isUNPCKL_v_undef_Mask(const SmallVectorImpl<int> &Mask, EVT VT) {
2896  int NumElems = VT.getVectorNumElements();
2897  if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
2898    return false;
2899
2900  for (int i = 0, j = 0; i != NumElems; i += 2, ++j) {
2901    int BitI  = Mask[i];
2902    int BitI1 = Mask[i+1];
2903    if (!isUndefOrEqual(BitI, j))
2904      return false;
2905    if (!isUndefOrEqual(BitI1, j))
2906      return false;
2907  }
2908  return true;
2909}
2910
2911bool X86::isUNPCKL_v_undef_Mask(ShuffleVectorSDNode *N) {
2912  SmallVector<int, 8> M;
2913  N->getMask(M);
2914  return ::isUNPCKL_v_undef_Mask(M, N->getValueType(0));
2915}
2916
2917/// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
2918/// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
2919/// <2, 2, 3, 3>
2920static bool isUNPCKH_v_undef_Mask(const SmallVectorImpl<int> &Mask, EVT VT) {
2921  int NumElems = VT.getVectorNumElements();
2922  if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
2923    return false;
2924
2925  for (int i = 0, j = NumElems / 2; i != NumElems; i += 2, ++j) {
2926    int BitI  = Mask[i];
2927    int BitI1 = Mask[i+1];
2928    if (!isUndefOrEqual(BitI, j))
2929      return false;
2930    if (!isUndefOrEqual(BitI1, j))
2931      return false;
2932  }
2933  return true;
2934}
2935
2936bool X86::isUNPCKH_v_undef_Mask(ShuffleVectorSDNode *N) {
2937  SmallVector<int, 8> M;
2938  N->getMask(M);
2939  return ::isUNPCKH_v_undef_Mask(M, N->getValueType(0));
2940}
2941
2942/// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
2943/// specifies a shuffle of elements that is suitable for input to MOVSS,
2944/// MOVSD, and MOVD, i.e. setting the lowest element.
2945static bool isMOVLMask(const SmallVectorImpl<int> &Mask, EVT VT) {
2946  if (VT.getVectorElementType().getSizeInBits() < 32)
2947    return false;
2948
2949  int NumElts = VT.getVectorNumElements();
2950
2951  if (!isUndefOrEqual(Mask[0], NumElts))
2952    return false;
2953
2954  for (int i = 1; i < NumElts; ++i)
2955    if (!isUndefOrEqual(Mask[i], i))
2956      return false;
2957
2958  return true;
2959}
2960
2961bool X86::isMOVLMask(ShuffleVectorSDNode *N) {
2962  SmallVector<int, 8> M;
2963  N->getMask(M);
2964  return ::isMOVLMask(M, N->getValueType(0));
2965}
2966
2967/// isCommutedMOVL - Returns true if the shuffle mask is except the reverse
2968/// of what x86 movss want. X86 movs requires the lowest  element to be lowest
2969/// element of vector 2 and the other elements to come from vector 1 in order.
2970static bool isCommutedMOVLMask(const SmallVectorImpl<int> &Mask, EVT VT,
2971                               bool V2IsSplat = false, bool V2IsUndef = false) {
2972  int NumOps = VT.getVectorNumElements();
2973  if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
2974    return false;
2975
2976  if (!isUndefOrEqual(Mask[0], 0))
2977    return false;
2978
2979  for (int i = 1; i < NumOps; ++i)
2980    if (!(isUndefOrEqual(Mask[i], i+NumOps) ||
2981          (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) ||
2982          (V2IsSplat && isUndefOrEqual(Mask[i], NumOps))))
2983      return false;
2984
2985  return true;
2986}
2987
2988static bool isCommutedMOVL(ShuffleVectorSDNode *N, bool V2IsSplat = false,
2989                           bool V2IsUndef = false) {
2990  SmallVector<int, 8> M;
2991  N->getMask(M);
2992  return isCommutedMOVLMask(M, N->getValueType(0), V2IsSplat, V2IsUndef);
2993}
2994
2995/// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
2996/// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
2997bool X86::isMOVSHDUPMask(ShuffleVectorSDNode *N) {
2998  if (N->getValueType(0).getVectorNumElements() != 4)
2999    return false;
3000
3001  // Expect 1, 1, 3, 3
3002  for (unsigned i = 0; i < 2; ++i) {
3003    int Elt = N->getMaskElt(i);
3004    if (Elt >= 0 && Elt != 1)
3005      return false;
3006  }
3007
3008  bool HasHi = false;
3009  for (unsigned i = 2; i < 4; ++i) {
3010    int Elt = N->getMaskElt(i);
3011    if (Elt >= 0 && Elt != 3)
3012      return false;
3013    if (Elt == 3)
3014      HasHi = true;
3015  }
3016  // Don't use movshdup if it can be done with a shufps.
3017  // FIXME: verify that matching u, u, 3, 3 is what we want.
3018  return HasHi;
3019}
3020
3021/// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3022/// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
3023bool X86::isMOVSLDUPMask(ShuffleVectorSDNode *N) {
3024  if (N->getValueType(0).getVectorNumElements() != 4)
3025    return false;
3026
3027  // Expect 0, 0, 2, 2
3028  for (unsigned i = 0; i < 2; ++i)
3029    if (N->getMaskElt(i) > 0)
3030      return false;
3031
3032  bool HasHi = false;
3033  for (unsigned i = 2; i < 4; ++i) {
3034    int Elt = N->getMaskElt(i);
3035    if (Elt >= 0 && Elt != 2)
3036      return false;
3037    if (Elt == 2)
3038      HasHi = true;
3039  }
3040  // Don't use movsldup if it can be done with a shufps.
3041  return HasHi;
3042}
3043
3044/// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3045/// specifies a shuffle of elements that is suitable for input to MOVDDUP.
3046bool X86::isMOVDDUPMask(ShuffleVectorSDNode *N) {
3047  int e = N->getValueType(0).getVectorNumElements() / 2;
3048
3049  for (int i = 0; i < e; ++i)
3050    if (!isUndefOrEqual(N->getMaskElt(i), i))
3051      return false;
3052  for (int i = 0; i < e; ++i)
3053    if (!isUndefOrEqual(N->getMaskElt(e+i), i))
3054      return false;
3055  return true;
3056}
3057
3058/// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
3059/// the specified VECTOR_SHUFFLE mask with PSHUF* and SHUFP* instructions.
3060unsigned X86::getShuffleSHUFImmediate(SDNode *N) {
3061  ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3062  int NumOperands = SVOp->getValueType(0).getVectorNumElements();
3063
3064  unsigned Shift = (NumOperands == 4) ? 2 : 1;
3065  unsigned Mask = 0;
3066  for (int i = 0; i < NumOperands; ++i) {
3067    int Val = SVOp->getMaskElt(NumOperands-i-1);
3068    if (Val < 0) Val = 0;
3069    if (Val >= NumOperands) Val -= NumOperands;
3070    Mask |= Val;
3071    if (i != NumOperands - 1)
3072      Mask <<= Shift;
3073  }
3074  return Mask;
3075}
3076
3077/// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
3078/// the specified VECTOR_SHUFFLE mask with the PSHUFHW instruction.
3079unsigned X86::getShufflePSHUFHWImmediate(SDNode *N) {
3080  ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3081  unsigned Mask = 0;
3082  // 8 nodes, but we only care about the last 4.
3083  for (unsigned i = 7; i >= 4; --i) {
3084    int Val = SVOp->getMaskElt(i);
3085    if (Val >= 0)
3086      Mask |= (Val - 4);
3087    if (i != 4)
3088      Mask <<= 2;
3089  }
3090  return Mask;
3091}
3092
3093/// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
3094/// the specified VECTOR_SHUFFLE mask with the PSHUFLW instruction.
3095unsigned X86::getShufflePSHUFLWImmediate(SDNode *N) {
3096  ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3097  unsigned Mask = 0;
3098  // 8 nodes, but we only care about the first 4.
3099  for (int i = 3; i >= 0; --i) {
3100    int Val = SVOp->getMaskElt(i);
3101    if (Val >= 0)
3102      Mask |= Val;
3103    if (i != 0)
3104      Mask <<= 2;
3105  }
3106  return Mask;
3107}
3108
3109/// getShufflePALIGNRImmediate - Return the appropriate immediate to shuffle
3110/// the specified VECTOR_SHUFFLE mask with the PALIGNR instruction.
3111unsigned X86::getShufflePALIGNRImmediate(SDNode *N) {
3112  ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3113  EVT VVT = N->getValueType(0);
3114  unsigned EltSize = VVT.getVectorElementType().getSizeInBits() >> 3;
3115  int Val = 0;
3116
3117  unsigned i, e;
3118  for (i = 0, e = VVT.getVectorNumElements(); i != e; ++i) {
3119    Val = SVOp->getMaskElt(i);
3120    if (Val >= 0)
3121      break;
3122  }
3123  return (Val - i) * EltSize;
3124}
3125
3126/// isZeroNode - Returns true if Elt is a constant zero or a floating point
3127/// constant +0.0.
3128bool X86::isZeroNode(SDValue Elt) {
3129  return ((isa<ConstantSDNode>(Elt) &&
3130           cast<ConstantSDNode>(Elt)->getZExtValue() == 0) ||
3131          (isa<ConstantFPSDNode>(Elt) &&
3132           cast<ConstantFPSDNode>(Elt)->getValueAPF().isPosZero()));
3133}
3134
3135/// CommuteVectorShuffle - Swap vector_shuffle operands as well as values in
3136/// their permute mask.
3137static SDValue CommuteVectorShuffle(ShuffleVectorSDNode *SVOp,
3138                                    SelectionDAG &DAG) {
3139  EVT VT = SVOp->getValueType(0);
3140  unsigned NumElems = VT.getVectorNumElements();
3141  SmallVector<int, 8> MaskVec;
3142
3143  for (unsigned i = 0; i != NumElems; ++i) {
3144    int idx = SVOp->getMaskElt(i);
3145    if (idx < 0)
3146      MaskVec.push_back(idx);
3147    else if (idx < (int)NumElems)
3148      MaskVec.push_back(idx + NumElems);
3149    else
3150      MaskVec.push_back(idx - NumElems);
3151  }
3152  return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(1),
3153                              SVOp->getOperand(0), &MaskVec[0]);
3154}
3155
3156/// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
3157/// the two vector operands have swapped position.
3158static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask, EVT VT) {
3159  unsigned NumElems = VT.getVectorNumElements();
3160  for (unsigned i = 0; i != NumElems; ++i) {
3161    int idx = Mask[i];
3162    if (idx < 0)
3163      continue;
3164    else if (idx < (int)NumElems)
3165      Mask[i] = idx + NumElems;
3166    else
3167      Mask[i] = idx - NumElems;
3168  }
3169}
3170
3171/// ShouldXformToMOVHLPS - Return true if the node should be transformed to
3172/// match movhlps. The lower half elements should come from upper half of
3173/// V1 (and in order), and the upper half elements should come from the upper
3174/// half of V2 (and in order).
3175static bool ShouldXformToMOVHLPS(ShuffleVectorSDNode *Op) {
3176  if (Op->getValueType(0).getVectorNumElements() != 4)
3177    return false;
3178  for (unsigned i = 0, e = 2; i != e; ++i)
3179    if (!isUndefOrEqual(Op->getMaskElt(i), i+2))
3180      return false;
3181  for (unsigned i = 2; i != 4; ++i)
3182    if (!isUndefOrEqual(Op->getMaskElt(i), i+4))
3183      return false;
3184  return true;
3185}
3186
3187/// isScalarLoadToVector - Returns true if the node is a scalar load that
3188/// is promoted to a vector. It also returns the LoadSDNode by reference if
3189/// required.
3190static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = NULL) {
3191  if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
3192    return false;
3193  N = N->getOperand(0).getNode();
3194  if (!ISD::isNON_EXTLoad(N))
3195    return false;
3196  if (LD)
3197    *LD = cast<LoadSDNode>(N);
3198  return true;
3199}
3200
3201/// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
3202/// match movlp{s|d}. The lower half elements should come from lower half of
3203/// V1 (and in order), and the upper half elements should come from the upper
3204/// half of V2 (and in order). And since V1 will become the source of the
3205/// MOVLP, it must be either a vector load or a scalar load to vector.
3206static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2,
3207                               ShuffleVectorSDNode *Op) {
3208  if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
3209    return false;
3210  // Is V2 is a vector load, don't do this transformation. We will try to use
3211  // load folding shufps op.
3212  if (ISD::isNON_EXTLoad(V2))
3213    return false;
3214
3215  unsigned NumElems = Op->getValueType(0).getVectorNumElements();
3216
3217  if (NumElems != 2 && NumElems != 4)
3218    return false;
3219  for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3220    if (!isUndefOrEqual(Op->getMaskElt(i), i))
3221      return false;
3222  for (unsigned i = NumElems/2; i != NumElems; ++i)
3223    if (!isUndefOrEqual(Op->getMaskElt(i), i+NumElems))
3224      return false;
3225  return true;
3226}
3227
3228/// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
3229/// all the same.
3230static bool isSplatVector(SDNode *N) {
3231  if (N->getOpcode() != ISD::BUILD_VECTOR)
3232    return false;
3233
3234  SDValue SplatValue = N->getOperand(0);
3235  for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
3236    if (N->getOperand(i) != SplatValue)
3237      return false;
3238  return true;
3239}
3240
3241/// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
3242/// to an zero vector.
3243/// FIXME: move to dag combiner / method on ShuffleVectorSDNode
3244static bool isZeroShuffle(ShuffleVectorSDNode *N) {
3245  SDValue V1 = N->getOperand(0);
3246  SDValue V2 = N->getOperand(1);
3247  unsigned NumElems = N->getValueType(0).getVectorNumElements();
3248  for (unsigned i = 0; i != NumElems; ++i) {
3249    int Idx = N->getMaskElt(i);
3250    if (Idx >= (int)NumElems) {
3251      unsigned Opc = V2.getOpcode();
3252      if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
3253        continue;
3254      if (Opc != ISD::BUILD_VECTOR ||
3255          !X86::isZeroNode(V2.getOperand(Idx-NumElems)))
3256        return false;
3257    } else if (Idx >= 0) {
3258      unsigned Opc = V1.getOpcode();
3259      if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
3260        continue;
3261      if (Opc != ISD::BUILD_VECTOR ||
3262          !X86::isZeroNode(V1.getOperand(Idx)))
3263        return false;
3264    }
3265  }
3266  return true;
3267}
3268
3269/// getZeroVector - Returns a vector of specified type with all zero elements.
3270///
3271static SDValue getZeroVector(EVT VT, bool HasSSE2, SelectionDAG &DAG,
3272                             DebugLoc dl) {
3273  assert(VT.isVector() && "Expected a vector type");
3274
3275  // Always build zero vectors as <4 x i32> or <2 x i32> bitcasted to their dest
3276  // type.  This ensures they get CSE'd.
3277  SDValue Vec;
3278  if (VT.getSizeInBits() == 64) { // MMX
3279    SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
3280    Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2i32, Cst, Cst);
3281  } else if (HasSSE2) {  // SSE2
3282    SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
3283    Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
3284  } else { // SSE1
3285    SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
3286    Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
3287  }
3288  return DAG.getNode(ISD::BIT_CONVERT, dl, VT, Vec);
3289}
3290
3291/// getOnesVector - Returns a vector of specified type with all bits set.
3292///
3293static SDValue getOnesVector(EVT VT, SelectionDAG &DAG, DebugLoc dl) {
3294  assert(VT.isVector() && "Expected a vector type");
3295
3296  // Always build ones vectors as <4 x i32> or <2 x i32> bitcasted to their dest
3297  // type.  This ensures they get CSE'd.
3298  SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
3299  SDValue Vec;
3300  if (VT.getSizeInBits() == 64)  // MMX
3301    Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2i32, Cst, Cst);
3302  else                                              // SSE
3303    Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
3304  return DAG.getNode(ISD::BIT_CONVERT, dl, VT, Vec);
3305}
3306
3307
3308/// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
3309/// that point to V2 points to its first element.
3310static SDValue NormalizeMask(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
3311  EVT VT = SVOp->getValueType(0);
3312  unsigned NumElems = VT.getVectorNumElements();
3313
3314  bool Changed = false;
3315  SmallVector<int, 8> MaskVec;
3316  SVOp->getMask(MaskVec);
3317
3318  for (unsigned i = 0; i != NumElems; ++i) {
3319    if (MaskVec[i] > (int)NumElems) {
3320      MaskVec[i] = NumElems;
3321      Changed = true;
3322    }
3323  }
3324  if (Changed)
3325    return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(0),
3326                                SVOp->getOperand(1), &MaskVec[0]);
3327  return SDValue(SVOp, 0);
3328}
3329
3330/// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
3331/// operation of specified width.
3332static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
3333                       SDValue V2) {
3334  unsigned NumElems = VT.getVectorNumElements();
3335  SmallVector<int, 8> Mask;
3336  Mask.push_back(NumElems);
3337  for (unsigned i = 1; i != NumElems; ++i)
3338    Mask.push_back(i);
3339  return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
3340}
3341
3342/// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
3343static SDValue getUnpackl(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
3344                          SDValue V2) {
3345  unsigned NumElems = VT.getVectorNumElements();
3346  SmallVector<int, 8> Mask;
3347  for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
3348    Mask.push_back(i);
3349    Mask.push_back(i + NumElems);
3350  }
3351  return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
3352}
3353
3354/// getUnpackhMask - Returns a vector_shuffle node for an unpackh operation.
3355static SDValue getUnpackh(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
3356                          SDValue V2) {
3357  unsigned NumElems = VT.getVectorNumElements();
3358  unsigned Half = NumElems/2;
3359  SmallVector<int, 8> Mask;
3360  for (unsigned i = 0; i != Half; ++i) {
3361    Mask.push_back(i + Half);
3362    Mask.push_back(i + NumElems + Half);
3363  }
3364  return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
3365}
3366
3367/// PromoteSplat - Promote a splat of v4f32, v8i16 or v16i8 to v4i32.
3368static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG,
3369                            bool HasSSE2) {
3370  if (SV->getValueType(0).getVectorNumElements() <= 4)
3371    return SDValue(SV, 0);
3372
3373  EVT PVT = MVT::v4f32;
3374  EVT VT = SV->getValueType(0);
3375  DebugLoc dl = SV->getDebugLoc();
3376  SDValue V1 = SV->getOperand(0);
3377  int NumElems = VT.getVectorNumElements();
3378  int EltNo = SV->getSplatIndex();
3379
3380  // unpack elements to the correct location
3381  while (NumElems > 4) {
3382    if (EltNo < NumElems/2) {
3383      V1 = getUnpackl(DAG, dl, VT, V1, V1);
3384    } else {
3385      V1 = getUnpackh(DAG, dl, VT, V1, V1);
3386      EltNo -= NumElems/2;
3387    }
3388    NumElems >>= 1;
3389  }
3390
3391  // Perform the splat.
3392  int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo };
3393  V1 = DAG.getNode(ISD::BIT_CONVERT, dl, PVT, V1);
3394  V1 = DAG.getVectorShuffle(PVT, dl, V1, DAG.getUNDEF(PVT), &SplatMask[0]);
3395  return DAG.getNode(ISD::BIT_CONVERT, dl, VT, V1);
3396}
3397
3398/// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
3399/// vector of zero or undef vector.  This produces a shuffle where the low
3400/// element of V2 is swizzled into the zero/undef vector, landing at element
3401/// Idx.  This produces a shuffle mask like 4,1,2,3 (idx=0) or  0,1,2,4 (idx=3).
3402static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
3403                                             bool isZero, bool HasSSE2,
3404                                             SelectionDAG &DAG) {
3405  EVT VT = V2.getValueType();
3406  SDValue V1 = isZero
3407    ? getZeroVector(VT, HasSSE2, DAG, V2.getDebugLoc()) : DAG.getUNDEF(VT);
3408  unsigned NumElems = VT.getVectorNumElements();
3409  SmallVector<int, 16> MaskVec;
3410  for (unsigned i = 0; i != NumElems; ++i)
3411    // If this is the insertion idx, put the low elt of V2 here.
3412    MaskVec.push_back(i == Idx ? NumElems : i);
3413  return DAG.getVectorShuffle(VT, V2.getDebugLoc(), V1, V2, &MaskVec[0]);
3414}
3415
3416/// getNumOfConsecutiveZeros - Return the number of elements in a result of
3417/// a shuffle that is zero.
3418static
3419unsigned getNumOfConsecutiveZeros(ShuffleVectorSDNode *SVOp, int NumElems,
3420                                  bool Low, SelectionDAG &DAG) {
3421  unsigned NumZeros = 0;
3422  for (int i = 0; i < NumElems; ++i) {
3423    unsigned Index = Low ? i : NumElems-i-1;
3424    int Idx = SVOp->getMaskElt(Index);
3425    if (Idx < 0) {
3426      ++NumZeros;
3427      continue;
3428    }
3429    SDValue Elt = DAG.getShuffleScalarElt(SVOp, Index);
3430    if (Elt.getNode() && X86::isZeroNode(Elt))
3431      ++NumZeros;
3432    else
3433      break;
3434  }
3435  return NumZeros;
3436}
3437
3438/// isVectorShift - Returns true if the shuffle can be implemented as a
3439/// logical left or right shift of a vector.
3440/// FIXME: split into pslldqi, psrldqi, palignr variants.
3441static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
3442                          bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
3443  int NumElems = SVOp->getValueType(0).getVectorNumElements();
3444
3445  isLeft = true;
3446  unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems, true, DAG);
3447  if (!NumZeros) {
3448    isLeft = false;
3449    NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems, false, DAG);
3450    if (!NumZeros)
3451      return false;
3452  }
3453  bool SeenV1 = false;
3454  bool SeenV2 = false;
3455  for (int i = NumZeros; i < NumElems; ++i) {
3456    int Val = isLeft ? (i - NumZeros) : i;
3457    int Idx = SVOp->getMaskElt(isLeft ? i : (i - NumZeros));
3458    if (Idx < 0)
3459      continue;
3460    if (Idx < NumElems)
3461      SeenV1 = true;
3462    else {
3463      Idx -= NumElems;
3464      SeenV2 = true;
3465    }
3466    if (Idx != Val)
3467      return false;
3468  }
3469  if (SeenV1 && SeenV2)
3470    return false;
3471
3472  ShVal = SeenV1 ? SVOp->getOperand(0) : SVOp->getOperand(1);
3473  ShAmt = NumZeros;
3474  return true;
3475}
3476
3477
3478/// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
3479///
3480static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
3481                                       unsigned NumNonZero, unsigned NumZero,
3482                                       SelectionDAG &DAG, TargetLowering &TLI) {
3483  if (NumNonZero > 8)
3484    return SDValue();
3485
3486  DebugLoc dl = Op.getDebugLoc();
3487  SDValue V(0, 0);
3488  bool First = true;
3489  for (unsigned i = 0; i < 16; ++i) {
3490    bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
3491    if (ThisIsNonZero && First) {
3492      if (NumZero)
3493        V = getZeroVector(MVT::v8i16, true, DAG, dl);
3494      else
3495        V = DAG.getUNDEF(MVT::v8i16);
3496      First = false;
3497    }
3498
3499    if ((i & 1) != 0) {
3500      SDValue ThisElt(0, 0), LastElt(0, 0);
3501      bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
3502      if (LastIsNonZero) {
3503        LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
3504                              MVT::i16, Op.getOperand(i-1));
3505      }
3506      if (ThisIsNonZero) {
3507        ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
3508        ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
3509                              ThisElt, DAG.getConstant(8, MVT::i8));
3510        if (LastIsNonZero)
3511          ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
3512      } else
3513        ThisElt = LastElt;
3514
3515      if (ThisElt.getNode())
3516        V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
3517                        DAG.getIntPtrConstant(i/2));
3518    }
3519  }
3520
3521  return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v16i8, V);
3522}
3523
3524/// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
3525///
3526static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
3527                                       unsigned NumNonZero, unsigned NumZero,
3528                                       SelectionDAG &DAG, TargetLowering &TLI) {
3529  if (NumNonZero > 4)
3530    return SDValue();
3531
3532  DebugLoc dl = Op.getDebugLoc();
3533  SDValue V(0, 0);
3534  bool First = true;
3535  for (unsigned i = 0; i < 8; ++i) {
3536    bool isNonZero = (NonZeros & (1 << i)) != 0;
3537    if (isNonZero) {
3538      if (First) {
3539        if (NumZero)
3540          V = getZeroVector(MVT::v8i16, true, DAG, dl);
3541        else
3542          V = DAG.getUNDEF(MVT::v8i16);
3543        First = false;
3544      }
3545      V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
3546                      MVT::v8i16, V, Op.getOperand(i),
3547                      DAG.getIntPtrConstant(i));
3548    }
3549  }
3550
3551  return V;
3552}
3553
3554/// getVShift - Return a vector logical shift node.
3555///
3556static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
3557                         unsigned NumBits, SelectionDAG &DAG,
3558                         const TargetLowering &TLI, DebugLoc dl) {
3559  bool isMMX = VT.getSizeInBits() == 64;
3560  EVT ShVT = isMMX ? MVT::v1i64 : MVT::v2i64;
3561  unsigned Opc = isLeft ? X86ISD::VSHL : X86ISD::VSRL;
3562  SrcOp = DAG.getNode(ISD::BIT_CONVERT, dl, ShVT, SrcOp);
3563  return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
3564                     DAG.getNode(Opc, dl, ShVT, SrcOp,
3565                             DAG.getConstant(NumBits, TLI.getShiftAmountTy())));
3566}
3567
3568SDValue
3569X86TargetLowering::LowerAsSplatVectorLoad(SDValue SrcOp, EVT VT, DebugLoc dl,
3570                                          SelectionDAG &DAG) {
3571
3572  // Check if the scalar load can be widened into a vector load. And if
3573  // the address is "base + cst" see if the cst can be "absorbed" into
3574  // the shuffle mask.
3575  if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
3576    SDValue Ptr = LD->getBasePtr();
3577    if (!ISD::isNormalLoad(LD) || LD->isVolatile())
3578      return SDValue();
3579    EVT PVT = LD->getValueType(0);
3580    if (PVT != MVT::i32 && PVT != MVT::f32)
3581      return SDValue();
3582
3583    int FI = -1;
3584    int64_t Offset = 0;
3585    if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
3586      FI = FINode->getIndex();
3587      Offset = 0;
3588    } else if (Ptr.getOpcode() == ISD::ADD &&
3589               isa<ConstantSDNode>(Ptr.getOperand(1)) &&
3590               isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
3591      FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
3592      Offset = Ptr.getConstantOperandVal(1);
3593      Ptr = Ptr.getOperand(0);
3594    } else {
3595      return SDValue();
3596    }
3597
3598    SDValue Chain = LD->getChain();
3599    // Make sure the stack object alignment is at least 16.
3600    MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
3601    if (DAG.InferPtrAlignment(Ptr) < 16) {
3602      if (MFI->isFixedObjectIndex(FI)) {
3603        // Can't change the alignment. FIXME: It's possible to compute
3604        // the exact stack offset and reference FI + adjust offset instead.
3605        // If someone *really* cares about this. That's the way to implement it.
3606        return SDValue();
3607      } else {
3608        MFI->setObjectAlignment(FI, 16);
3609      }
3610    }
3611
3612    // (Offset % 16) must be multiple of 4. Then address is then
3613    // Ptr + (Offset & ~15).
3614    if (Offset < 0)
3615      return SDValue();
3616    if ((Offset % 16) & 3)
3617      return SDValue();
3618    int64_t StartOffset = Offset & ~15;
3619    if (StartOffset)
3620      Ptr = DAG.getNode(ISD::ADD, Ptr.getDebugLoc(), Ptr.getValueType(),
3621                        Ptr,DAG.getConstant(StartOffset, Ptr.getValueType()));
3622
3623    int EltNo = (Offset - StartOffset) >> 2;
3624    int Mask[4] = { EltNo, EltNo, EltNo, EltNo };
3625    EVT VT = (PVT == MVT::i32) ? MVT::v4i32 : MVT::v4f32;
3626    SDValue V1 = DAG.getLoad(VT, dl, Chain, Ptr,LD->getSrcValue(),0,
3627                             false, false, 0);
3628    // Canonicalize it to a v4i32 shuffle.
3629    V1 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v4i32, V1);
3630    return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
3631                       DAG.getVectorShuffle(MVT::v4i32, dl, V1,
3632                                            DAG.getUNDEF(MVT::v4i32), &Mask[0]));
3633  }
3634
3635  return SDValue();
3636}
3637
3638/// EltsFromConsecutiveLoads - Given the initializing elements 'Elts' of a
3639/// vector of type 'VT', see if the elements can be replaced by a single large
3640/// load which has the same value as a build_vector whose operands are 'elts'.
3641///
3642/// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
3643///
3644/// FIXME: we'd also like to handle the case where the last elements are zero
3645/// rather than undef via VZEXT_LOAD, but we do not detect that case today.
3646/// There's even a handy isZeroNode for that purpose.
3647static SDValue EltsFromConsecutiveLoads(EVT VT, SmallVectorImpl<SDValue> &Elts,
3648                                        DebugLoc &dl, SelectionDAG &DAG) {
3649  EVT EltVT = VT.getVectorElementType();
3650  unsigned NumElems = Elts.size();
3651
3652  LoadSDNode *LDBase = NULL;
3653  unsigned LastLoadedElt = -1U;
3654
3655  // For each element in the initializer, see if we've found a load or an undef.
3656  // If we don't find an initial load element, or later load elements are
3657  // non-consecutive, bail out.
3658  for (unsigned i = 0; i < NumElems; ++i) {
3659    SDValue Elt = Elts[i];
3660
3661    if (!Elt.getNode() ||
3662        (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
3663      return SDValue();
3664    if (!LDBase) {
3665      if (Elt.getNode()->getOpcode() == ISD::UNDEF)
3666        return SDValue();
3667      LDBase = cast<LoadSDNode>(Elt.getNode());
3668      LastLoadedElt = i;
3669      continue;
3670    }
3671    if (Elt.getOpcode() == ISD::UNDEF)
3672      continue;
3673
3674    LoadSDNode *LD = cast<LoadSDNode>(Elt);
3675    if (!DAG.isConsecutiveLoad(LD, LDBase, EltVT.getSizeInBits()/8, i))
3676      return SDValue();
3677    LastLoadedElt = i;
3678  }
3679
3680  // If we have found an entire vector of loads and undefs, then return a large
3681  // load of the entire vector width starting at the base pointer.  If we found
3682  // consecutive loads for the low half, generate a vzext_load node.
3683  if (LastLoadedElt == NumElems - 1) {
3684    if (DAG.InferPtrAlignment(LDBase->getBasePtr()) >= 16)
3685      return DAG.getLoad(VT, dl, LDBase->getChain(), LDBase->getBasePtr(),
3686                         LDBase->getSrcValue(), LDBase->getSrcValueOffset(),
3687                         LDBase->isVolatile(), LDBase->isNonTemporal(), 0);
3688    return DAG.getLoad(VT, dl, LDBase->getChain(), LDBase->getBasePtr(),
3689                       LDBase->getSrcValue(), LDBase->getSrcValueOffset(),
3690                       LDBase->isVolatile(), LDBase->isNonTemporal(),
3691                       LDBase->getAlignment());
3692  } else if (NumElems == 4 && LastLoadedElt == 1) {
3693    SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
3694    SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
3695    SDValue ResNode = DAG.getNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops, 2);
3696    return DAG.getNode(ISD::BIT_CONVERT, dl, VT, ResNode);
3697  }
3698  return SDValue();
3699}
3700
3701SDValue
3702X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) {
3703  DebugLoc dl = Op.getDebugLoc();
3704  // All zero's are handled with pxor, all one's are handled with pcmpeqd.
3705  if (ISD::isBuildVectorAllZeros(Op.getNode())
3706      || ISD::isBuildVectorAllOnes(Op.getNode())) {
3707    // Canonicalize this to either <4 x i32> or <2 x i32> (SSE vs MMX) to
3708    // 1) ensure the zero vectors are CSE'd, and 2) ensure that i64 scalars are
3709    // eliminated on x86-32 hosts.
3710    if (Op.getValueType() == MVT::v4i32 || Op.getValueType() == MVT::v2i32)
3711      return Op;
3712
3713    if (ISD::isBuildVectorAllOnes(Op.getNode()))
3714      return getOnesVector(Op.getValueType(), DAG, dl);
3715    return getZeroVector(Op.getValueType(), Subtarget->hasSSE2(), DAG, dl);
3716  }
3717
3718  EVT VT = Op.getValueType();
3719  EVT ExtVT = VT.getVectorElementType();
3720  unsigned EVTBits = ExtVT.getSizeInBits();
3721
3722  unsigned NumElems = Op.getNumOperands();
3723  unsigned NumZero  = 0;
3724  unsigned NumNonZero = 0;
3725  unsigned NonZeros = 0;
3726  bool IsAllConstants = true;
3727  SmallSet<SDValue, 8> Values;
3728  for (unsigned i = 0; i < NumElems; ++i) {
3729    SDValue Elt = Op.getOperand(i);
3730    if (Elt.getOpcode() == ISD::UNDEF)
3731      continue;
3732    Values.insert(Elt);
3733    if (Elt.getOpcode() != ISD::Constant &&
3734        Elt.getOpcode() != ISD::ConstantFP)
3735      IsAllConstants = false;
3736    if (X86::isZeroNode(Elt))
3737      NumZero++;
3738    else {
3739      NonZeros |= (1 << i);
3740      NumNonZero++;
3741    }
3742  }
3743
3744  if (NumNonZero == 0) {
3745    // All undef vector. Return an UNDEF.  All zero vectors were handled above.
3746    return DAG.getUNDEF(VT);
3747  }
3748
3749  // Special case for single non-zero, non-undef, element.
3750  if (NumNonZero == 1) {
3751    unsigned Idx = CountTrailingZeros_32(NonZeros);
3752    SDValue Item = Op.getOperand(Idx);
3753
3754    // If this is an insertion of an i64 value on x86-32, and if the top bits of
3755    // the value are obviously zero, truncate the value to i32 and do the
3756    // insertion that way.  Only do this if the value is non-constant or if the
3757    // value is a constant being inserted into element 0.  It is cheaper to do
3758    // a constant pool load than it is to do a movd + shuffle.
3759    if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
3760        (!IsAllConstants || Idx == 0)) {
3761      if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
3762        // Handle MMX and SSE both.
3763        EVT VecVT = VT == MVT::v2i64 ? MVT::v4i32 : MVT::v2i32;
3764        unsigned VecElts = VT == MVT::v2i64 ? 4 : 2;
3765
3766        // Truncate the value (which may itself be a constant) to i32, and
3767        // convert it to a vector with movd (S2V+shuffle to zero extend).
3768        Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
3769        Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
3770        Item = getShuffleVectorZeroOrUndef(Item, 0, true,
3771                                           Subtarget->hasSSE2(), DAG);
3772
3773        // Now we have our 32-bit value zero extended in the low element of
3774        // a vector.  If Idx != 0, swizzle it into place.
3775        if (Idx != 0) {
3776          SmallVector<int, 4> Mask;
3777          Mask.push_back(Idx);
3778          for (unsigned i = 1; i != VecElts; ++i)
3779            Mask.push_back(i);
3780          Item = DAG.getVectorShuffle(VecVT, dl, Item,
3781                                      DAG.getUNDEF(Item.getValueType()),
3782                                      &Mask[0]);
3783        }
3784        return DAG.getNode(ISD::BIT_CONVERT, dl, Op.getValueType(), Item);
3785      }
3786    }
3787
3788    // If we have a constant or non-constant insertion into the low element of
3789    // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
3790    // the rest of the elements.  This will be matched as movd/movq/movss/movsd
3791    // depending on what the source datatype is.
3792    if (Idx == 0) {
3793      if (NumZero == 0) {
3794        return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
3795      } else if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
3796          (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
3797        Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
3798        // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
3799        return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget->hasSSE2(),
3800                                           DAG);
3801      } else if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
3802        Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
3803        EVT MiddleVT = VT.getSizeInBits() == 64 ? MVT::v2i32 : MVT::v4i32;
3804        Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MiddleVT, Item);
3805        Item = getShuffleVectorZeroOrUndef(Item, 0, true,
3806                                           Subtarget->hasSSE2(), DAG);
3807        return DAG.getNode(ISD::BIT_CONVERT, dl, VT, Item);
3808      }
3809    }
3810
3811    // Is it a vector logical left shift?
3812    if (NumElems == 2 && Idx == 1 &&
3813        X86::isZeroNode(Op.getOperand(0)) &&
3814        !X86::isZeroNode(Op.getOperand(1))) {
3815      unsigned NumBits = VT.getSizeInBits();
3816      return getVShift(true, VT,
3817                       DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
3818                                   VT, Op.getOperand(1)),
3819                       NumBits/2, DAG, *this, dl);
3820    }
3821
3822    if (IsAllConstants) // Otherwise, it's better to do a constpool load.
3823      return SDValue();
3824
3825    // Otherwise, if this is a vector with i32 or f32 elements, and the element
3826    // is a non-constant being inserted into an element other than the low one,
3827    // we can't use a constant pool load.  Instead, use SCALAR_TO_VECTOR (aka
3828    // movd/movss) to move this into the low element, then shuffle it into
3829    // place.
3830    if (EVTBits == 32) {
3831      Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
3832
3833      // Turn it into a shuffle of zero and zero-extended scalar to vector.
3834      Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0,
3835                                         Subtarget->hasSSE2(), DAG);
3836      SmallVector<int, 8> MaskVec;
3837      for (unsigned i = 0; i < NumElems; i++)
3838        MaskVec.push_back(i == Idx ? 0 : 1);
3839      return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
3840    }
3841  }
3842
3843  // Splat is obviously ok. Let legalizer expand it to a shuffle.
3844  if (Values.size() == 1) {
3845    if (EVTBits == 32) {
3846      // Instead of a shuffle like this:
3847      // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
3848      // Check if it's possible to issue this instead.
3849      // shuffle (vload ptr)), undef, <1, 1, 1, 1>
3850      unsigned Idx = CountTrailingZeros_32(NonZeros);
3851      SDValue Item = Op.getOperand(Idx);
3852      if (Op.getNode()->isOnlyUserOf(Item.getNode()))
3853        return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
3854    }
3855    return SDValue();
3856  }
3857
3858  // A vector full of immediates; various special cases are already
3859  // handled, so this is best done with a single constant-pool load.
3860  if (IsAllConstants)
3861    return SDValue();
3862
3863  // Let legalizer expand 2-wide build_vectors.
3864  if (EVTBits == 64) {
3865    if (NumNonZero == 1) {
3866      // One half is zero or undef.
3867      unsigned Idx = CountTrailingZeros_32(NonZeros);
3868      SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
3869                                 Op.getOperand(Idx));
3870      return getShuffleVectorZeroOrUndef(V2, Idx, true,
3871                                         Subtarget->hasSSE2(), DAG);
3872    }
3873    return SDValue();
3874  }
3875
3876  // If element VT is < 32 bits, convert it to inserts into a zero vector.
3877  if (EVTBits == 8 && NumElems == 16) {
3878    SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
3879                                        *this);
3880    if (V.getNode()) return V;
3881  }
3882
3883  if (EVTBits == 16 && NumElems == 8) {
3884    SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
3885                                        *this);
3886    if (V.getNode()) return V;
3887  }
3888
3889  // If element VT is == 32 bits, turn it into a number of shuffles.
3890  SmallVector<SDValue, 8> V;
3891  V.resize(NumElems);
3892  if (NumElems == 4 && NumZero > 0) {
3893    for (unsigned i = 0; i < 4; ++i) {
3894      bool isZero = !(NonZeros & (1 << i));
3895      if (isZero)
3896        V[i] = getZeroVector(VT, Subtarget->hasSSE2(), DAG, dl);
3897      else
3898        V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
3899    }
3900
3901    for (unsigned i = 0; i < 2; ++i) {
3902      switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
3903        default: break;
3904        case 0:
3905          V[i] = V[i*2];  // Must be a zero vector.
3906          break;
3907        case 1:
3908          V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
3909          break;
3910        case 2:
3911          V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
3912          break;
3913        case 3:
3914          V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
3915          break;
3916      }
3917    }
3918
3919    SmallVector<int, 8> MaskVec;
3920    bool Reverse = (NonZeros & 0x3) == 2;
3921    for (unsigned i = 0; i < 2; ++i)
3922      MaskVec.push_back(Reverse ? 1-i : i);
3923    Reverse = ((NonZeros & (0x3 << 2)) >> 2) == 2;
3924    for (unsigned i = 0; i < 2; ++i)
3925      MaskVec.push_back(Reverse ? 1-i+NumElems : i+NumElems);
3926    return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
3927  }
3928
3929  if (Values.size() > 1 && VT.getSizeInBits() == 128) {
3930    // Check for a build vector of consecutive loads.
3931    for (unsigned i = 0; i < NumElems; ++i)
3932      V[i] = Op.getOperand(i);
3933
3934    // Check for elements which are consecutive loads.
3935    SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG);
3936    if (LD.getNode())
3937      return LD;
3938
3939    // For SSE 4.1, use inserts into undef.
3940    if (getSubtarget()->hasSSE41()) {
3941      V[0] = DAG.getUNDEF(VT);
3942      for (unsigned i = 0; i < NumElems; ++i)
3943        if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
3944          V[0] = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, V[0],
3945                             Op.getOperand(i), DAG.getIntPtrConstant(i));
3946      return V[0];
3947    }
3948
3949    // Otherwise, expand into a number of unpckl*
3950    // e.g. for v4f32
3951    //   Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
3952    //         : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
3953    //   Step 2: unpcklps X, Y ==>    <3, 2, 1, 0>
3954    for (unsigned i = 0; i < NumElems; ++i)
3955      V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
3956    NumElems >>= 1;
3957    while (NumElems != 0) {
3958      for (unsigned i = 0; i < NumElems; ++i)
3959        V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + NumElems]);
3960      NumElems >>= 1;
3961    }
3962    return V[0];
3963  }
3964  return SDValue();
3965}
3966
3967SDValue
3968X86TargetLowering::LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
3969  // We support concatenate two MMX registers and place them in a MMX
3970  // register.  This is better than doing a stack convert.
3971  DebugLoc dl = Op.getDebugLoc();
3972  EVT ResVT = Op.getValueType();
3973  assert(Op.getNumOperands() == 2);
3974  assert(ResVT == MVT::v2i64 || ResVT == MVT::v4i32 ||
3975         ResVT == MVT::v8i16 || ResVT == MVT::v16i8);
3976  int Mask[2];
3977  SDValue InVec = DAG.getNode(ISD::BIT_CONVERT,dl, MVT::v1i64, Op.getOperand(0));
3978  SDValue VecOp = DAG.getNode(X86ISD::MOVQ2DQ, dl, MVT::v2i64, InVec);
3979  InVec = Op.getOperand(1);
3980  if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
3981    unsigned NumElts = ResVT.getVectorNumElements();
3982    VecOp = DAG.getNode(ISD::BIT_CONVERT, dl, ResVT, VecOp);
3983    VecOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ResVT, VecOp,
3984                       InVec.getOperand(0), DAG.getIntPtrConstant(NumElts/2+1));
3985  } else {
3986    InVec = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v1i64, InVec);
3987    SDValue VecOp2 = DAG.getNode(X86ISD::MOVQ2DQ, dl, MVT::v2i64, InVec);
3988    Mask[0] = 0; Mask[1] = 2;
3989    VecOp = DAG.getVectorShuffle(MVT::v2i64, dl, VecOp, VecOp2, Mask);
3990  }
3991  return DAG.getNode(ISD::BIT_CONVERT, dl, ResVT, VecOp);
3992}
3993
3994// v8i16 shuffles - Prefer shuffles in the following order:
3995// 1. [all]   pshuflw, pshufhw, optional move
3996// 2. [ssse3] 1 x pshufb
3997// 3. [ssse3] 2 x pshufb + 1 x por
3998// 4. [all]   mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
3999static
4000SDValue LowerVECTOR_SHUFFLEv8i16(ShuffleVectorSDNode *SVOp,
4001                                 SelectionDAG &DAG, X86TargetLowering &TLI) {
4002  SDValue V1 = SVOp->getOperand(0);
4003  SDValue V2 = SVOp->getOperand(1);
4004  DebugLoc dl = SVOp->getDebugLoc();
4005  SmallVector<int, 8> MaskVals;
4006
4007  // Determine if more than 1 of the words in each of the low and high quadwords
4008  // of the result come from the same quadword of one of the two inputs.  Undef
4009  // mask values count as coming from any quadword, for better codegen.
4010  SmallVector<unsigned, 4> LoQuad(4);
4011  SmallVector<unsigned, 4> HiQuad(4);
4012  BitVector InputQuads(4);
4013  for (unsigned i = 0; i < 8; ++i) {
4014    SmallVectorImpl<unsigned> &Quad = i < 4 ? LoQuad : HiQuad;
4015    int EltIdx = SVOp->getMaskElt(i);
4016    MaskVals.push_back(EltIdx);
4017    if (EltIdx < 0) {
4018      ++Quad[0];
4019      ++Quad[1];
4020      ++Quad[2];
4021      ++Quad[3];
4022      continue;
4023    }
4024    ++Quad[EltIdx / 4];
4025    InputQuads.set(EltIdx / 4);
4026  }
4027
4028  int BestLoQuad = -1;
4029  unsigned MaxQuad = 1;
4030  for (unsigned i = 0; i < 4; ++i) {
4031    if (LoQuad[i] > MaxQuad) {
4032      BestLoQuad = i;
4033      MaxQuad = LoQuad[i];
4034    }
4035  }
4036
4037  int BestHiQuad = -1;
4038  MaxQuad = 1;
4039  for (unsigned i = 0; i < 4; ++i) {
4040    if (HiQuad[i] > MaxQuad) {
4041      BestHiQuad = i;
4042      MaxQuad = HiQuad[i];
4043    }
4044  }
4045
4046  // For SSSE3, If all 8 words of the result come from only 1 quadword of each
4047  // of the two input vectors, shuffle them into one input vector so only a
4048  // single pshufb instruction is necessary. If There are more than 2 input
4049  // quads, disable the next transformation since it does not help SSSE3.
4050  bool V1Used = InputQuads[0] || InputQuads[1];
4051  bool V2Used = InputQuads[2] || InputQuads[3];
4052  if (TLI.getSubtarget()->hasSSSE3()) {
4053    if (InputQuads.count() == 2 && V1Used && V2Used) {
4054      BestLoQuad = InputQuads.find_first();
4055      BestHiQuad = InputQuads.find_next(BestLoQuad);
4056    }
4057    if (InputQuads.count() > 2) {
4058      BestLoQuad = -1;
4059      BestHiQuad = -1;
4060    }
4061  }
4062
4063  // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
4064  // the shuffle mask.  If a quad is scored as -1, that means that it contains
4065  // words from all 4 input quadwords.
4066  SDValue NewV;
4067  if (BestLoQuad >= 0 || BestHiQuad >= 0) {
4068    SmallVector<int, 8> MaskV;
4069    MaskV.push_back(BestLoQuad < 0 ? 0 : BestLoQuad);
4070    MaskV.push_back(BestHiQuad < 0 ? 1 : BestHiQuad);
4071    NewV = DAG.getVectorShuffle(MVT::v2i64, dl,
4072                  DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64, V1),
4073                  DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64, V2), &MaskV[0]);
4074    NewV = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v8i16, NewV);
4075
4076    // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
4077    // source words for the shuffle, to aid later transformations.
4078    bool AllWordsInNewV = true;
4079    bool InOrder[2] = { true, true };
4080    for (unsigned i = 0; i != 8; ++i) {
4081      int idx = MaskVals[i];
4082      if (idx != (int)i)
4083        InOrder[i/4] = false;
4084      if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
4085        continue;
4086      AllWordsInNewV = false;
4087      break;
4088    }
4089
4090    bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
4091    if (AllWordsInNewV) {
4092      for (int i = 0; i != 8; ++i) {
4093        int idx = MaskVals[i];
4094        if (idx < 0)
4095          continue;
4096        idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
4097        if ((idx != i) && idx < 4)
4098          pshufhw = false;
4099        if ((idx != i) && idx > 3)
4100          pshuflw = false;
4101      }
4102      V1 = NewV;
4103      V2Used = false;
4104      BestLoQuad = 0;
4105      BestHiQuad = 1;
4106    }
4107
4108    // If we've eliminated the use of V2, and the new mask is a pshuflw or
4109    // pshufhw, that's as cheap as it gets.  Return the new shuffle.
4110    if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
4111      return DAG.getVectorShuffle(MVT::v8i16, dl, NewV,
4112                                  DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
4113    }
4114  }
4115
4116  // If we have SSSE3, and all words of the result are from 1 input vector,
4117  // case 2 is generated, otherwise case 3 is generated.  If no SSSE3
4118  // is present, fall back to case 4.
4119  if (TLI.getSubtarget()->hasSSSE3()) {
4120    SmallVector<SDValue,16> pshufbMask;
4121
4122    // If we have elements from both input vectors, set the high bit of the
4123    // shuffle mask element to zero out elements that come from V2 in the V1
4124    // mask, and elements that come from V1 in the V2 mask, so that the two
4125    // results can be OR'd together.
4126    bool TwoInputs = V1Used && V2Used;
4127    for (unsigned i = 0; i != 8; ++i) {
4128      int EltIdx = MaskVals[i] * 2;
4129      if (TwoInputs && (EltIdx >= 16)) {
4130        pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4131        pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4132        continue;
4133      }
4134      pshufbMask.push_back(DAG.getConstant(EltIdx,   MVT::i8));
4135      pshufbMask.push_back(DAG.getConstant(EltIdx+1, MVT::i8));
4136    }
4137    V1 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v16i8, V1);
4138    V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
4139                     DAG.getNode(ISD::BUILD_VECTOR, dl,
4140                                 MVT::v16i8, &pshufbMask[0], 16));
4141    if (!TwoInputs)
4142      return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v8i16, V1);
4143
4144    // Calculate the shuffle mask for the second input, shuffle it, and
4145    // OR it with the first shuffled input.
4146    pshufbMask.clear();
4147    for (unsigned i = 0; i != 8; ++i) {
4148      int EltIdx = MaskVals[i] * 2;
4149      if (EltIdx < 16) {
4150        pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4151        pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4152        continue;
4153      }
4154      pshufbMask.push_back(DAG.getConstant(EltIdx - 16, MVT::i8));
4155      pshufbMask.push_back(DAG.getConstant(EltIdx - 15, MVT::i8));
4156    }
4157    V2 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v16i8, V2);
4158    V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
4159                     DAG.getNode(ISD::BUILD_VECTOR, dl,
4160                                 MVT::v16i8, &pshufbMask[0], 16));
4161    V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
4162    return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v8i16, V1);
4163  }
4164
4165  // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
4166  // and update MaskVals with new element order.
4167  BitVector InOrder(8);
4168  if (BestLoQuad >= 0) {
4169    SmallVector<int, 8> MaskV;
4170    for (int i = 0; i != 4; ++i) {
4171      int idx = MaskVals[i];
4172      if (idx < 0) {
4173        MaskV.push_back(-1);
4174        InOrder.set(i);
4175      } else if ((idx / 4) == BestLoQuad) {
4176        MaskV.push_back(idx & 3);
4177        InOrder.set(i);
4178      } else {
4179        MaskV.push_back(-1);
4180      }
4181    }
4182    for (unsigned i = 4; i != 8; ++i)
4183      MaskV.push_back(i);
4184    NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
4185                                &MaskV[0]);
4186  }
4187
4188  // If BestHi >= 0, generate a pshufhw to put the high elements in order,
4189  // and update MaskVals with the new element order.
4190  if (BestHiQuad >= 0) {
4191    SmallVector<int, 8> MaskV;
4192    for (unsigned i = 0; i != 4; ++i)
4193      MaskV.push_back(i);
4194    for (unsigned i = 4; i != 8; ++i) {
4195      int idx = MaskVals[i];
4196      if (idx < 0) {
4197        MaskV.push_back(-1);
4198        InOrder.set(i);
4199      } else if ((idx / 4) == BestHiQuad) {
4200        MaskV.push_back((idx & 3) + 4);
4201        InOrder.set(i);
4202      } else {
4203        MaskV.push_back(-1);
4204      }
4205    }
4206    NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
4207                                &MaskV[0]);
4208  }
4209
4210  // In case BestHi & BestLo were both -1, which means each quadword has a word
4211  // from each of the four input quadwords, calculate the InOrder bitvector now
4212  // before falling through to the insert/extract cleanup.
4213  if (BestLoQuad == -1 && BestHiQuad == -1) {
4214    NewV = V1;
4215    for (int i = 0; i != 8; ++i)
4216      if (MaskVals[i] < 0 || MaskVals[i] == i)
4217        InOrder.set(i);
4218  }
4219
4220  // The other elements are put in the right place using pextrw and pinsrw.
4221  for (unsigned i = 0; i != 8; ++i) {
4222    if (InOrder[i])
4223      continue;
4224    int EltIdx = MaskVals[i];
4225    if (EltIdx < 0)
4226      continue;
4227    SDValue ExtOp = (EltIdx < 8)
4228    ? DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
4229                  DAG.getIntPtrConstant(EltIdx))
4230    : DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
4231                  DAG.getIntPtrConstant(EltIdx - 8));
4232    NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
4233                       DAG.getIntPtrConstant(i));
4234  }
4235  return NewV;
4236}
4237
4238// v16i8 shuffles - Prefer shuffles in the following order:
4239// 1. [ssse3] 1 x pshufb
4240// 2. [ssse3] 2 x pshufb + 1 x por
4241// 3. [all]   v8i16 shuffle + N x pextrw + rotate + pinsrw
4242static
4243SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
4244                                 SelectionDAG &DAG, X86TargetLowering &TLI) {
4245  SDValue V1 = SVOp->getOperand(0);
4246  SDValue V2 = SVOp->getOperand(1);
4247  DebugLoc dl = SVOp->getDebugLoc();
4248  SmallVector<int, 16> MaskVals;
4249  SVOp->getMask(MaskVals);
4250
4251  // If we have SSSE3, case 1 is generated when all result bytes come from
4252  // one of  the inputs.  Otherwise, case 2 is generated.  If no SSSE3 is
4253  // present, fall back to case 3.
4254  // FIXME: kill V2Only once shuffles are canonizalized by getNode.
4255  bool V1Only = true;
4256  bool V2Only = true;
4257  for (unsigned i = 0; i < 16; ++i) {
4258    int EltIdx = MaskVals[i];
4259    if (EltIdx < 0)
4260      continue;
4261    if (EltIdx < 16)
4262      V2Only = false;
4263    else
4264      V1Only = false;
4265  }
4266
4267  // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
4268  if (TLI.getSubtarget()->hasSSSE3()) {
4269    SmallVector<SDValue,16> pshufbMask;
4270
4271    // If all result elements are from one input vector, then only translate
4272    // undef mask values to 0x80 (zero out result) in the pshufb mask.
4273    //
4274    // Otherwise, we have elements from both input vectors, and must zero out
4275    // elements that come from V2 in the first mask, and V1 in the second mask
4276    // so that we can OR them together.
4277    bool TwoInputs = !(V1Only || V2Only);
4278    for (unsigned i = 0; i != 16; ++i) {
4279      int EltIdx = MaskVals[i];
4280      if (EltIdx < 0 || (TwoInputs && EltIdx >= 16)) {
4281        pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4282        continue;
4283      }
4284      pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
4285    }
4286    // If all the elements are from V2, assign it to V1 and return after
4287    // building the first pshufb.
4288    if (V2Only)
4289      V1 = V2;
4290    V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
4291                     DAG.getNode(ISD::BUILD_VECTOR, dl,
4292                                 MVT::v16i8, &pshufbMask[0], 16));
4293    if (!TwoInputs)
4294      return V1;
4295
4296    // Calculate the shuffle mask for the second input, shuffle it, and
4297    // OR it with the first shuffled input.
4298    pshufbMask.clear();
4299    for (unsigned i = 0; i != 16; ++i) {
4300      int EltIdx = MaskVals[i];
4301      if (EltIdx < 16) {
4302        pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4303        continue;
4304      }
4305      pshufbMask.push_back(DAG.getConstant(EltIdx - 16, MVT::i8));
4306    }
4307    V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
4308                     DAG.getNode(ISD::BUILD_VECTOR, dl,
4309                                 MVT::v16i8, &pshufbMask[0], 16));
4310    return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
4311  }
4312
4313  // No SSSE3 - Calculate in place words and then fix all out of place words
4314  // With 0-16 extracts & inserts.  Worst case is 16 bytes out of order from
4315  // the 16 different words that comprise the two doublequadword input vectors.
4316  V1 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v8i16, V1);
4317  V2 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v8i16, V2);
4318  SDValue NewV = V2Only ? V2 : V1;
4319  for (int i = 0; i != 8; ++i) {
4320    int Elt0 = MaskVals[i*2];
4321    int Elt1 = MaskVals[i*2+1];
4322
4323    // This word of the result is all undef, skip it.
4324    if (Elt0 < 0 && Elt1 < 0)
4325      continue;
4326
4327    // This word of the result is already in the correct place, skip it.
4328    if (V1Only && (Elt0 == i*2) && (Elt1 == i*2+1))
4329      continue;
4330    if (V2Only && (Elt0 == i*2+16) && (Elt1 == i*2+17))
4331      continue;
4332
4333    SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
4334    SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
4335    SDValue InsElt;
4336
4337    // If Elt0 and Elt1 are defined, are consecutive, and can be load
4338    // using a single extract together, load it and store it.
4339    if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
4340      InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
4341                           DAG.getIntPtrConstant(Elt1 / 2));
4342      NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
4343                        DAG.getIntPtrConstant(i));
4344      continue;
4345    }
4346
4347    // If Elt1 is defined, extract it from the appropriate source.  If the
4348    // source byte is not also odd, shift the extracted word left 8 bits
4349    // otherwise clear the bottom 8 bits if we need to do an or.
4350    if (Elt1 >= 0) {
4351      InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
4352                           DAG.getIntPtrConstant(Elt1 / 2));
4353      if ((Elt1 & 1) == 0)
4354        InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
4355                             DAG.getConstant(8, TLI.getShiftAmountTy()));
4356      else if (Elt0 >= 0)
4357        InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
4358                             DAG.getConstant(0xFF00, MVT::i16));
4359    }
4360    // If Elt0 is defined, extract it from the appropriate source.  If the
4361    // source byte is not also even, shift the extracted word right 8 bits. If
4362    // Elt1 was also defined, OR the extracted values together before
4363    // inserting them in the result.
4364    if (Elt0 >= 0) {
4365      SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
4366                                    Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
4367      if ((Elt0 & 1) != 0)
4368        InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
4369                              DAG.getConstant(8, TLI.getShiftAmountTy()));
4370      else if (Elt1 >= 0)
4371        InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
4372                             DAG.getConstant(0x00FF, MVT::i16));
4373      InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
4374                         : InsElt0;
4375    }
4376    NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
4377                       DAG.getIntPtrConstant(i));
4378  }
4379  return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v16i8, NewV);
4380}
4381
4382/// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
4383/// ones, or rewriting v4i32 / v2f32 as 2 wide ones if possible. This can be
4384/// done when every pair / quad of shuffle mask elements point to elements in
4385/// the right sequence. e.g.
4386/// vector_shuffle <>, <>, < 3, 4, | 10, 11, | 0, 1, | 14, 15>
4387static
4388SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
4389                                 SelectionDAG &DAG,
4390                                 TargetLowering &TLI, DebugLoc dl) {
4391  EVT VT = SVOp->getValueType(0);
4392  SDValue V1 = SVOp->getOperand(0);
4393  SDValue V2 = SVOp->getOperand(1);
4394  unsigned NumElems = VT.getVectorNumElements();
4395  unsigned NewWidth = (NumElems == 4) ? 2 : 4;
4396  EVT MaskVT = MVT::getIntVectorWithNumElements(NewWidth);
4397  EVT MaskEltVT = MaskVT.getVectorElementType();
4398  EVT NewVT = MaskVT;
4399  switch (VT.getSimpleVT().SimpleTy) {
4400  default: assert(false && "Unexpected!");
4401  case MVT::v4f32: NewVT = MVT::v2f64; break;
4402  case MVT::v4i32: NewVT = MVT::v2i64; break;
4403  case MVT::v8i16: NewVT = MVT::v4i32; break;
4404  case MVT::v16i8: NewVT = MVT::v4i32; break;
4405  }
4406
4407  if (NewWidth == 2) {
4408    if (VT.isInteger())
4409      NewVT = MVT::v2i64;
4410    else
4411      NewVT = MVT::v2f64;
4412  }
4413  int Scale = NumElems / NewWidth;
4414  SmallVector<int, 8> MaskVec;
4415  for (unsigned i = 0; i < NumElems; i += Scale) {
4416    int StartIdx = -1;
4417    for (int j = 0; j < Scale; ++j) {
4418      int EltIdx = SVOp->getMaskElt(i+j);
4419      if (EltIdx < 0)
4420        continue;
4421      if (StartIdx == -1)
4422        StartIdx = EltIdx - (EltIdx % Scale);
4423      if (EltIdx != StartIdx + j)
4424        return SDValue();
4425    }
4426    if (StartIdx == -1)
4427      MaskVec.push_back(-1);
4428    else
4429      MaskVec.push_back(StartIdx / Scale);
4430  }
4431
4432  V1 = DAG.getNode(ISD::BIT_CONVERT, dl, NewVT, V1);
4433  V2 = DAG.getNode(ISD::BIT_CONVERT, dl, NewVT, V2);
4434  return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
4435}
4436
4437/// getVZextMovL - Return a zero-extending vector move low node.
4438///
4439static SDValue getVZextMovL(EVT VT, EVT OpVT,
4440                            SDValue SrcOp, SelectionDAG &DAG,
4441                            const X86Subtarget *Subtarget, DebugLoc dl) {
4442  if (VT == MVT::v2f64 || VT == MVT::v4f32) {
4443    LoadSDNode *LD = NULL;
4444    if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
4445      LD = dyn_cast<LoadSDNode>(SrcOp);
4446    if (!LD) {
4447      // movssrr and movsdrr do not clear top bits. Try to use movd, movq
4448      // instead.
4449      MVT ExtVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
4450      if ((ExtVT.SimpleTy != MVT::i64 || Subtarget->is64Bit()) &&
4451          SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
4452          SrcOp.getOperand(0).getOpcode() == ISD::BIT_CONVERT &&
4453          SrcOp.getOperand(0).getOperand(0).getValueType() == ExtVT) {
4454        // PR2108
4455        OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
4456        return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
4457                           DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
4458                                       DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
4459                                                   OpVT,
4460                                                   SrcOp.getOperand(0)
4461                                                          .getOperand(0))));
4462      }
4463    }
4464  }
4465
4466  return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
4467                     DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
4468                                 DAG.getNode(ISD::BIT_CONVERT, dl,
4469                                             OpVT, SrcOp)));
4470}
4471
4472/// LowerVECTOR_SHUFFLE_4wide - Handle all 4 wide cases with a number of
4473/// shuffles.
4474static SDValue
4475LowerVECTOR_SHUFFLE_4wide(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
4476  SDValue V1 = SVOp->getOperand(0);
4477  SDValue V2 = SVOp->getOperand(1);
4478  DebugLoc dl = SVOp->getDebugLoc();
4479  EVT VT = SVOp->getValueType(0);
4480
4481  SmallVector<std::pair<int, int>, 8> Locs;
4482  Locs.resize(4);
4483  SmallVector<int, 8> Mask1(4U, -1);
4484  SmallVector<int, 8> PermMask;
4485  SVOp->getMask(PermMask);
4486
4487  unsigned NumHi = 0;
4488  unsigned NumLo = 0;
4489  for (unsigned i = 0; i != 4; ++i) {
4490    int Idx = PermMask[i];
4491    if (Idx < 0) {
4492      Locs[i] = std::make_pair(-1, -1);
4493    } else {
4494      assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
4495      if (Idx < 4) {
4496        Locs[i] = std::make_pair(0, NumLo);
4497        Mask1[NumLo] = Idx;
4498        NumLo++;
4499      } else {
4500        Locs[i] = std::make_pair(1, NumHi);
4501        if (2+NumHi < 4)
4502          Mask1[2+NumHi] = Idx;
4503        NumHi++;
4504      }
4505    }
4506  }
4507
4508  if (NumLo <= 2 && NumHi <= 2) {
4509    // If no more than two elements come from either vector. This can be
4510    // implemented with two shuffles. First shuffle gather the elements.
4511    // The second shuffle, which takes the first shuffle as both of its
4512    // vector operands, put the elements into the right order.
4513    V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
4514
4515    SmallVector<int, 8> Mask2(4U, -1);
4516
4517    for (unsigned i = 0; i != 4; ++i) {
4518      if (Locs[i].first == -1)
4519        continue;
4520      else {
4521        unsigned Idx = (i < 2) ? 0 : 4;
4522        Idx += Locs[i].first * 2 + Locs[i].second;
4523        Mask2[i] = Idx;
4524      }
4525    }
4526
4527    return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
4528  } else if (NumLo == 3 || NumHi == 3) {
4529    // Otherwise, we must have three elements from one vector, call it X, and
4530    // one element from the other, call it Y.  First, use a shufps to build an
4531    // intermediate vector with the one element from Y and the element from X
4532    // that will be in the same half in the final destination (the indexes don't
4533    // matter). Then, use a shufps to build the final vector, taking the half
4534    // containing the element from Y from the intermediate, and the other half
4535    // from X.
4536    if (NumHi == 3) {
4537      // Normalize it so the 3 elements come from V1.
4538      CommuteVectorShuffleMask(PermMask, VT);
4539      std::swap(V1, V2);
4540    }
4541
4542    // Find the element from V2.
4543    unsigned HiIndex;
4544    for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
4545      int Val = PermMask[HiIndex];
4546      if (Val < 0)
4547        continue;
4548      if (Val >= 4)
4549        break;
4550    }
4551
4552    Mask1[0] = PermMask[HiIndex];
4553    Mask1[1] = -1;
4554    Mask1[2] = PermMask[HiIndex^1];
4555    Mask1[3] = -1;
4556    V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
4557
4558    if (HiIndex >= 2) {
4559      Mask1[0] = PermMask[0];
4560      Mask1[1] = PermMask[1];
4561      Mask1[2] = HiIndex & 1 ? 6 : 4;
4562      Mask1[3] = HiIndex & 1 ? 4 : 6;
4563      return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
4564    } else {
4565      Mask1[0] = HiIndex & 1 ? 2 : 0;
4566      Mask1[1] = HiIndex & 1 ? 0 : 2;
4567      Mask1[2] = PermMask[2];
4568      Mask1[3] = PermMask[3];
4569      if (Mask1[2] >= 0)
4570        Mask1[2] += 4;
4571      if (Mask1[3] >= 0)
4572        Mask1[3] += 4;
4573      return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
4574    }
4575  }
4576
4577  // Break it into (shuffle shuffle_hi, shuffle_lo).
4578  Locs.clear();
4579  SmallVector<int,8> LoMask(4U, -1);
4580  SmallVector<int,8> HiMask(4U, -1);
4581
4582  SmallVector<int,8> *MaskPtr = &LoMask;
4583  unsigned MaskIdx = 0;
4584  unsigned LoIdx = 0;
4585  unsigned HiIdx = 2;
4586  for (unsigned i = 0; i != 4; ++i) {
4587    if (i == 2) {
4588      MaskPtr = &HiMask;
4589      MaskIdx = 1;
4590      LoIdx = 0;
4591      HiIdx = 2;
4592    }
4593    int Idx = PermMask[i];
4594    if (Idx < 0) {
4595      Locs[i] = std::make_pair(-1, -1);
4596    } else if (Idx < 4) {
4597      Locs[i] = std::make_pair(MaskIdx, LoIdx);
4598      (*MaskPtr)[LoIdx] = Idx;
4599      LoIdx++;
4600    } else {
4601      Locs[i] = std::make_pair(MaskIdx, HiIdx);
4602      (*MaskPtr)[HiIdx] = Idx;
4603      HiIdx++;
4604    }
4605  }
4606
4607  SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
4608  SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
4609  SmallVector<int, 8> MaskOps;
4610  for (unsigned i = 0; i != 4; ++i) {
4611    if (Locs[i].first == -1) {
4612      MaskOps.push_back(-1);
4613    } else {
4614      unsigned Idx = Locs[i].first * 4 + Locs[i].second;
4615      MaskOps.push_back(Idx);
4616    }
4617  }
4618  return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
4619}
4620
4621SDValue
4622X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) {
4623  ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
4624  SDValue V1 = Op.getOperand(0);
4625  SDValue V2 = Op.getOperand(1);
4626  EVT VT = Op.getValueType();
4627  DebugLoc dl = Op.getDebugLoc();
4628  unsigned NumElems = VT.getVectorNumElements();
4629  bool isMMX = VT.getSizeInBits() == 64;
4630  bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
4631  bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
4632  bool V1IsSplat = false;
4633  bool V2IsSplat = false;
4634
4635  if (isZeroShuffle(SVOp))
4636    return getZeroVector(VT, Subtarget->hasSSE2(), DAG, dl);
4637
4638  // Promote splats to v4f32.
4639  if (SVOp->isSplat()) {
4640    if (isMMX || NumElems < 4)
4641      return Op;
4642    return PromoteSplat(SVOp, DAG, Subtarget->hasSSE2());
4643  }
4644
4645  // If the shuffle can be profitably rewritten as a narrower shuffle, then
4646  // do it!
4647  if (VT == MVT::v8i16 || VT == MVT::v16i8) {
4648    SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, *this, dl);
4649    if (NewOp.getNode())
4650      return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
4651                         LowerVECTOR_SHUFFLE(NewOp, DAG));
4652  } else if ((VT == MVT::v4i32 || (VT == MVT::v4f32 && Subtarget->hasSSE2()))) {
4653    // FIXME: Figure out a cleaner way to do this.
4654    // Try to make use of movq to zero out the top part.
4655    if (ISD::isBuildVectorAllZeros(V2.getNode())) {
4656      SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, *this, dl);
4657      if (NewOp.getNode()) {
4658        if (isCommutedMOVL(cast<ShuffleVectorSDNode>(NewOp), true, false))
4659          return getVZextMovL(VT, NewOp.getValueType(), NewOp.getOperand(0),
4660                              DAG, Subtarget, dl);
4661      }
4662    } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
4663      SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, *this, dl);
4664      if (NewOp.getNode() && X86::isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)))
4665        return getVZextMovL(VT, NewOp.getValueType(), NewOp.getOperand(1),
4666                            DAG, Subtarget, dl);
4667    }
4668  }
4669
4670  if (X86::isPSHUFDMask(SVOp))
4671    return Op;
4672
4673  // Check if this can be converted into a logical shift.
4674  bool isLeft = false;
4675  unsigned ShAmt = 0;
4676  SDValue ShVal;
4677  bool isShift = getSubtarget()->hasSSE2() &&
4678    isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
4679  if (isShift && ShVal.hasOneUse()) {
4680    // If the shifted value has multiple uses, it may be cheaper to use
4681    // v_set0 + movlhps or movhlps, etc.
4682    EVT EltVT = VT.getVectorElementType();
4683    ShAmt *= EltVT.getSizeInBits();
4684    return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
4685  }
4686
4687  if (X86::isMOVLMask(SVOp)) {
4688    if (V1IsUndef)
4689      return V2;
4690    if (ISD::isBuildVectorAllZeros(V1.getNode()))
4691      return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
4692    if (!isMMX)
4693      return Op;
4694  }
4695
4696  // FIXME: fold these into legal mask.
4697  if (!isMMX && (X86::isMOVSHDUPMask(SVOp) ||
4698                 X86::isMOVSLDUPMask(SVOp) ||
4699                 X86::isMOVHLPSMask(SVOp) ||
4700                 X86::isMOVLHPSMask(SVOp) ||
4701                 X86::isMOVLPMask(SVOp)))
4702    return Op;
4703
4704  if (ShouldXformToMOVHLPS(SVOp) ||
4705      ShouldXformToMOVLP(V1.getNode(), V2.getNode(), SVOp))
4706    return CommuteVectorShuffle(SVOp, DAG);
4707
4708  if (isShift) {
4709    // No better options. Use a vshl / vsrl.
4710    EVT EltVT = VT.getVectorElementType();
4711    ShAmt *= EltVT.getSizeInBits();
4712    return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
4713  }
4714
4715  bool Commuted = false;
4716  // FIXME: This should also accept a bitcast of a splat?  Be careful, not
4717  // 1,1,1,1 -> v8i16 though.
4718  V1IsSplat = isSplatVector(V1.getNode());
4719  V2IsSplat = isSplatVector(V2.getNode());
4720
4721  // Canonicalize the splat or undef, if present, to be on the RHS.
4722  if ((V1IsSplat || V1IsUndef) && !(V2IsSplat || V2IsUndef)) {
4723    Op = CommuteVectorShuffle(SVOp, DAG);
4724    SVOp = cast<ShuffleVectorSDNode>(Op);
4725    V1 = SVOp->getOperand(0);
4726    V2 = SVOp->getOperand(1);
4727    std::swap(V1IsSplat, V2IsSplat);
4728    std::swap(V1IsUndef, V2IsUndef);
4729    Commuted = true;
4730  }
4731
4732  if (isCommutedMOVL(SVOp, V2IsSplat, V2IsUndef)) {
4733    // Shuffling low element of v1 into undef, just return v1.
4734    if (V2IsUndef)
4735      return V1;
4736    // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
4737    // the instruction selector will not match, so get a canonical MOVL with
4738    // swapped operands to undo the commute.
4739    return getMOVL(DAG, dl, VT, V2, V1);
4740  }
4741
4742  if (X86::isUNPCKL_v_undef_Mask(SVOp) ||
4743      X86::isUNPCKH_v_undef_Mask(SVOp) ||
4744      X86::isUNPCKLMask(SVOp) ||
4745      X86::isUNPCKHMask(SVOp))
4746    return Op;
4747
4748  if (V2IsSplat) {
4749    // Normalize mask so all entries that point to V2 points to its first
4750    // element then try to match unpck{h|l} again. If match, return a
4751    // new vector_shuffle with the corrected mask.
4752    SDValue NewMask = NormalizeMask(SVOp, DAG);
4753    ShuffleVectorSDNode *NSVOp = cast<ShuffleVectorSDNode>(NewMask);
4754    if (NSVOp != SVOp) {
4755      if (X86::isUNPCKLMask(NSVOp, true)) {
4756        return NewMask;
4757      } else if (X86::isUNPCKHMask(NSVOp, true)) {
4758        return NewMask;
4759      }
4760    }
4761  }
4762
4763  if (Commuted) {
4764    // Commute is back and try unpck* again.
4765    // FIXME: this seems wrong.
4766    SDValue NewOp = CommuteVectorShuffle(SVOp, DAG);
4767    ShuffleVectorSDNode *NewSVOp = cast<ShuffleVectorSDNode>(NewOp);
4768    if (X86::isUNPCKL_v_undef_Mask(NewSVOp) ||
4769        X86::isUNPCKH_v_undef_Mask(NewSVOp) ||
4770        X86::isUNPCKLMask(NewSVOp) ||
4771        X86::isUNPCKHMask(NewSVOp))
4772      return NewOp;
4773  }
4774
4775  // FIXME: for mmx, bitcast v2i32 to v4i16 for shuffle.
4776
4777  // Normalize the node to match x86 shuffle ops if needed
4778  if (!isMMX && V2.getOpcode() != ISD::UNDEF && isCommutedSHUFP(SVOp))
4779    return CommuteVectorShuffle(SVOp, DAG);
4780
4781  // Check for legal shuffle and return?
4782  SmallVector<int, 16> PermMask;
4783  SVOp->getMask(PermMask);
4784  if (isShuffleMaskLegal(PermMask, VT))
4785    return Op;
4786
4787  // Handle v8i16 specifically since SSE can do byte extraction and insertion.
4788  if (VT == MVT::v8i16) {
4789    SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(SVOp, DAG, *this);
4790    if (NewOp.getNode())
4791      return NewOp;
4792  }
4793
4794  if (VT == MVT::v16i8) {
4795    SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, DAG, *this);
4796    if (NewOp.getNode())
4797      return NewOp;
4798  }
4799
4800  // Handle all 4 wide cases with a number of shuffles except for MMX.
4801  if (NumElems == 4 && !isMMX)
4802    return LowerVECTOR_SHUFFLE_4wide(SVOp, DAG);
4803
4804  return SDValue();
4805}
4806
4807SDValue
4808X86TargetLowering::LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op,
4809                                                SelectionDAG &DAG) {
4810  EVT VT = Op.getValueType();
4811  DebugLoc dl = Op.getDebugLoc();
4812  if (VT.getSizeInBits() == 8) {
4813    SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
4814                                    Op.getOperand(0), Op.getOperand(1));
4815    SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
4816                                    DAG.getValueType(VT));
4817    return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
4818  } else if (VT.getSizeInBits() == 16) {
4819    unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
4820    // If Idx is 0, it's cheaper to do a move instead of a pextrw.
4821    if (Idx == 0)
4822      return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
4823                         DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
4824                                     DAG.getNode(ISD::BIT_CONVERT, dl,
4825                                                 MVT::v4i32,
4826                                                 Op.getOperand(0)),
4827                                     Op.getOperand(1)));
4828    SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
4829                                    Op.getOperand(0), Op.getOperand(1));
4830    SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
4831                                    DAG.getValueType(VT));
4832    return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
4833  } else if (VT == MVT::f32) {
4834    // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
4835    // the result back to FR32 register. It's only worth matching if the
4836    // result has a single use which is a store or a bitcast to i32.  And in
4837    // the case of a store, it's not worth it if the index is a constant 0,
4838    // because a MOVSSmr can be used instead, which is smaller and faster.
4839    if (!Op.hasOneUse())
4840      return SDValue();
4841    SDNode *User = *Op.getNode()->use_begin();
4842    if ((User->getOpcode() != ISD::STORE ||
4843         (isa<ConstantSDNode>(Op.getOperand(1)) &&
4844          cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
4845        (User->getOpcode() != ISD::BIT_CONVERT ||
4846         User->getValueType(0) != MVT::i32))
4847      return SDValue();
4848    SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
4849                                  DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v4i32,
4850                                              Op.getOperand(0)),
4851                                              Op.getOperand(1));
4852    return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::f32, Extract);
4853  } else if (VT == MVT::i32) {
4854    // ExtractPS works with constant index.
4855    if (isa<ConstantSDNode>(Op.getOperand(1)))
4856      return Op;
4857  }
4858  return SDValue();
4859}
4860
4861
4862SDValue
4863X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
4864  if (!isa<ConstantSDNode>(Op.getOperand(1)))
4865    return SDValue();
4866
4867  if (Subtarget->hasSSE41()) {
4868    SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
4869    if (Res.getNode())
4870      return Res;
4871  }
4872
4873  EVT VT = Op.getValueType();
4874  DebugLoc dl = Op.getDebugLoc();
4875  // TODO: handle v16i8.
4876  if (VT.getSizeInBits() == 16) {
4877    SDValue Vec = Op.getOperand(0);
4878    unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
4879    if (Idx == 0)
4880      return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
4881                         DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
4882                                     DAG.getNode(ISD::BIT_CONVERT, dl,
4883                                                 MVT::v4i32, Vec),
4884                                     Op.getOperand(1)));
4885    // Transform it so it match pextrw which produces a 32-bit result.
4886    EVT EltVT = MVT::i32;
4887    SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
4888                                    Op.getOperand(0), Op.getOperand(1));
4889    SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
4890                                    DAG.getValueType(VT));
4891    return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
4892  } else if (VT.getSizeInBits() == 32) {
4893    unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
4894    if (Idx == 0)
4895      return Op;
4896
4897    // SHUFPS the element to the lowest double word, then movss.
4898    int Mask[4] = { Idx, -1, -1, -1 };
4899    EVT VVT = Op.getOperand(0).getValueType();
4900    SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
4901                                       DAG.getUNDEF(VVT), Mask);
4902    return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
4903                       DAG.getIntPtrConstant(0));
4904  } else if (VT.getSizeInBits() == 64) {
4905    // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
4906    // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
4907    //        to match extract_elt for f64.
4908    unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
4909    if (Idx == 0)
4910      return Op;
4911
4912    // UNPCKHPD the element to the lowest double word, then movsd.
4913    // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
4914    // to a f64mem, the whole operation is folded into a single MOVHPDmr.
4915    int Mask[2] = { 1, -1 };
4916    EVT VVT = Op.getOperand(0).getValueType();
4917    SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
4918                                       DAG.getUNDEF(VVT), Mask);
4919    return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
4920                       DAG.getIntPtrConstant(0));
4921  }
4922
4923  return SDValue();
4924}
4925
4926SDValue
4927X86TargetLowering::LowerINSERT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG){
4928  EVT VT = Op.getValueType();
4929  EVT EltVT = VT.getVectorElementType();
4930  DebugLoc dl = Op.getDebugLoc();
4931
4932  SDValue N0 = Op.getOperand(0);
4933  SDValue N1 = Op.getOperand(1);
4934  SDValue N2 = Op.getOperand(2);
4935
4936  if ((EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) &&
4937      isa<ConstantSDNode>(N2)) {
4938    unsigned Opc;
4939    if (VT == MVT::v8i16)
4940      Opc = X86ISD::PINSRW;
4941    else if (VT == MVT::v4i16)
4942      Opc = X86ISD::MMX_PINSRW;
4943    else if (VT == MVT::v16i8)
4944      Opc = X86ISD::PINSRB;
4945    else
4946      Opc = X86ISD::PINSRB;
4947
4948    // Transform it so it match pinsr{b,w} which expects a GR32 as its second
4949    // argument.
4950    if (N1.getValueType() != MVT::i32)
4951      N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
4952    if (N2.getValueType() != MVT::i32)
4953      N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
4954    return DAG.getNode(Opc, dl, VT, N0, N1, N2);
4955  } else if (EltVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
4956    // Bits [7:6] of the constant are the source select.  This will always be
4957    //  zero here.  The DAG Combiner may combine an extract_elt index into these
4958    //  bits.  For example (insert (extract, 3), 2) could be matched by putting
4959    //  the '3' into bits [7:6] of X86ISD::INSERTPS.
4960    // Bits [5:4] of the constant are the destination select.  This is the
4961    //  value of the incoming immediate.
4962    // Bits [3:0] of the constant are the zero mask.  The DAG Combiner may
4963    //   combine either bitwise AND or insert of float 0.0 to set these bits.
4964    N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
4965    // Create this as a scalar to vector..
4966    N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
4967    return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
4968  } else if (EltVT == MVT::i32 && isa<ConstantSDNode>(N2)) {
4969    // PINSR* works with constant index.
4970    return Op;
4971  }
4972  return SDValue();
4973}
4974
4975SDValue
4976X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
4977  EVT VT = Op.getValueType();
4978  EVT EltVT = VT.getVectorElementType();
4979
4980  if (Subtarget->hasSSE41())
4981    return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
4982
4983  if (EltVT == MVT::i8)
4984    return SDValue();
4985
4986  DebugLoc dl = Op.getDebugLoc();
4987  SDValue N0 = Op.getOperand(0);
4988  SDValue N1 = Op.getOperand(1);
4989  SDValue N2 = Op.getOperand(2);
4990
4991  if (EltVT.getSizeInBits() == 16 && isa<ConstantSDNode>(N2)) {
4992    // Transform it so it match pinsrw which expects a 16-bit value in a GR32
4993    // as its second argument.
4994    if (N1.getValueType() != MVT::i32)
4995      N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
4996    if (N2.getValueType() != MVT::i32)
4997      N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
4998    return DAG.getNode(VT == MVT::v8i16 ? X86ISD::PINSRW : X86ISD::MMX_PINSRW,
4999                       dl, VT, N0, N1, N2);
5000  }
5001  return SDValue();
5002}
5003
5004SDValue
5005X86TargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
5006  DebugLoc dl = Op.getDebugLoc();
5007  if (Op.getValueType() == MVT::v2f32)
5008    return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2f32,
5009                       DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i32,
5010                                   DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32,
5011                                               Op.getOperand(0))));
5012
5013  if (Op.getValueType() == MVT::v1i64 && Op.getOperand(0).getValueType() == MVT::i64)
5014    return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
5015
5016  SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
5017  EVT VT = MVT::v2i32;
5018  switch (Op.getValueType().getSimpleVT().SimpleTy) {
5019  default: break;
5020  case MVT::v16i8:
5021  case MVT::v8i16:
5022    VT = MVT::v4i32;
5023    break;
5024  }
5025  return DAG.getNode(ISD::BIT_CONVERT, dl, Op.getValueType(),
5026                     DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, AnyExt));
5027}
5028
5029// ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
5030// their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
5031// one of the above mentioned nodes. It has to be wrapped because otherwise
5032// Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
5033// be used to form addressing mode. These wrapped nodes will be selected
5034// into MOV32ri.
5035SDValue
5036X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) {
5037  ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
5038
5039  // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
5040  // global base reg.
5041  unsigned char OpFlag = 0;
5042  unsigned WrapperKind = X86ISD::Wrapper;
5043  CodeModel::Model M = getTargetMachine().getCodeModel();
5044
5045  if (Subtarget->isPICStyleRIPRel() &&
5046      (M == CodeModel::Small || M == CodeModel::Kernel))
5047    WrapperKind = X86ISD::WrapperRIP;
5048  else if (Subtarget->isPICStyleGOT())
5049    OpFlag = X86II::MO_GOTOFF;
5050  else if (Subtarget->isPICStyleStubPIC())
5051    OpFlag = X86II::MO_PIC_BASE_OFFSET;
5052
5053  SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
5054                                             CP->getAlignment(),
5055                                             CP->getOffset(), OpFlag);
5056  DebugLoc DL = CP->getDebugLoc();
5057  Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
5058  // With PIC, the address is actually $g + Offset.
5059  if (OpFlag) {
5060    Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
5061                         DAG.getNode(X86ISD::GlobalBaseReg,
5062                                     DebugLoc(), getPointerTy()),
5063                         Result);
5064  }
5065
5066  return Result;
5067}
5068
5069SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) {
5070  JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
5071
5072  // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
5073  // global base reg.
5074  unsigned char OpFlag = 0;
5075  unsigned WrapperKind = X86ISD::Wrapper;
5076  CodeModel::Model M = getTargetMachine().getCodeModel();
5077
5078  if (Subtarget->isPICStyleRIPRel() &&
5079      (M == CodeModel::Small || M == CodeModel::Kernel))
5080    WrapperKind = X86ISD::WrapperRIP;
5081  else if (Subtarget->isPICStyleGOT())
5082    OpFlag = X86II::MO_GOTOFF;
5083  else if (Subtarget->isPICStyleStubPIC())
5084    OpFlag = X86II::MO_PIC_BASE_OFFSET;
5085
5086  SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
5087                                          OpFlag);
5088  DebugLoc DL = JT->getDebugLoc();
5089  Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
5090
5091  // With PIC, the address is actually $g + Offset.
5092  if (OpFlag) {
5093    Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
5094                         DAG.getNode(X86ISD::GlobalBaseReg,
5095                                     DebugLoc(), getPointerTy()),
5096                         Result);
5097  }
5098
5099  return Result;
5100}
5101
5102SDValue
5103X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) {
5104  const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
5105
5106  // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
5107  // global base reg.
5108  unsigned char OpFlag = 0;
5109  unsigned WrapperKind = X86ISD::Wrapper;
5110  CodeModel::Model M = getTargetMachine().getCodeModel();
5111
5112  if (Subtarget->isPICStyleRIPRel() &&
5113      (M == CodeModel::Small || M == CodeModel::Kernel))
5114    WrapperKind = X86ISD::WrapperRIP;
5115  else if (Subtarget->isPICStyleGOT())
5116    OpFlag = X86II::MO_GOTOFF;
5117  else if (Subtarget->isPICStyleStubPIC())
5118    OpFlag = X86II::MO_PIC_BASE_OFFSET;
5119
5120  SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
5121
5122  DebugLoc DL = Op.getDebugLoc();
5123  Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
5124
5125
5126  // With PIC, the address is actually $g + Offset.
5127  if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
5128      !Subtarget->is64Bit()) {
5129    Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
5130                         DAG.getNode(X86ISD::GlobalBaseReg,
5131                                     DebugLoc(), getPointerTy()),
5132                         Result);
5133  }
5134
5135  return Result;
5136}
5137
5138SDValue
5139X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) {
5140  // Create the TargetBlockAddressAddress node.
5141  unsigned char OpFlags =
5142    Subtarget->ClassifyBlockAddressReference();
5143  CodeModel::Model M = getTargetMachine().getCodeModel();
5144  BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
5145  DebugLoc dl = Op.getDebugLoc();
5146  SDValue Result = DAG.getBlockAddress(BA, getPointerTy(),
5147                                       /*isTarget=*/true, OpFlags);
5148
5149  if (Subtarget->isPICStyleRIPRel() &&
5150      (M == CodeModel::Small || M == CodeModel::Kernel))
5151    Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
5152  else
5153    Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
5154
5155  // With PIC, the address is actually $g + Offset.
5156  if (isGlobalRelativeToPICBase(OpFlags)) {
5157    Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
5158                         DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
5159                         Result);
5160  }
5161
5162  return Result;
5163}
5164
5165SDValue
5166X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, DebugLoc dl,
5167                                      int64_t Offset,
5168                                      SelectionDAG &DAG) const {
5169  // Create the TargetGlobalAddress node, folding in the constant
5170  // offset if it is legal.
5171  unsigned char OpFlags =
5172    Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
5173  CodeModel::Model M = getTargetMachine().getCodeModel();
5174  SDValue Result;
5175  if (OpFlags == X86II::MO_NO_FLAG &&
5176      X86::isOffsetSuitableForCodeModel(Offset, M)) {
5177    // A direct static reference to a global.
5178    Result = DAG.getTargetGlobalAddress(GV, getPointerTy(), Offset);
5179    Offset = 0;
5180  } else {
5181    Result = DAG.getTargetGlobalAddress(GV, getPointerTy(), 0, OpFlags);
5182  }
5183
5184  if (Subtarget->isPICStyleRIPRel() &&
5185      (M == CodeModel::Small || M == CodeModel::Kernel))
5186    Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
5187  else
5188    Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
5189
5190  // With PIC, the address is actually $g + Offset.
5191  if (isGlobalRelativeToPICBase(OpFlags)) {
5192    Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
5193                         DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
5194                         Result);
5195  }
5196
5197  // For globals that require a load from a stub to get the address, emit the
5198  // load.
5199  if (isGlobalStubReference(OpFlags))
5200    Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
5201                         PseudoSourceValue::getGOT(), 0, false, false, 0);
5202
5203  // If there was a non-zero offset that we didn't fold, create an explicit
5204  // addition for it.
5205  if (Offset != 0)
5206    Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
5207                         DAG.getConstant(Offset, getPointerTy()));
5208
5209  return Result;
5210}
5211
5212SDValue
5213X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) {
5214  const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
5215  int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
5216  return LowerGlobalAddress(GV, Op.getDebugLoc(), Offset, DAG);
5217}
5218
5219static SDValue
5220GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
5221           SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
5222           unsigned char OperandFlags) {
5223  MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
5224  SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
5225  DebugLoc dl = GA->getDebugLoc();
5226  SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(),
5227                                           GA->getValueType(0),
5228                                           GA->getOffset(),
5229                                           OperandFlags);
5230  if (InFlag) {
5231    SDValue Ops[] = { Chain,  TGA, *InFlag };
5232    Chain = DAG.getNode(X86ISD::TLSADDR, dl, NodeTys, Ops, 3);
5233  } else {
5234    SDValue Ops[]  = { Chain, TGA };
5235    Chain = DAG.getNode(X86ISD::TLSADDR, dl, NodeTys, Ops, 2);
5236  }
5237
5238  // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
5239  MFI->setHasCalls(true);
5240
5241  SDValue Flag = Chain.getValue(1);
5242  return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
5243}
5244
5245// Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
5246static SDValue
5247LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
5248                                const EVT PtrVT) {
5249  SDValue InFlag;
5250  DebugLoc dl = GA->getDebugLoc();  // ? function entry point might be better
5251  SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
5252                                     DAG.getNode(X86ISD::GlobalBaseReg,
5253                                                 DebugLoc(), PtrVT), InFlag);
5254  InFlag = Chain.getValue(1);
5255
5256  return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
5257}
5258
5259// Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
5260static SDValue
5261LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
5262                                const EVT PtrVT) {
5263  return GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT,
5264                    X86::RAX, X86II::MO_TLSGD);
5265}
5266
5267// Lower ISD::GlobalTLSAddress using the "initial exec" (for no-pic) or
5268// "local exec" model.
5269static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
5270                                   const EVT PtrVT, TLSModel::Model model,
5271                                   bool is64Bit) {
5272  DebugLoc dl = GA->getDebugLoc();
5273  // Get the Thread Pointer
5274  SDValue Base = DAG.getNode(X86ISD::SegmentBaseAddress,
5275                             DebugLoc(), PtrVT,
5276                             DAG.getRegister(is64Bit? X86::FS : X86::GS,
5277                                             MVT::i32));
5278
5279  SDValue ThreadPointer = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Base,
5280                                      NULL, 0, false, false, 0);
5281
5282  unsigned char OperandFlags = 0;
5283  // Most TLS accesses are not RIP relative, even on x86-64.  One exception is
5284  // initialexec.
5285  unsigned WrapperKind = X86ISD::Wrapper;
5286  if (model == TLSModel::LocalExec) {
5287    OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
5288  } else if (is64Bit) {
5289    assert(model == TLSModel::InitialExec);
5290    OperandFlags = X86II::MO_GOTTPOFF;
5291    WrapperKind = X86ISD::WrapperRIP;
5292  } else {
5293    assert(model == TLSModel::InitialExec);
5294    OperandFlags = X86II::MO_INDNTPOFF;
5295  }
5296
5297  // emit "addl x@ntpoff,%eax" (local exec) or "addl x@indntpoff,%eax" (initial
5298  // exec)
5299  SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), GA->getValueType(0),
5300                                           GA->getOffset(), OperandFlags);
5301  SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
5302
5303  if (model == TLSModel::InitialExec)
5304    Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
5305                         PseudoSourceValue::getGOT(), 0, false, false, 0);
5306
5307  // The address of the thread local variable is the add of the thread
5308  // pointer with the offset of the variable.
5309  return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
5310}
5311
5312SDValue
5313X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) {
5314  // TODO: implement the "local dynamic" model
5315  // TODO: implement the "initial exec"model for pic executables
5316  assert(Subtarget->isTargetELF() &&
5317         "TLS not implemented for non-ELF targets");
5318  GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
5319  const GlobalValue *GV = GA->getGlobal();
5320
5321  // If GV is an alias then use the aliasee for determining
5322  // thread-localness.
5323  if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
5324    GV = GA->resolveAliasedGlobal(false);
5325
5326  TLSModel::Model model = getTLSModel(GV,
5327                                      getTargetMachine().getRelocationModel());
5328
5329  switch (model) {
5330  case TLSModel::GeneralDynamic:
5331  case TLSModel::LocalDynamic: // not implemented
5332    if (Subtarget->is64Bit())
5333      return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
5334    return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
5335
5336  case TLSModel::InitialExec:
5337  case TLSModel::LocalExec:
5338    return LowerToTLSExecModel(GA, DAG, getPointerTy(), model,
5339                               Subtarget->is64Bit());
5340  }
5341
5342  llvm_unreachable("Unreachable");
5343  return SDValue();
5344}
5345
5346
5347/// LowerShift - Lower SRA_PARTS and friends, which return two i32 values and
5348/// take a 2 x i32 value to shift plus a shift amount.
5349SDValue X86TargetLowering::LowerShift(SDValue Op, SelectionDAG &DAG) {
5350  assert(Op.getNumOperands() == 3 && "Not a double-shift!");
5351  EVT VT = Op.getValueType();
5352  unsigned VTBits = VT.getSizeInBits();
5353  DebugLoc dl = Op.getDebugLoc();
5354  bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
5355  SDValue ShOpLo = Op.getOperand(0);
5356  SDValue ShOpHi = Op.getOperand(1);
5357  SDValue ShAmt  = Op.getOperand(2);
5358  SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
5359                                     DAG.getConstant(VTBits - 1, MVT::i8))
5360                       : DAG.getConstant(0, VT);
5361
5362  SDValue Tmp2, Tmp3;
5363  if (Op.getOpcode() == ISD::SHL_PARTS) {
5364    Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
5365    Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
5366  } else {
5367    Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
5368    Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, ShAmt);
5369  }
5370
5371  SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
5372                                DAG.getConstant(VTBits, MVT::i8));
5373  SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
5374                             AndNode, DAG.getConstant(0, MVT::i8));
5375
5376  SDValue Hi, Lo;
5377  SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
5378  SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
5379  SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
5380
5381  if (Op.getOpcode() == ISD::SHL_PARTS) {
5382    Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
5383    Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
5384  } else {
5385    Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
5386    Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
5387  }
5388
5389  SDValue Ops[2] = { Lo, Hi };
5390  return DAG.getMergeValues(Ops, 2, dl);
5391}
5392
5393SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
5394  EVT SrcVT = Op.getOperand(0).getValueType();
5395
5396  if (SrcVT.isVector()) {
5397    if (SrcVT == MVT::v2i32 && Op.getValueType() == MVT::v2f64) {
5398      return Op;
5399    }
5400    return SDValue();
5401  }
5402
5403  assert(SrcVT.getSimpleVT() <= MVT::i64 && SrcVT.getSimpleVT() >= MVT::i16 &&
5404         "Unknown SINT_TO_FP to lower!");
5405
5406  // These are really Legal; return the operand so the caller accepts it as
5407  // Legal.
5408  if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
5409    return Op;
5410  if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
5411      Subtarget->is64Bit()) {
5412    return Op;
5413  }
5414
5415  DebugLoc dl = Op.getDebugLoc();
5416  unsigned Size = SrcVT.getSizeInBits()/8;
5417  MachineFunction &MF = DAG.getMachineFunction();
5418  int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
5419  SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
5420  SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
5421                               StackSlot,
5422                               PseudoSourceValue::getFixedStack(SSFI), 0,
5423                               false, false, 0);
5424  return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
5425}
5426
5427SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
5428                                     SDValue StackSlot,
5429                                     SelectionDAG &DAG) {
5430  // Build the FILD
5431  DebugLoc dl = Op.getDebugLoc();
5432  SDVTList Tys;
5433  bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
5434  if (useSSE)
5435    Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Flag);
5436  else
5437    Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
5438  SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
5439  SDValue Result = DAG.getNode(useSSE ? X86ISD::FILD_FLAG : X86ISD::FILD, dl,
5440                               Tys, Ops, array_lengthof(Ops));
5441
5442  if (useSSE) {
5443    Chain = Result.getValue(1);
5444    SDValue InFlag = Result.getValue(2);
5445
5446    // FIXME: Currently the FST is flagged to the FILD_FLAG. This
5447    // shouldn't be necessary except that RFP cannot be live across
5448    // multiple blocks. When stackifier is fixed, they can be uncoupled.
5449    MachineFunction &MF = DAG.getMachineFunction();
5450    int SSFI = MF.getFrameInfo()->CreateStackObject(8, 8, false);
5451    SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
5452    Tys = DAG.getVTList(MVT::Other);
5453    SDValue Ops[] = {
5454      Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
5455    };
5456    Chain = DAG.getNode(X86ISD::FST, dl, Tys, Ops, array_lengthof(Ops));
5457    Result = DAG.getLoad(Op.getValueType(), dl, Chain, StackSlot,
5458                         PseudoSourceValue::getFixedStack(SSFI), 0,
5459                         false, false, 0);
5460  }
5461
5462  return Result;
5463}
5464
5465// LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
5466SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op, SelectionDAG &DAG) {
5467  // This algorithm is not obvious. Here it is in C code, more or less:
5468  /*
5469    double uint64_to_double( uint32_t hi, uint32_t lo ) {
5470      static const __m128i exp = { 0x4330000045300000ULL, 0 };
5471      static const __m128d bias = { 0x1.0p84, 0x1.0p52 };
5472
5473      // Copy ints to xmm registers.
5474      __m128i xh = _mm_cvtsi32_si128( hi );
5475      __m128i xl = _mm_cvtsi32_si128( lo );
5476
5477      // Combine into low half of a single xmm register.
5478      __m128i x = _mm_unpacklo_epi32( xh, xl );
5479      __m128d d;
5480      double sd;
5481
5482      // Merge in appropriate exponents to give the integer bits the right
5483      // magnitude.
5484      x = _mm_unpacklo_epi32( x, exp );
5485
5486      // Subtract away the biases to deal with the IEEE-754 double precision
5487      // implicit 1.
5488      d = _mm_sub_pd( (__m128d) x, bias );
5489
5490      // All conversions up to here are exact. The correctly rounded result is
5491      // calculated using the current rounding mode using the following
5492      // horizontal add.
5493      d = _mm_add_sd( d, _mm_unpackhi_pd( d, d ) );
5494      _mm_store_sd( &sd, d );   // Because we are returning doubles in XMM, this
5495                                // store doesn't really need to be here (except
5496                                // maybe to zero the other double)
5497      return sd;
5498    }
5499  */
5500
5501  DebugLoc dl = Op.getDebugLoc();
5502  LLVMContext *Context = DAG.getContext();
5503
5504  // Build some magic constants.
5505  std::vector<Constant*> CV0;
5506  CV0.push_back(ConstantInt::get(*Context, APInt(32, 0x45300000)));
5507  CV0.push_back(ConstantInt::get(*Context, APInt(32, 0x43300000)));
5508  CV0.push_back(ConstantInt::get(*Context, APInt(32, 0)));
5509  CV0.push_back(ConstantInt::get(*Context, APInt(32, 0)));
5510  Constant *C0 = ConstantVector::get(CV0);
5511  SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
5512
5513  std::vector<Constant*> CV1;
5514  CV1.push_back(
5515    ConstantFP::get(*Context, APFloat(APInt(64, 0x4530000000000000ULL))));
5516  CV1.push_back(
5517    ConstantFP::get(*Context, APFloat(APInt(64, 0x4330000000000000ULL))));
5518  Constant *C1 = ConstantVector::get(CV1);
5519  SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
5520
5521  SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
5522                            DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
5523                                        Op.getOperand(0),
5524                                        DAG.getIntPtrConstant(1)));
5525  SDValue XR2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
5526                            DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
5527                                        Op.getOperand(0),
5528                                        DAG.getIntPtrConstant(0)));
5529  SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32, XR1, XR2);
5530  SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
5531                              PseudoSourceValue::getConstantPool(), 0,
5532                              false, false, 16);
5533  SDValue Unpck2 = getUnpackl(DAG, dl, MVT::v4i32, Unpck1, CLod0);
5534  SDValue XR2F = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2f64, Unpck2);
5535  SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
5536                              PseudoSourceValue::getConstantPool(), 0,
5537                              false, false, 16);
5538  SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
5539
5540  // Add the halves; easiest way is to swap them into another reg first.
5541  int ShufMask[2] = { 1, -1 };
5542  SDValue Shuf = DAG.getVectorShuffle(MVT::v2f64, dl, Sub,
5543                                      DAG.getUNDEF(MVT::v2f64), ShufMask);
5544  SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::v2f64, Shuf, Sub);
5545  return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Add,
5546                     DAG.getIntPtrConstant(0));
5547}
5548
5549// LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
5550SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op, SelectionDAG &DAG) {
5551  DebugLoc dl = Op.getDebugLoc();
5552  // FP constant to bias correct the final result.
5553  SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
5554                                   MVT::f64);
5555
5556  // Load the 32-bit value into an XMM register.
5557  SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
5558                             DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
5559                                         Op.getOperand(0),
5560                                         DAG.getIntPtrConstant(0)));
5561
5562  Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
5563                     DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2f64, Load),
5564                     DAG.getIntPtrConstant(0));
5565
5566  // Or the load with the bias.
5567  SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
5568                           DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64,
5569                                       DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
5570                                                   MVT::v2f64, Load)),
5571                           DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64,
5572                                       DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
5573                                                   MVT::v2f64, Bias)));
5574  Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
5575                   DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2f64, Or),
5576                   DAG.getIntPtrConstant(0));
5577
5578  // Subtract the bias.
5579  SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
5580
5581  // Handle final rounding.
5582  EVT DestVT = Op.getValueType();
5583
5584  if (DestVT.bitsLT(MVT::f64)) {
5585    return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
5586                       DAG.getIntPtrConstant(0));
5587  } else if (DestVT.bitsGT(MVT::f64)) {
5588    return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
5589  }
5590
5591  // Handle final rounding.
5592  return Sub;
5593}
5594
5595SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
5596  SDValue N0 = Op.getOperand(0);
5597  DebugLoc dl = Op.getDebugLoc();
5598
5599  // Now not UINT_TO_FP is legal (it's marked custom), dag combiner won't
5600  // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
5601  // the optimization here.
5602  if (DAG.SignBitIsZero(N0))
5603    return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
5604
5605  EVT SrcVT = N0.getValueType();
5606  if (SrcVT == MVT::i64) {
5607    // We only handle SSE2 f64 target here; caller can expand the rest.
5608    if (Op.getValueType() != MVT::f64 || !X86ScalarSSEf64)
5609      return SDValue();
5610
5611    return LowerUINT_TO_FP_i64(Op, DAG);
5612  } else if (SrcVT == MVT::i32 && X86ScalarSSEf64) {
5613    return LowerUINT_TO_FP_i32(Op, DAG);
5614  }
5615
5616  assert(SrcVT == MVT::i32 && "Unknown UINT_TO_FP to lower!");
5617
5618  // Make a 64-bit buffer, and use it to build an FILD.
5619  SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
5620  SDValue WordOff = DAG.getConstant(4, getPointerTy());
5621  SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
5622                                   getPointerTy(), StackSlot, WordOff);
5623  SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
5624                                StackSlot, NULL, 0, false, false, 0);
5625  SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
5626                                OffsetSlot, NULL, 0, false, false, 0);
5627  return BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
5628}
5629
5630std::pair<SDValue,SDValue> X86TargetLowering::
5631FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG, bool IsSigned) {
5632  DebugLoc dl = Op.getDebugLoc();
5633
5634  EVT DstTy = Op.getValueType();
5635
5636  if (!IsSigned) {
5637    assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
5638    DstTy = MVT::i64;
5639  }
5640
5641  assert(DstTy.getSimpleVT() <= MVT::i64 &&
5642         DstTy.getSimpleVT() >= MVT::i16 &&
5643         "Unknown FP_TO_SINT to lower!");
5644
5645  // These are really Legal.
5646  if (DstTy == MVT::i32 &&
5647      isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
5648    return std::make_pair(SDValue(), SDValue());
5649  if (Subtarget->is64Bit() &&
5650      DstTy == MVT::i64 &&
5651      isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
5652    return std::make_pair(SDValue(), SDValue());
5653
5654  // We lower FP->sint64 into FISTP64, followed by a load, all to a temporary
5655  // stack slot.
5656  MachineFunction &MF = DAG.getMachineFunction();
5657  unsigned MemSize = DstTy.getSizeInBits()/8;
5658  int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
5659  SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
5660
5661  unsigned Opc;
5662  switch (DstTy.getSimpleVT().SimpleTy) {
5663  default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
5664  case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
5665  case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
5666  case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
5667  }
5668
5669  SDValue Chain = DAG.getEntryNode();
5670  SDValue Value = Op.getOperand(0);
5671  if (isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType())) {
5672    assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
5673    Chain = DAG.getStore(Chain, dl, Value, StackSlot,
5674                         PseudoSourceValue::getFixedStack(SSFI), 0,
5675                         false, false, 0);
5676    SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
5677    SDValue Ops[] = {
5678      Chain, StackSlot, DAG.getValueType(Op.getOperand(0).getValueType())
5679    };
5680    Value = DAG.getNode(X86ISD::FLD, dl, Tys, Ops, 3);
5681    Chain = Value.getValue(1);
5682    SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
5683    StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
5684  }
5685
5686  // Build the FP_TO_INT*_IN_MEM
5687  SDValue Ops[] = { Chain, Value, StackSlot };
5688  SDValue FIST = DAG.getNode(Opc, dl, MVT::Other, Ops, 3);
5689
5690  return std::make_pair(FIST, StackSlot);
5691}
5692
5693SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op, SelectionDAG &DAG) {
5694  if (Op.getValueType().isVector()) {
5695    if (Op.getValueType() == MVT::v2i32 &&
5696        Op.getOperand(0).getValueType() == MVT::v2f64) {
5697      return Op;
5698    }
5699    return SDValue();
5700  }
5701
5702  std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG, true);
5703  SDValue FIST = Vals.first, StackSlot = Vals.second;
5704  // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
5705  if (FIST.getNode() == 0) return Op;
5706
5707  // Load the result.
5708  return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
5709                     FIST, StackSlot, NULL, 0, false, false, 0);
5710}
5711
5712SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op, SelectionDAG &DAG) {
5713  std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG, false);
5714  SDValue FIST = Vals.first, StackSlot = Vals.second;
5715  assert(FIST.getNode() && "Unexpected failure");
5716
5717  // Load the result.
5718  return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
5719                     FIST, StackSlot, NULL, 0, false, false, 0);
5720}
5721
5722SDValue X86TargetLowering::LowerFABS(SDValue Op, SelectionDAG &DAG) {
5723  LLVMContext *Context = DAG.getContext();
5724  DebugLoc dl = Op.getDebugLoc();
5725  EVT VT = Op.getValueType();
5726  EVT EltVT = VT;
5727  if (VT.isVector())
5728    EltVT = VT.getVectorElementType();
5729  std::vector<Constant*> CV;
5730  if (EltVT == MVT::f64) {
5731    Constant *C = ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63))));
5732    CV.push_back(C);
5733    CV.push_back(C);
5734  } else {
5735    Constant *C = ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31))));
5736    CV.push_back(C);
5737    CV.push_back(C);
5738    CV.push_back(C);
5739    CV.push_back(C);
5740  }
5741  Constant *C = ConstantVector::get(CV);
5742  SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
5743  SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
5744                             PseudoSourceValue::getConstantPool(), 0,
5745                             false, false, 16);
5746  return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
5747}
5748
5749SDValue X86TargetLowering::LowerFNEG(SDValue Op, SelectionDAG &DAG) {
5750  LLVMContext *Context = DAG.getContext();
5751  DebugLoc dl = Op.getDebugLoc();
5752  EVT VT = Op.getValueType();
5753  EVT EltVT = VT;
5754  if (VT.isVector())
5755    EltVT = VT.getVectorElementType();
5756  std::vector<Constant*> CV;
5757  if (EltVT == MVT::f64) {
5758    Constant *C = ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63)));
5759    CV.push_back(C);
5760    CV.push_back(C);
5761  } else {
5762    Constant *C = ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31)));
5763    CV.push_back(C);
5764    CV.push_back(C);
5765    CV.push_back(C);
5766    CV.push_back(C);
5767  }
5768  Constant *C = ConstantVector::get(CV);
5769  SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
5770  SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
5771                             PseudoSourceValue::getConstantPool(), 0,
5772                             false, false, 16);
5773  if (VT.isVector()) {
5774    return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
5775                       DAG.getNode(ISD::XOR, dl, MVT::v2i64,
5776                    DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64,
5777                                Op.getOperand(0)),
5778                    DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64, Mask)));
5779  } else {
5780    return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
5781  }
5782}
5783
5784SDValue X86TargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) {
5785  LLVMContext *Context = DAG.getContext();
5786  SDValue Op0 = Op.getOperand(0);
5787  SDValue Op1 = Op.getOperand(1);
5788  DebugLoc dl = Op.getDebugLoc();
5789  EVT VT = Op.getValueType();
5790  EVT SrcVT = Op1.getValueType();
5791
5792  // If second operand is smaller, extend it first.
5793  if (SrcVT.bitsLT(VT)) {
5794    Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
5795    SrcVT = VT;
5796  }
5797  // And if it is bigger, shrink it first.
5798  if (SrcVT.bitsGT(VT)) {
5799    Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
5800    SrcVT = VT;
5801  }
5802
5803  // At this point the operands and the result should have the same
5804  // type, and that won't be f80 since that is not custom lowered.
5805
5806  // First get the sign bit of second operand.
5807  std::vector<Constant*> CV;
5808  if (SrcVT == MVT::f64) {
5809    CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63))));
5810    CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
5811  } else {
5812    CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31))));
5813    CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
5814    CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
5815    CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
5816  }
5817  Constant *C = ConstantVector::get(CV);
5818  SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
5819  SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
5820                              PseudoSourceValue::getConstantPool(), 0,
5821                              false, false, 16);
5822  SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
5823
5824  // Shift sign bit right or left if the two operands have different types.
5825  if (SrcVT.bitsGT(VT)) {
5826    // Op0 is MVT::f32, Op1 is MVT::f64.
5827    SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
5828    SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
5829                          DAG.getConstant(32, MVT::i32));
5830    SignBit = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v4f32, SignBit);
5831    SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
5832                          DAG.getIntPtrConstant(0));
5833  }
5834
5835  // Clear first operand sign bit.
5836  CV.clear();
5837  if (VT == MVT::f64) {
5838    CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63)))));
5839    CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
5840  } else {
5841    CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31)))));
5842    CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
5843    CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
5844    CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
5845  }
5846  C = ConstantVector::get(CV);
5847  CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
5848  SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
5849                              PseudoSourceValue::getConstantPool(), 0,
5850                              false, false, 16);
5851  SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
5852
5853  // Or the value with the sign bit.
5854  return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
5855}
5856
5857/// Emit nodes that will be selected as "test Op0,Op0", or something
5858/// equivalent.
5859SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC,
5860                                    SelectionDAG &DAG) {
5861  DebugLoc dl = Op.getDebugLoc();
5862
5863  // CF and OF aren't always set the way we want. Determine which
5864  // of these we need.
5865  bool NeedCF = false;
5866  bool NeedOF = false;
5867  switch (X86CC) {
5868  case X86::COND_A: case X86::COND_AE:
5869  case X86::COND_B: case X86::COND_BE:
5870    NeedCF = true;
5871    break;
5872  case X86::COND_G: case X86::COND_GE:
5873  case X86::COND_L: case X86::COND_LE:
5874  case X86::COND_O: case X86::COND_NO:
5875    NeedOF = true;
5876    break;
5877  default: break;
5878  }
5879
5880  // See if we can use the EFLAGS value from the operand instead of
5881  // doing a separate TEST. TEST always sets OF and CF to 0, so unless
5882  // we prove that the arithmetic won't overflow, we can't use OF or CF.
5883  if (Op.getResNo() == 0 && !NeedOF && !NeedCF) {
5884    unsigned Opcode = 0;
5885    unsigned NumOperands = 0;
5886    switch (Op.getNode()->getOpcode()) {
5887    case ISD::ADD:
5888      // Due to an isel shortcoming, be conservative if this add is likely to
5889      // be selected as part of a load-modify-store instruction. When the root
5890      // node in a match is a store, isel doesn't know how to remap non-chain
5891      // non-flag uses of other nodes in the match, such as the ADD in this
5892      // case. This leads to the ADD being left around and reselected, with
5893      // the result being two adds in the output.
5894      for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
5895           UE = Op.getNode()->use_end(); UI != UE; ++UI)
5896        if (UI->getOpcode() == ISD::STORE)
5897          goto default_case;
5898      if (ConstantSDNode *C =
5899            dyn_cast<ConstantSDNode>(Op.getNode()->getOperand(1))) {
5900        // An add of one will be selected as an INC.
5901        if (C->getAPIntValue() == 1) {
5902          Opcode = X86ISD::INC;
5903          NumOperands = 1;
5904          break;
5905        }
5906        // An add of negative one (subtract of one) will be selected as a DEC.
5907        if (C->getAPIntValue().isAllOnesValue()) {
5908          Opcode = X86ISD::DEC;
5909          NumOperands = 1;
5910          break;
5911        }
5912      }
5913      // Otherwise use a regular EFLAGS-setting add.
5914      Opcode = X86ISD::ADD;
5915      NumOperands = 2;
5916      break;
5917    case ISD::AND: {
5918      // If the primary and result isn't used, don't bother using X86ISD::AND,
5919      // because a TEST instruction will be better.
5920      bool NonFlagUse = false;
5921      for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
5922             UE = Op.getNode()->use_end(); UI != UE; ++UI) {
5923        SDNode *User = *UI;
5924        unsigned UOpNo = UI.getOperandNo();
5925        if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
5926          // Look pass truncate.
5927          UOpNo = User->use_begin().getOperandNo();
5928          User = *User->use_begin();
5929        }
5930        if (User->getOpcode() != ISD::BRCOND &&
5931            User->getOpcode() != ISD::SETCC &&
5932            (User->getOpcode() != ISD::SELECT || UOpNo != 0)) {
5933          NonFlagUse = true;
5934          break;
5935        }
5936      }
5937      if (!NonFlagUse)
5938        break;
5939    }
5940    // FALL THROUGH
5941    case ISD::SUB:
5942    case ISD::OR:
5943    case ISD::XOR:
5944      // Due to the ISEL shortcoming noted above, be conservative if this op is
5945      // likely to be selected as part of a load-modify-store instruction.
5946      for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
5947           UE = Op.getNode()->use_end(); UI != UE; ++UI)
5948        if (UI->getOpcode() == ISD::STORE)
5949          goto default_case;
5950      // Otherwise use a regular EFLAGS-setting instruction.
5951      switch (Op.getNode()->getOpcode()) {
5952      case ISD::SUB: Opcode = X86ISD::SUB; break;
5953      case ISD::OR:  Opcode = X86ISD::OR;  break;
5954      case ISD::XOR: Opcode = X86ISD::XOR; break;
5955      case ISD::AND: Opcode = X86ISD::AND; break;
5956      default: llvm_unreachable("unexpected operator!");
5957      }
5958      NumOperands = 2;
5959      break;
5960    case X86ISD::ADD:
5961    case X86ISD::SUB:
5962    case X86ISD::INC:
5963    case X86ISD::DEC:
5964    case X86ISD::OR:
5965    case X86ISD::XOR:
5966    case X86ISD::AND:
5967      return SDValue(Op.getNode(), 1);
5968    default:
5969    default_case:
5970      break;
5971    }
5972    if (Opcode != 0) {
5973      SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
5974      SmallVector<SDValue, 4> Ops;
5975      for (unsigned i = 0; i != NumOperands; ++i)
5976        Ops.push_back(Op.getOperand(i));
5977      SDValue New = DAG.getNode(Opcode, dl, VTs, &Ops[0], NumOperands);
5978      DAG.ReplaceAllUsesWith(Op, New);
5979      return SDValue(New.getNode(), 1);
5980    }
5981  }
5982
5983  // Otherwise just emit a CMP with 0, which is the TEST pattern.
5984  return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
5985                     DAG.getConstant(0, Op.getValueType()));
5986}
5987
5988/// Emit nodes that will be selected as "cmp Op0,Op1", or something
5989/// equivalent.
5990SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
5991                                   SelectionDAG &DAG) {
5992  if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1))
5993    if (C->getAPIntValue() == 0)
5994      return EmitTest(Op0, X86CC, DAG);
5995
5996  DebugLoc dl = Op0.getDebugLoc();
5997  return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
5998}
5999
6000/// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
6001/// if it's possible.
6002static SDValue LowerToBT(SDValue And, ISD::CondCode CC,
6003                         DebugLoc dl, SelectionDAG &DAG) {
6004  SDValue Op0 = And.getOperand(0);
6005  SDValue Op1 = And.getOperand(1);
6006  if (Op0.getOpcode() == ISD::TRUNCATE)
6007    Op0 = Op0.getOperand(0);
6008  if (Op1.getOpcode() == ISD::TRUNCATE)
6009    Op1 = Op1.getOperand(0);
6010
6011  SDValue LHS, RHS;
6012  if (Op1.getOpcode() == ISD::SHL) {
6013    if (ConstantSDNode *And10C = dyn_cast<ConstantSDNode>(Op1.getOperand(0)))
6014      if (And10C->getZExtValue() == 1) {
6015        LHS = Op0;
6016        RHS = Op1.getOperand(1);
6017      }
6018  } else if (Op0.getOpcode() == ISD::SHL) {
6019    if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
6020      if (And00C->getZExtValue() == 1) {
6021        LHS = Op1;
6022        RHS = Op0.getOperand(1);
6023      }
6024  } else if (Op1.getOpcode() == ISD::Constant) {
6025    ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
6026    SDValue AndLHS = Op0;
6027    if (AndRHS->getZExtValue() == 1 && AndLHS.getOpcode() == ISD::SRL) {
6028      LHS = AndLHS.getOperand(0);
6029      RHS = AndLHS.getOperand(1);
6030    }
6031  }
6032
6033  if (LHS.getNode()) {
6034    // If LHS is i8, promote it to i16 with any_extend.  There is no i8 BT
6035    // instruction.  Since the shift amount is in-range-or-undefined, we know
6036    // that doing a bittest on the i16 value is ok.  We extend to i32 because
6037    // the encoding for the i16 version is larger than the i32 version.
6038    if (LHS.getValueType() == MVT::i8)
6039      LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
6040
6041    // If the operand types disagree, extend the shift amount to match.  Since
6042    // BT ignores high bits (like shifts) we can use anyextend.
6043    if (LHS.getValueType() != RHS.getValueType())
6044      RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
6045
6046    SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
6047    unsigned Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
6048    return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
6049                       DAG.getConstant(Cond, MVT::i8), BT);
6050  }
6051
6052  return SDValue();
6053}
6054
6055SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) {
6056  assert(Op.getValueType() == MVT::i8 && "SetCC type must be 8-bit integer");
6057  SDValue Op0 = Op.getOperand(0);
6058  SDValue Op1 = Op.getOperand(1);
6059  DebugLoc dl = Op.getDebugLoc();
6060  ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
6061
6062  // Optimize to BT if possible.
6063  // Lower (X & (1 << N)) == 0 to BT(X, N).
6064  // Lower ((X >>u N) & 1) != 0 to BT(X, N).
6065  // Lower ((X >>s N) & 1) != 0 to BT(X, N).
6066  if (Op0.getOpcode() == ISD::AND &&
6067      Op0.hasOneUse() &&
6068      Op1.getOpcode() == ISD::Constant &&
6069      cast<ConstantSDNode>(Op1)->getZExtValue() == 0 &&
6070      (CC == ISD::SETEQ || CC == ISD::SETNE)) {
6071    SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
6072    if (NewSetCC.getNode())
6073      return NewSetCC;
6074  }
6075
6076  // Look for "(setcc) == / != 1" to avoid unncessary setcc.
6077  if (Op0.getOpcode() == X86ISD::SETCC &&
6078      Op1.getOpcode() == ISD::Constant &&
6079      (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
6080       cast<ConstantSDNode>(Op1)->isNullValue()) &&
6081      (CC == ISD::SETEQ || CC == ISD::SETNE)) {
6082    X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
6083    bool Invert = (CC == ISD::SETNE) ^
6084      cast<ConstantSDNode>(Op1)->isNullValue();
6085    if (Invert)
6086      CCode = X86::GetOppositeBranchCondition(CCode);
6087    return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
6088                       DAG.getConstant(CCode, MVT::i8), Op0.getOperand(1));
6089  }
6090
6091  bool isFP = Op.getOperand(1).getValueType().isFloatingPoint();
6092  unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
6093  if (X86CC == X86::COND_INVALID)
6094    return SDValue();
6095
6096  SDValue Cond = EmitCmp(Op0, Op1, X86CC, DAG);
6097
6098  // Use sbb x, x to materialize carry bit into a GPR.
6099  if (X86CC == X86::COND_B)
6100    return DAG.getNode(ISD::AND, dl, MVT::i8,
6101                       DAG.getNode(X86ISD::SETCC_CARRY, dl, MVT::i8,
6102                                   DAG.getConstant(X86CC, MVT::i8), Cond),
6103                       DAG.getConstant(1, MVT::i8));
6104
6105  return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
6106                     DAG.getConstant(X86CC, MVT::i8), Cond);
6107}
6108
6109SDValue X86TargetLowering::LowerVSETCC(SDValue Op, SelectionDAG &DAG) {
6110  SDValue Cond;
6111  SDValue Op0 = Op.getOperand(0);
6112  SDValue Op1 = Op.getOperand(1);
6113  SDValue CC = Op.getOperand(2);
6114  EVT VT = Op.getValueType();
6115  ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
6116  bool isFP = Op.getOperand(1).getValueType().isFloatingPoint();
6117  DebugLoc dl = Op.getDebugLoc();
6118
6119  if (isFP) {
6120    unsigned SSECC = 8;
6121    EVT VT0 = Op0.getValueType();
6122    assert(VT0 == MVT::v4f32 || VT0 == MVT::v2f64);
6123    unsigned Opc = VT0 == MVT::v4f32 ? X86ISD::CMPPS : X86ISD::CMPPD;
6124    bool Swap = false;
6125
6126    switch (SetCCOpcode) {
6127    default: break;
6128    case ISD::SETOEQ:
6129    case ISD::SETEQ:  SSECC = 0; break;
6130    case ISD::SETOGT:
6131    case ISD::SETGT: Swap = true; // Fallthrough
6132    case ISD::SETLT:
6133    case ISD::SETOLT: SSECC = 1; break;
6134    case ISD::SETOGE:
6135    case ISD::SETGE: Swap = true; // Fallthrough
6136    case ISD::SETLE:
6137    case ISD::SETOLE: SSECC = 2; break;
6138    case ISD::SETUO:  SSECC = 3; break;
6139    case ISD::SETUNE:
6140    case ISD::SETNE:  SSECC = 4; break;
6141    case ISD::SETULE: Swap = true;
6142    case ISD::SETUGE: SSECC = 5; break;
6143    case ISD::SETULT: Swap = true;
6144    case ISD::SETUGT: SSECC = 6; break;
6145    case ISD::SETO:   SSECC = 7; break;
6146    }
6147    if (Swap)
6148      std::swap(Op0, Op1);
6149
6150    // In the two special cases we can't handle, emit two comparisons.
6151    if (SSECC == 8) {
6152      if (SetCCOpcode == ISD::SETUEQ) {
6153        SDValue UNORD, EQ;
6154        UNORD = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(3, MVT::i8));
6155        EQ = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(0, MVT::i8));
6156        return DAG.getNode(ISD::OR, dl, VT, UNORD, EQ);
6157      }
6158      else if (SetCCOpcode == ISD::SETONE) {
6159        SDValue ORD, NEQ;
6160        ORD = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(7, MVT::i8));
6161        NEQ = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(4, MVT::i8));
6162        return DAG.getNode(ISD::AND, dl, VT, ORD, NEQ);
6163      }
6164      llvm_unreachable("Illegal FP comparison");
6165    }
6166    // Handle all other FP comparisons here.
6167    return DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(SSECC, MVT::i8));
6168  }
6169
6170  // We are handling one of the integer comparisons here.  Since SSE only has
6171  // GT and EQ comparisons for integer, swapping operands and multiple
6172  // operations may be required for some comparisons.
6173  unsigned Opc = 0, EQOpc = 0, GTOpc = 0;
6174  bool Swap = false, Invert = false, FlipSigns = false;
6175
6176  switch (VT.getSimpleVT().SimpleTy) {
6177  default: break;
6178  case MVT::v8i8:
6179  case MVT::v16i8: EQOpc = X86ISD::PCMPEQB; GTOpc = X86ISD::PCMPGTB; break;
6180  case MVT::v4i16:
6181  case MVT::v8i16: EQOpc = X86ISD::PCMPEQW; GTOpc = X86ISD::PCMPGTW; break;
6182  case MVT::v2i32:
6183  case MVT::v4i32: EQOpc = X86ISD::PCMPEQD; GTOpc = X86ISD::PCMPGTD; break;
6184  case MVT::v2i64: EQOpc = X86ISD::PCMPEQQ; GTOpc = X86ISD::PCMPGTQ; break;
6185  }
6186
6187  switch (SetCCOpcode) {
6188  default: break;
6189  case ISD::SETNE:  Invert = true;
6190  case ISD::SETEQ:  Opc = EQOpc; break;
6191  case ISD::SETLT:  Swap = true;
6192  case ISD::SETGT:  Opc = GTOpc; break;
6193  case ISD::SETGE:  Swap = true;
6194  case ISD::SETLE:  Opc = GTOpc; Invert = true; break;
6195  case ISD::SETULT: Swap = true;
6196  case ISD::SETUGT: Opc = GTOpc; FlipSigns = true; break;
6197  case ISD::SETUGE: Swap = true;
6198  case ISD::SETULE: Opc = GTOpc; FlipSigns = true; Invert = true; break;
6199  }
6200  if (Swap)
6201    std::swap(Op0, Op1);
6202
6203  // Since SSE has no unsigned integer comparisons, we need to flip  the sign
6204  // bits of the inputs before performing those operations.
6205  if (FlipSigns) {
6206    EVT EltVT = VT.getVectorElementType();
6207    SDValue SignBit = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()),
6208                                      EltVT);
6209    std::vector<SDValue> SignBits(VT.getVectorNumElements(), SignBit);
6210    SDValue SignVec = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &SignBits[0],
6211                                    SignBits.size());
6212    Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SignVec);
6213    Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SignVec);
6214  }
6215
6216  SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
6217
6218  // If the logical-not of the result is required, perform that now.
6219  if (Invert)
6220    Result = DAG.getNOT(dl, Result, VT);
6221
6222  return Result;
6223}
6224
6225// isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
6226static bool isX86LogicalCmp(SDValue Op) {
6227  unsigned Opc = Op.getNode()->getOpcode();
6228  if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI)
6229    return true;
6230  if (Op.getResNo() == 1 &&
6231      (Opc == X86ISD::ADD ||
6232       Opc == X86ISD::SUB ||
6233       Opc == X86ISD::SMUL ||
6234       Opc == X86ISD::UMUL ||
6235       Opc == X86ISD::INC ||
6236       Opc == X86ISD::DEC ||
6237       Opc == X86ISD::OR ||
6238       Opc == X86ISD::XOR ||
6239       Opc == X86ISD::AND))
6240    return true;
6241
6242  return false;
6243}
6244
6245SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) {
6246  bool addTest = true;
6247  SDValue Cond  = Op.getOperand(0);
6248  DebugLoc dl = Op.getDebugLoc();
6249  SDValue CC;
6250
6251  if (Cond.getOpcode() == ISD::SETCC) {
6252    SDValue NewCond = LowerSETCC(Cond, DAG);
6253    if (NewCond.getNode())
6254      Cond = NewCond;
6255  }
6256
6257  // (select (x == 0), -1, 0) -> (sign_bit (x - 1))
6258  SDValue Op1 = Op.getOperand(1);
6259  SDValue Op2 = Op.getOperand(2);
6260  if (Cond.getOpcode() == X86ISD::SETCC &&
6261      cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue() == X86::COND_E) {
6262    SDValue Cmp = Cond.getOperand(1);
6263    if (Cmp.getOpcode() == X86ISD::CMP) {
6264      ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op1);
6265      ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
6266      ConstantSDNode *RHSC =
6267        dyn_cast<ConstantSDNode>(Cmp.getOperand(1).getNode());
6268      if (N1C && N1C->isAllOnesValue() &&
6269          N2C && N2C->isNullValue() &&
6270          RHSC && RHSC->isNullValue()) {
6271        SDValue CmpOp0 = Cmp.getOperand(0);
6272        Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
6273                          CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
6274        return DAG.getNode(X86ISD::SETCC_CARRY, dl, Op.getValueType(),
6275                           DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
6276      }
6277    }
6278  }
6279
6280  // Look pass (and (setcc_carry (cmp ...)), 1).
6281  if (Cond.getOpcode() == ISD::AND &&
6282      Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
6283    ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
6284    if (C && C->getAPIntValue() == 1)
6285      Cond = Cond.getOperand(0);
6286  }
6287
6288  // If condition flag is set by a X86ISD::CMP, then use it as the condition
6289  // setting operand in place of the X86ISD::SETCC.
6290  if (Cond.getOpcode() == X86ISD::SETCC ||
6291      Cond.getOpcode() == X86ISD::SETCC_CARRY) {
6292    CC = Cond.getOperand(0);
6293
6294    SDValue Cmp = Cond.getOperand(1);
6295    unsigned Opc = Cmp.getOpcode();
6296    EVT VT = Op.getValueType();
6297
6298    bool IllegalFPCMov = false;
6299    if (VT.isFloatingPoint() && !VT.isVector() &&
6300        !isScalarFPTypeInSSEReg(VT))  // FPStack?
6301      IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
6302
6303    if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
6304        Opc == X86ISD::BT) { // FIXME
6305      Cond = Cmp;
6306      addTest = false;
6307    }
6308  }
6309
6310  if (addTest) {
6311    // Look pass the truncate.
6312    if (Cond.getOpcode() == ISD::TRUNCATE)
6313      Cond = Cond.getOperand(0);
6314
6315    // We know the result of AND is compared against zero. Try to match
6316    // it to BT.
6317    if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
6318      SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
6319      if (NewSetCC.getNode()) {
6320        CC = NewSetCC.getOperand(0);
6321        Cond = NewSetCC.getOperand(1);
6322        addTest = false;
6323      }
6324    }
6325  }
6326
6327  if (addTest) {
6328    CC = DAG.getConstant(X86::COND_NE, MVT::i8);
6329    Cond = EmitTest(Cond, X86::COND_NE, DAG);
6330  }
6331
6332  // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
6333  // condition is true.
6334  SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Flag);
6335  SDValue Ops[] = { Op2, Op1, CC, Cond };
6336  return DAG.getNode(X86ISD::CMOV, dl, VTs, Ops, array_lengthof(Ops));
6337}
6338
6339// isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
6340// ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
6341// from the AND / OR.
6342static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
6343  Opc = Op.getOpcode();
6344  if (Opc != ISD::OR && Opc != ISD::AND)
6345    return false;
6346  return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
6347          Op.getOperand(0).hasOneUse() &&
6348          Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
6349          Op.getOperand(1).hasOneUse());
6350}
6351
6352// isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
6353// 1 and that the SETCC node has a single use.
6354static bool isXor1OfSetCC(SDValue Op) {
6355  if (Op.getOpcode() != ISD::XOR)
6356    return false;
6357  ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
6358  if (N1C && N1C->getAPIntValue() == 1) {
6359    return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
6360      Op.getOperand(0).hasOneUse();
6361  }
6362  return false;
6363}
6364
6365SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) {
6366  bool addTest = true;
6367  SDValue Chain = Op.getOperand(0);
6368  SDValue Cond  = Op.getOperand(1);
6369  SDValue Dest  = Op.getOperand(2);
6370  DebugLoc dl = Op.getDebugLoc();
6371  SDValue CC;
6372
6373  if (Cond.getOpcode() == ISD::SETCC) {
6374    SDValue NewCond = LowerSETCC(Cond, DAG);
6375    if (NewCond.getNode())
6376      Cond = NewCond;
6377  }
6378#if 0
6379  // FIXME: LowerXALUO doesn't handle these!!
6380  else if (Cond.getOpcode() == X86ISD::ADD  ||
6381           Cond.getOpcode() == X86ISD::SUB  ||
6382           Cond.getOpcode() == X86ISD::SMUL ||
6383           Cond.getOpcode() == X86ISD::UMUL)
6384    Cond = LowerXALUO(Cond, DAG);
6385#endif
6386
6387  // Look pass (and (setcc_carry (cmp ...)), 1).
6388  if (Cond.getOpcode() == ISD::AND &&
6389      Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
6390    ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
6391    if (C && C->getAPIntValue() == 1)
6392      Cond = Cond.getOperand(0);
6393  }
6394
6395  // If condition flag is set by a X86ISD::CMP, then use it as the condition
6396  // setting operand in place of the X86ISD::SETCC.
6397  if (Cond.getOpcode() == X86ISD::SETCC ||
6398      Cond.getOpcode() == X86ISD::SETCC_CARRY) {
6399    CC = Cond.getOperand(0);
6400
6401    SDValue Cmp = Cond.getOperand(1);
6402    unsigned Opc = Cmp.getOpcode();
6403    // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
6404    if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
6405      Cond = Cmp;
6406      addTest = false;
6407    } else {
6408      switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
6409      default: break;
6410      case X86::COND_O:
6411      case X86::COND_B:
6412        // These can only come from an arithmetic instruction with overflow,
6413        // e.g. SADDO, UADDO.
6414        Cond = Cond.getNode()->getOperand(1);
6415        addTest = false;
6416        break;
6417      }
6418    }
6419  } else {
6420    unsigned CondOpc;
6421    if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
6422      SDValue Cmp = Cond.getOperand(0).getOperand(1);
6423      if (CondOpc == ISD::OR) {
6424        // Also, recognize the pattern generated by an FCMP_UNE. We can emit
6425        // two branches instead of an explicit OR instruction with a
6426        // separate test.
6427        if (Cmp == Cond.getOperand(1).getOperand(1) &&
6428            isX86LogicalCmp(Cmp)) {
6429          CC = Cond.getOperand(0).getOperand(0);
6430          Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
6431                              Chain, Dest, CC, Cmp);
6432          CC = Cond.getOperand(1).getOperand(0);
6433          Cond = Cmp;
6434          addTest = false;
6435        }
6436      } else { // ISD::AND
6437        // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
6438        // two branches instead of an explicit AND instruction with a
6439        // separate test. However, we only do this if this block doesn't
6440        // have a fall-through edge, because this requires an explicit
6441        // jmp when the condition is false.
6442        if (Cmp == Cond.getOperand(1).getOperand(1) &&
6443            isX86LogicalCmp(Cmp) &&
6444            Op.getNode()->hasOneUse()) {
6445          X86::CondCode CCode =
6446            (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
6447          CCode = X86::GetOppositeBranchCondition(CCode);
6448          CC = DAG.getConstant(CCode, MVT::i8);
6449          SDValue User = SDValue(*Op.getNode()->use_begin(), 0);
6450          // Look for an unconditional branch following this conditional branch.
6451          // We need this because we need to reverse the successors in order
6452          // to implement FCMP_OEQ.
6453          if (User.getOpcode() == ISD::BR) {
6454            SDValue FalseBB = User.getOperand(1);
6455            SDValue NewBR =
6456              DAG.UpdateNodeOperands(User, User.getOperand(0), Dest);
6457            assert(NewBR == User);
6458            Dest = FalseBB;
6459
6460            Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
6461                                Chain, Dest, CC, Cmp);
6462            X86::CondCode CCode =
6463              (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
6464            CCode = X86::GetOppositeBranchCondition(CCode);
6465            CC = DAG.getConstant(CCode, MVT::i8);
6466            Cond = Cmp;
6467            addTest = false;
6468          }
6469        }
6470      }
6471    } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
6472      // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
6473      // It should be transformed during dag combiner except when the condition
6474      // is set by a arithmetics with overflow node.
6475      X86::CondCode CCode =
6476        (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
6477      CCode = X86::GetOppositeBranchCondition(CCode);
6478      CC = DAG.getConstant(CCode, MVT::i8);
6479      Cond = Cond.getOperand(0).getOperand(1);
6480      addTest = false;
6481    }
6482  }
6483
6484  if (addTest) {
6485    // Look pass the truncate.
6486    if (Cond.getOpcode() == ISD::TRUNCATE)
6487      Cond = Cond.getOperand(0);
6488
6489    // We know the result of AND is compared against zero. Try to match
6490    // it to BT.
6491    if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
6492      SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
6493      if (NewSetCC.getNode()) {
6494        CC = NewSetCC.getOperand(0);
6495        Cond = NewSetCC.getOperand(1);
6496        addTest = false;
6497      }
6498    }
6499  }
6500
6501  if (addTest) {
6502    CC = DAG.getConstant(X86::COND_NE, MVT::i8);
6503    Cond = EmitTest(Cond, X86::COND_NE, DAG);
6504  }
6505  return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
6506                     Chain, Dest, CC, Cond);
6507}
6508
6509
6510// Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
6511// Calls to _alloca is needed to probe the stack when allocating more than 4k
6512// bytes in one go. Touching the stack at 4K increments is necessary to ensure
6513// that the guard pages used by the OS virtual memory manager are allocated in
6514// correct sequence.
6515SDValue
6516X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
6517                                           SelectionDAG &DAG) {
6518  assert(Subtarget->isTargetCygMing() &&
6519         "This should be used only on Cygwin/Mingw targets");
6520  DebugLoc dl = Op.getDebugLoc();
6521
6522  // Get the inputs.
6523  SDValue Chain = Op.getOperand(0);
6524  SDValue Size  = Op.getOperand(1);
6525  // FIXME: Ensure alignment here
6526
6527  SDValue Flag;
6528
6529  EVT IntPtr = getPointerTy();
6530  EVT SPTy = Subtarget->is64Bit() ? MVT::i64 : MVT::i32;
6531
6532  Chain = DAG.getCopyToReg(Chain, dl, X86::EAX, Size, Flag);
6533  Flag = Chain.getValue(1);
6534
6535  SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
6536
6537  Chain = DAG.getNode(X86ISD::MINGW_ALLOCA, dl, NodeTys, Chain, Flag);
6538  Flag = Chain.getValue(1);
6539
6540  Chain = DAG.getCopyFromReg(Chain, dl, X86StackPtr, SPTy).getValue(1);
6541
6542  SDValue Ops1[2] = { Chain.getValue(0), Chain };
6543  return DAG.getMergeValues(Ops1, 2, dl);
6544}
6545
6546SDValue
6547X86TargetLowering::EmitTargetCodeForMemset(SelectionDAG &DAG, DebugLoc dl,
6548                                           SDValue Chain,
6549                                           SDValue Dst, SDValue Src,
6550                                           SDValue Size, unsigned Align,
6551                                           bool isVolatile,
6552                                           const Value *DstSV,
6553                                           uint64_t DstSVOff) {
6554  ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
6555
6556  // If not DWORD aligned or size is more than the threshold, call the library.
6557  // The libc version is likely to be faster for these cases. It can use the
6558  // address value and run time information about the CPU.
6559  if ((Align & 3) != 0 ||
6560      !ConstantSize ||
6561      ConstantSize->getZExtValue() >
6562        getSubtarget()->getMaxInlineSizeThreshold()) {
6563    SDValue InFlag(0, 0);
6564
6565    // Check to see if there is a specialized entry-point for memory zeroing.
6566    ConstantSDNode *V = dyn_cast<ConstantSDNode>(Src);
6567
6568    if (const char *bzeroEntry =  V &&
6569        V->isNullValue() ? Subtarget->getBZeroEntry() : 0) {
6570      EVT IntPtr = getPointerTy();
6571      const Type *IntPtrTy = TD->getIntPtrType(*DAG.getContext());
6572      TargetLowering::ArgListTy Args;
6573      TargetLowering::ArgListEntry Entry;
6574      Entry.Node = Dst;
6575      Entry.Ty = IntPtrTy;
6576      Args.push_back(Entry);
6577      Entry.Node = Size;
6578      Args.push_back(Entry);
6579      std::pair<SDValue,SDValue> CallResult =
6580        LowerCallTo(Chain, Type::getVoidTy(*DAG.getContext()),
6581                    false, false, false, false,
6582                    0, CallingConv::C, false, /*isReturnValueUsed=*/false,
6583                    DAG.getExternalSymbol(bzeroEntry, IntPtr), Args, DAG, dl);
6584      return CallResult.second;
6585    }
6586
6587    // Otherwise have the target-independent code call memset.
6588    return SDValue();
6589  }
6590
6591  uint64_t SizeVal = ConstantSize->getZExtValue();
6592  SDValue InFlag(0, 0);
6593  EVT AVT;
6594  SDValue Count;
6595  ConstantSDNode *ValC = dyn_cast<ConstantSDNode>(Src);
6596  unsigned BytesLeft = 0;
6597  bool TwoRepStos = false;
6598  if (ValC) {
6599    unsigned ValReg;
6600    uint64_t Val = ValC->getZExtValue() & 255;
6601
6602    // If the value is a constant, then we can potentially use larger sets.
6603    switch (Align & 3) {
6604    case 2:   // WORD aligned
6605      AVT = MVT::i16;
6606      ValReg = X86::AX;
6607      Val = (Val << 8) | Val;
6608      break;
6609    case 0:  // DWORD aligned
6610      AVT = MVT::i32;
6611      ValReg = X86::EAX;
6612      Val = (Val << 8)  | Val;
6613      Val = (Val << 16) | Val;
6614      if (Subtarget->is64Bit() && ((Align & 0x7) == 0)) {  // QWORD aligned
6615        AVT = MVT::i64;
6616        ValReg = X86::RAX;
6617        Val = (Val << 32) | Val;
6618      }
6619      break;
6620    default:  // Byte aligned
6621      AVT = MVT::i8;
6622      ValReg = X86::AL;
6623      Count = DAG.getIntPtrConstant(SizeVal);
6624      break;
6625    }
6626
6627    if (AVT.bitsGT(MVT::i8)) {
6628      unsigned UBytes = AVT.getSizeInBits() / 8;
6629      Count = DAG.getIntPtrConstant(SizeVal / UBytes);
6630      BytesLeft = SizeVal % UBytes;
6631    }
6632
6633    Chain  = DAG.getCopyToReg(Chain, dl, ValReg, DAG.getConstant(Val, AVT),
6634                              InFlag);
6635    InFlag = Chain.getValue(1);
6636  } else {
6637    AVT = MVT::i8;
6638    Count  = DAG.getIntPtrConstant(SizeVal);
6639    Chain  = DAG.getCopyToReg(Chain, dl, X86::AL, Src, InFlag);
6640    InFlag = Chain.getValue(1);
6641  }
6642
6643  Chain  = DAG.getCopyToReg(Chain, dl, Subtarget->is64Bit() ? X86::RCX :
6644                                                              X86::ECX,
6645                            Count, InFlag);
6646  InFlag = Chain.getValue(1);
6647  Chain  = DAG.getCopyToReg(Chain, dl, Subtarget->is64Bit() ? X86::RDI :
6648                                                              X86::EDI,
6649                            Dst, InFlag);
6650  InFlag = Chain.getValue(1);
6651
6652  SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
6653  SDValue Ops[] = { Chain, DAG.getValueType(AVT), InFlag };
6654  Chain = DAG.getNode(X86ISD::REP_STOS, dl, Tys, Ops, array_lengthof(Ops));
6655
6656  if (TwoRepStos) {
6657    InFlag = Chain.getValue(1);
6658    Count  = Size;
6659    EVT CVT = Count.getValueType();
6660    SDValue Left = DAG.getNode(ISD::AND, dl, CVT, Count,
6661                               DAG.getConstant((AVT == MVT::i64) ? 7 : 3, CVT));
6662    Chain  = DAG.getCopyToReg(Chain, dl, (CVT == MVT::i64) ? X86::RCX :
6663                                                             X86::ECX,
6664                              Left, InFlag);
6665    InFlag = Chain.getValue(1);
6666    Tys = DAG.getVTList(MVT::Other, MVT::Flag);
6667    SDValue Ops[] = { Chain, DAG.getValueType(MVT::i8), InFlag };
6668    Chain = DAG.getNode(X86ISD::REP_STOS, dl, Tys, Ops, array_lengthof(Ops));
6669  } else if (BytesLeft) {
6670    // Handle the last 1 - 7 bytes.
6671    unsigned Offset = SizeVal - BytesLeft;
6672    EVT AddrVT = Dst.getValueType();
6673    EVT SizeVT = Size.getValueType();
6674
6675    Chain = DAG.getMemset(Chain, dl,
6676                          DAG.getNode(ISD::ADD, dl, AddrVT, Dst,
6677                                      DAG.getConstant(Offset, AddrVT)),
6678                          Src,
6679                          DAG.getConstant(BytesLeft, SizeVT),
6680                          Align, isVolatile, DstSV, DstSVOff + Offset);
6681  }
6682
6683  // TODO: Use a Tokenfactor, as in memcpy, instead of a single chain.
6684  return Chain;
6685}
6686
6687SDValue
6688X86TargetLowering::EmitTargetCodeForMemcpy(SelectionDAG &DAG, DebugLoc dl,
6689                                      SDValue Chain, SDValue Dst, SDValue Src,
6690                                      SDValue Size, unsigned Align,
6691                                      bool isVolatile, bool AlwaysInline,
6692                                      const Value *DstSV, uint64_t DstSVOff,
6693                                      const Value *SrcSV, uint64_t SrcSVOff) {
6694  // This requires the copy size to be a constant, preferrably
6695  // within a subtarget-specific limit.
6696  ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
6697  if (!ConstantSize)
6698    return SDValue();
6699  uint64_t SizeVal = ConstantSize->getZExtValue();
6700  if (!AlwaysInline && SizeVal > getSubtarget()->getMaxInlineSizeThreshold())
6701    return SDValue();
6702
6703  /// If not DWORD aligned, call the library.
6704  if ((Align & 3) != 0)
6705    return SDValue();
6706
6707  // DWORD aligned
6708  EVT AVT = MVT::i32;
6709  if (Subtarget->is64Bit() && ((Align & 0x7) == 0))  // QWORD aligned
6710    AVT = MVT::i64;
6711
6712  unsigned UBytes = AVT.getSizeInBits() / 8;
6713  unsigned CountVal = SizeVal / UBytes;
6714  SDValue Count = DAG.getIntPtrConstant(CountVal);
6715  unsigned BytesLeft = SizeVal % UBytes;
6716
6717  SDValue InFlag(0, 0);
6718  Chain  = DAG.getCopyToReg(Chain, dl, Subtarget->is64Bit() ? X86::RCX :
6719                                                              X86::ECX,
6720                            Count, InFlag);
6721  InFlag = Chain.getValue(1);
6722  Chain  = DAG.getCopyToReg(Chain, dl, Subtarget->is64Bit() ? X86::RDI :
6723                                                             X86::EDI,
6724                            Dst, InFlag);
6725  InFlag = Chain.getValue(1);
6726  Chain  = DAG.getCopyToReg(Chain, dl, Subtarget->is64Bit() ? X86::RSI :
6727                                                              X86::ESI,
6728                            Src, InFlag);
6729  InFlag = Chain.getValue(1);
6730
6731  SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
6732  SDValue Ops[] = { Chain, DAG.getValueType(AVT), InFlag };
6733  SDValue RepMovs = DAG.getNode(X86ISD::REP_MOVS, dl, Tys, Ops,
6734                                array_lengthof(Ops));
6735
6736  SmallVector<SDValue, 4> Results;
6737  Results.push_back(RepMovs);
6738  if (BytesLeft) {
6739    // Handle the last 1 - 7 bytes.
6740    unsigned Offset = SizeVal - BytesLeft;
6741    EVT DstVT = Dst.getValueType();
6742    EVT SrcVT = Src.getValueType();
6743    EVT SizeVT = Size.getValueType();
6744    Results.push_back(DAG.getMemcpy(Chain, dl,
6745                                    DAG.getNode(ISD::ADD, dl, DstVT, Dst,
6746                                                DAG.getConstant(Offset, DstVT)),
6747                                    DAG.getNode(ISD::ADD, dl, SrcVT, Src,
6748                                                DAG.getConstant(Offset, SrcVT)),
6749                                    DAG.getConstant(BytesLeft, SizeVT),
6750                                    Align, isVolatile, AlwaysInline,
6751                                    DstSV, DstSVOff + Offset,
6752                                    SrcSV, SrcSVOff + Offset));
6753  }
6754
6755  return DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
6756                     &Results[0], Results.size());
6757}
6758
6759SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) {
6760  const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
6761  DebugLoc dl = Op.getDebugLoc();
6762
6763  if (!Subtarget->is64Bit()) {
6764    // vastart just stores the address of the VarArgsFrameIndex slot into the
6765    // memory location argument.
6766    SDValue FR = DAG.getFrameIndex(VarArgsFrameIndex, getPointerTy());
6767    return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1), SV, 0,
6768                        false, false, 0);
6769  }
6770
6771  // __va_list_tag:
6772  //   gp_offset         (0 - 6 * 8)
6773  //   fp_offset         (48 - 48 + 8 * 16)
6774  //   overflow_arg_area (point to parameters coming in memory).
6775  //   reg_save_area
6776  SmallVector<SDValue, 8> MemOps;
6777  SDValue FIN = Op.getOperand(1);
6778  // Store gp_offset
6779  SDValue Store = DAG.getStore(Op.getOperand(0), dl,
6780                               DAG.getConstant(VarArgsGPOffset, MVT::i32),
6781                               FIN, SV, 0, false, false, 0);
6782  MemOps.push_back(Store);
6783
6784  // Store fp_offset
6785  FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(),
6786                    FIN, DAG.getIntPtrConstant(4));
6787  Store = DAG.getStore(Op.getOperand(0), dl,
6788                       DAG.getConstant(VarArgsFPOffset, MVT::i32),
6789                       FIN, SV, 0, false, false, 0);
6790  MemOps.push_back(Store);
6791
6792  // Store ptr to overflow_arg_area
6793  FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(),
6794                    FIN, DAG.getIntPtrConstant(4));
6795  SDValue OVFIN = DAG.getFrameIndex(VarArgsFrameIndex, getPointerTy());
6796  Store = DAG.getStore(Op.getOperand(0), dl, OVFIN, FIN, SV, 0,
6797                       false, false, 0);
6798  MemOps.push_back(Store);
6799
6800  // Store ptr to reg_save_area.
6801  FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(),
6802                    FIN, DAG.getIntPtrConstant(8));
6803  SDValue RSFIN = DAG.getFrameIndex(RegSaveFrameIndex, getPointerTy());
6804  Store = DAG.getStore(Op.getOperand(0), dl, RSFIN, FIN, SV, 0,
6805                       false, false, 0);
6806  MemOps.push_back(Store);
6807  return DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
6808                     &MemOps[0], MemOps.size());
6809}
6810
6811SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) {
6812  // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
6813  assert(Subtarget->is64Bit() && "This code only handles 64-bit va_arg!");
6814  SDValue Chain = Op.getOperand(0);
6815  SDValue SrcPtr = Op.getOperand(1);
6816  SDValue SrcSV = Op.getOperand(2);
6817
6818  llvm_report_error("VAArgInst is not yet implemented for x86-64!");
6819  return SDValue();
6820}
6821
6822SDValue X86TargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) {
6823  // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
6824  assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
6825  SDValue Chain = Op.getOperand(0);
6826  SDValue DstPtr = Op.getOperand(1);
6827  SDValue SrcPtr = Op.getOperand(2);
6828  const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
6829  const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
6830  DebugLoc dl = Op.getDebugLoc();
6831
6832  return DAG.getMemcpy(Chain, dl, DstPtr, SrcPtr,
6833                       DAG.getIntPtrConstant(24), 8, /*isVolatile*/false,
6834                       false, DstSV, 0, SrcSV, 0);
6835}
6836
6837SDValue
6838X86TargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) {
6839  DebugLoc dl = Op.getDebugLoc();
6840  unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
6841  switch (IntNo) {
6842  default: return SDValue();    // Don't custom lower most intrinsics.
6843  // Comparison intrinsics.
6844  case Intrinsic::x86_sse_comieq_ss:
6845  case Intrinsic::x86_sse_comilt_ss:
6846  case Intrinsic::x86_sse_comile_ss:
6847  case Intrinsic::x86_sse_comigt_ss:
6848  case Intrinsic::x86_sse_comige_ss:
6849  case Intrinsic::x86_sse_comineq_ss:
6850  case Intrinsic::x86_sse_ucomieq_ss:
6851  case Intrinsic::x86_sse_ucomilt_ss:
6852  case Intrinsic::x86_sse_ucomile_ss:
6853  case Intrinsic::x86_sse_ucomigt_ss:
6854  case Intrinsic::x86_sse_ucomige_ss:
6855  case Intrinsic::x86_sse_ucomineq_ss:
6856  case Intrinsic::x86_sse2_comieq_sd:
6857  case Intrinsic::x86_sse2_comilt_sd:
6858  case Intrinsic::x86_sse2_comile_sd:
6859  case Intrinsic::x86_sse2_comigt_sd:
6860  case Intrinsic::x86_sse2_comige_sd:
6861  case Intrinsic::x86_sse2_comineq_sd:
6862  case Intrinsic::x86_sse2_ucomieq_sd:
6863  case Intrinsic::x86_sse2_ucomilt_sd:
6864  case Intrinsic::x86_sse2_ucomile_sd:
6865  case Intrinsic::x86_sse2_ucomigt_sd:
6866  case Intrinsic::x86_sse2_ucomige_sd:
6867  case Intrinsic::x86_sse2_ucomineq_sd: {
6868    unsigned Opc = 0;
6869    ISD::CondCode CC = ISD::SETCC_INVALID;
6870    switch (IntNo) {
6871    default: break;
6872    case Intrinsic::x86_sse_comieq_ss:
6873    case Intrinsic::x86_sse2_comieq_sd:
6874      Opc = X86ISD::COMI;
6875      CC = ISD::SETEQ;
6876      break;
6877    case Intrinsic::x86_sse_comilt_ss:
6878    case Intrinsic::x86_sse2_comilt_sd:
6879      Opc = X86ISD::COMI;
6880      CC = ISD::SETLT;
6881      break;
6882    case Intrinsic::x86_sse_comile_ss:
6883    case Intrinsic::x86_sse2_comile_sd:
6884      Opc = X86ISD::COMI;
6885      CC = ISD::SETLE;
6886      break;
6887    case Intrinsic::x86_sse_comigt_ss:
6888    case Intrinsic::x86_sse2_comigt_sd:
6889      Opc = X86ISD::COMI;
6890      CC = ISD::SETGT;
6891      break;
6892    case Intrinsic::x86_sse_comige_ss:
6893    case Intrinsic::x86_sse2_comige_sd:
6894      Opc = X86ISD::COMI;
6895      CC = ISD::SETGE;
6896      break;
6897    case Intrinsic::x86_sse_comineq_ss:
6898    case Intrinsic::x86_sse2_comineq_sd:
6899      Opc = X86ISD::COMI;
6900      CC = ISD::SETNE;
6901      break;
6902    case Intrinsic::x86_sse_ucomieq_ss:
6903    case Intrinsic::x86_sse2_ucomieq_sd:
6904      Opc = X86ISD::UCOMI;
6905      CC = ISD::SETEQ;
6906      break;
6907    case Intrinsic::x86_sse_ucomilt_ss:
6908    case Intrinsic::x86_sse2_ucomilt_sd:
6909      Opc = X86ISD::UCOMI;
6910      CC = ISD::SETLT;
6911      break;
6912    case Intrinsic::x86_sse_ucomile_ss:
6913    case Intrinsic::x86_sse2_ucomile_sd:
6914      Opc = X86ISD::UCOMI;
6915      CC = ISD::SETLE;
6916      break;
6917    case Intrinsic::x86_sse_ucomigt_ss:
6918    case Intrinsic::x86_sse2_ucomigt_sd:
6919      Opc = X86ISD::UCOMI;
6920      CC = ISD::SETGT;
6921      break;
6922    case Intrinsic::x86_sse_ucomige_ss:
6923    case Intrinsic::x86_sse2_ucomige_sd:
6924      Opc = X86ISD::UCOMI;
6925      CC = ISD::SETGE;
6926      break;
6927    case Intrinsic::x86_sse_ucomineq_ss:
6928    case Intrinsic::x86_sse2_ucomineq_sd:
6929      Opc = X86ISD::UCOMI;
6930      CC = ISD::SETNE;
6931      break;
6932    }
6933
6934    SDValue LHS = Op.getOperand(1);
6935    SDValue RHS = Op.getOperand(2);
6936    unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
6937    assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
6938    SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS);
6939    SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
6940                                DAG.getConstant(X86CC, MVT::i8), Cond);
6941    return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
6942  }
6943  // ptest intrinsics. The intrinsic these come from are designed to return
6944  // an integer value, not just an instruction so lower it to the ptest
6945  // pattern and a setcc for the result.
6946  case Intrinsic::x86_sse41_ptestz:
6947  case Intrinsic::x86_sse41_ptestc:
6948  case Intrinsic::x86_sse41_ptestnzc:{
6949    unsigned X86CC = 0;
6950    switch (IntNo) {
6951    default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
6952    case Intrinsic::x86_sse41_ptestz:
6953      // ZF = 1
6954      X86CC = X86::COND_E;
6955      break;
6956    case Intrinsic::x86_sse41_ptestc:
6957      // CF = 1
6958      X86CC = X86::COND_B;
6959      break;
6960    case Intrinsic::x86_sse41_ptestnzc:
6961      // ZF and CF = 0
6962      X86CC = X86::COND_A;
6963      break;
6964    }
6965
6966    SDValue LHS = Op.getOperand(1);
6967    SDValue RHS = Op.getOperand(2);
6968    SDValue Test = DAG.getNode(X86ISD::PTEST, dl, MVT::i32, LHS, RHS);
6969    SDValue CC = DAG.getConstant(X86CC, MVT::i8);
6970    SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
6971    return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
6972  }
6973
6974  // Fix vector shift instructions where the last operand is a non-immediate
6975  // i32 value.
6976  case Intrinsic::x86_sse2_pslli_w:
6977  case Intrinsic::x86_sse2_pslli_d:
6978  case Intrinsic::x86_sse2_pslli_q:
6979  case Intrinsic::x86_sse2_psrli_w:
6980  case Intrinsic::x86_sse2_psrli_d:
6981  case Intrinsic::x86_sse2_psrli_q:
6982  case Intrinsic::x86_sse2_psrai_w:
6983  case Intrinsic::x86_sse2_psrai_d:
6984  case Intrinsic::x86_mmx_pslli_w:
6985  case Intrinsic::x86_mmx_pslli_d:
6986  case Intrinsic::x86_mmx_pslli_q:
6987  case Intrinsic::x86_mmx_psrli_w:
6988  case Intrinsic::x86_mmx_psrli_d:
6989  case Intrinsic::x86_mmx_psrli_q:
6990  case Intrinsic::x86_mmx_psrai_w:
6991  case Intrinsic::x86_mmx_psrai_d: {
6992    SDValue ShAmt = Op.getOperand(2);
6993    if (isa<ConstantSDNode>(ShAmt))
6994      return SDValue();
6995
6996    unsigned NewIntNo = 0;
6997    EVT ShAmtVT = MVT::v4i32;
6998    switch (IntNo) {
6999    case Intrinsic::x86_sse2_pslli_w:
7000      NewIntNo = Intrinsic::x86_sse2_psll_w;
7001      break;
7002    case Intrinsic::x86_sse2_pslli_d:
7003      NewIntNo = Intrinsic::x86_sse2_psll_d;
7004      break;
7005    case Intrinsic::x86_sse2_pslli_q:
7006      NewIntNo = Intrinsic::x86_sse2_psll_q;
7007      break;
7008    case Intrinsic::x86_sse2_psrli_w:
7009      NewIntNo = Intrinsic::x86_sse2_psrl_w;
7010      break;
7011    case Intrinsic::x86_sse2_psrli_d:
7012      NewIntNo = Intrinsic::x86_sse2_psrl_d;
7013      break;
7014    case Intrinsic::x86_sse2_psrli_q:
7015      NewIntNo = Intrinsic::x86_sse2_psrl_q;
7016      break;
7017    case Intrinsic::x86_sse2_psrai_w:
7018      NewIntNo = Intrinsic::x86_sse2_psra_w;
7019      break;
7020    case Intrinsic::x86_sse2_psrai_d:
7021      NewIntNo = Intrinsic::x86_sse2_psra_d;
7022      break;
7023    default: {
7024      ShAmtVT = MVT::v2i32;
7025      switch (IntNo) {
7026      case Intrinsic::x86_mmx_pslli_w:
7027        NewIntNo = Intrinsic::x86_mmx_psll_w;
7028        break;
7029      case Intrinsic::x86_mmx_pslli_d:
7030        NewIntNo = Intrinsic::x86_mmx_psll_d;
7031        break;
7032      case Intrinsic::x86_mmx_pslli_q:
7033        NewIntNo = Intrinsic::x86_mmx_psll_q;
7034        break;
7035      case Intrinsic::x86_mmx_psrli_w:
7036        NewIntNo = Intrinsic::x86_mmx_psrl_w;
7037        break;
7038      case Intrinsic::x86_mmx_psrli_d:
7039        NewIntNo = Intrinsic::x86_mmx_psrl_d;
7040        break;
7041      case Intrinsic::x86_mmx_psrli_q:
7042        NewIntNo = Intrinsic::x86_mmx_psrl_q;
7043        break;
7044      case Intrinsic::x86_mmx_psrai_w:
7045        NewIntNo = Intrinsic::x86_mmx_psra_w;
7046        break;
7047      case Intrinsic::x86_mmx_psrai_d:
7048        NewIntNo = Intrinsic::x86_mmx_psra_d;
7049        break;
7050      default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
7051      }
7052      break;
7053    }
7054    }
7055
7056    // The vector shift intrinsics with scalars uses 32b shift amounts but
7057    // the sse2/mmx shift instructions reads 64 bits. Set the upper 32 bits
7058    // to be zero.
7059    SDValue ShOps[4];
7060    ShOps[0] = ShAmt;
7061    ShOps[1] = DAG.getConstant(0, MVT::i32);
7062    if (ShAmtVT == MVT::v4i32) {
7063      ShOps[2] = DAG.getUNDEF(MVT::i32);
7064      ShOps[3] = DAG.getUNDEF(MVT::i32);
7065      ShAmt =  DAG.getNode(ISD::BUILD_VECTOR, dl, ShAmtVT, &ShOps[0], 4);
7066    } else {
7067      ShAmt =  DAG.getNode(ISD::BUILD_VECTOR, dl, ShAmtVT, &ShOps[0], 2);
7068    }
7069
7070    EVT VT = Op.getValueType();
7071    ShAmt = DAG.getNode(ISD::BIT_CONVERT, dl, VT, ShAmt);
7072    return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
7073                       DAG.getConstant(NewIntNo, MVT::i32),
7074                       Op.getOperand(1), ShAmt);
7075  }
7076  }
7077}
7078
7079SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) {
7080  unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
7081  DebugLoc dl = Op.getDebugLoc();
7082
7083  if (Depth > 0) {
7084    SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
7085    SDValue Offset =
7086      DAG.getConstant(TD->getPointerSize(),
7087                      Subtarget->is64Bit() ? MVT::i64 : MVT::i32);
7088    return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
7089                       DAG.getNode(ISD::ADD, dl, getPointerTy(),
7090                                   FrameAddr, Offset),
7091                       NULL, 0, false, false, 0);
7092  }
7093
7094  // Just load the return address.
7095  SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
7096  return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
7097                     RetAddrFI, NULL, 0, false, false, 0);
7098}
7099
7100SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) {
7101  MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7102  MFI->setFrameAddressIsTaken(true);
7103  EVT VT = Op.getValueType();
7104  DebugLoc dl = Op.getDebugLoc();  // FIXME probably not meaningful
7105  unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
7106  unsigned FrameReg = Subtarget->is64Bit() ? X86::RBP : X86::EBP;
7107  SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
7108  while (Depth--)
7109    FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr, NULL, 0,
7110                            false, false, 0);
7111  return FrameAddr;
7112}
7113
7114SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
7115                                                     SelectionDAG &DAG) {
7116  return DAG.getIntPtrConstant(2*TD->getPointerSize());
7117}
7118
7119SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG)
7120{
7121  MachineFunction &MF = DAG.getMachineFunction();
7122  SDValue Chain     = Op.getOperand(0);
7123  SDValue Offset    = Op.getOperand(1);
7124  SDValue Handler   = Op.getOperand(2);
7125  DebugLoc dl       = Op.getDebugLoc();
7126
7127  SDValue Frame = DAG.getRegister(Subtarget->is64Bit() ? X86::RBP : X86::EBP,
7128                                  getPointerTy());
7129  unsigned StoreAddrReg = (Subtarget->is64Bit() ? X86::RCX : X86::ECX);
7130
7131  SDValue StoreAddr = DAG.getNode(ISD::SUB, dl, getPointerTy(), Frame,
7132                                  DAG.getIntPtrConstant(-TD->getPointerSize()));
7133  StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), StoreAddr, Offset);
7134  Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, NULL, 0, false, false, 0);
7135  Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
7136  MF.getRegInfo().addLiveOut(StoreAddrReg);
7137
7138  return DAG.getNode(X86ISD::EH_RETURN, dl,
7139                     MVT::Other,
7140                     Chain, DAG.getRegister(StoreAddrReg, getPointerTy()));
7141}
7142
7143SDValue X86TargetLowering::LowerTRAMPOLINE(SDValue Op,
7144                                             SelectionDAG &DAG) {
7145  SDValue Root = Op.getOperand(0);
7146  SDValue Trmp = Op.getOperand(1); // trampoline
7147  SDValue FPtr = Op.getOperand(2); // nested function
7148  SDValue Nest = Op.getOperand(3); // 'nest' parameter value
7149  DebugLoc dl  = Op.getDebugLoc();
7150
7151  const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
7152
7153  if (Subtarget->is64Bit()) {
7154    SDValue OutChains[6];
7155
7156    // Large code-model.
7157    const unsigned char JMP64r  = 0xFF; // 64-bit jmp through register opcode.
7158    const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
7159
7160    const unsigned char N86R10 = RegInfo->getX86RegNum(X86::R10);
7161    const unsigned char N86R11 = RegInfo->getX86RegNum(X86::R11);
7162
7163    const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
7164
7165    // Load the pointer to the nested function into R11.
7166    unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
7167    SDValue Addr = Trmp;
7168    OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
7169                                Addr, TrmpAddr, 0, false, false, 0);
7170
7171    Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
7172                       DAG.getConstant(2, MVT::i64));
7173    OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr, TrmpAddr, 2,
7174                                false, false, 2);
7175
7176    // Load the 'nest' parameter value into R10.
7177    // R10 is specified in X86CallingConv.td
7178    OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
7179    Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
7180                       DAG.getConstant(10, MVT::i64));
7181    OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
7182                                Addr, TrmpAddr, 10, false, false, 0);
7183
7184    Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
7185                       DAG.getConstant(12, MVT::i64));
7186    OutChains[3] = DAG.getStore(Root, dl, Nest, Addr, TrmpAddr, 12,
7187                                false, false, 2);
7188
7189    // Jump to the nested function.
7190    OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
7191    Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
7192                       DAG.getConstant(20, MVT::i64));
7193    OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
7194                                Addr, TrmpAddr, 20, false, false, 0);
7195
7196    unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
7197    Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
7198                       DAG.getConstant(22, MVT::i64));
7199    OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
7200                                TrmpAddr, 22, false, false, 0);
7201
7202    SDValue Ops[] =
7203      { Trmp, DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 6) };
7204    return DAG.getMergeValues(Ops, 2, dl);
7205  } else {
7206    const Function *Func =
7207      cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
7208    CallingConv::ID CC = Func->getCallingConv();
7209    unsigned NestReg;
7210
7211    switch (CC) {
7212    default:
7213      llvm_unreachable("Unsupported calling convention");
7214    case CallingConv::C:
7215    case CallingConv::X86_StdCall: {
7216      // Pass 'nest' parameter in ECX.
7217      // Must be kept in sync with X86CallingConv.td
7218      NestReg = X86::ECX;
7219
7220      // Check that ECX wasn't needed by an 'inreg' parameter.
7221      const FunctionType *FTy = Func->getFunctionType();
7222      const AttrListPtr &Attrs = Func->getAttributes();
7223
7224      if (!Attrs.isEmpty() && !Func->isVarArg()) {
7225        unsigned InRegCount = 0;
7226        unsigned Idx = 1;
7227
7228        for (FunctionType::param_iterator I = FTy->param_begin(),
7229             E = FTy->param_end(); I != E; ++I, ++Idx)
7230          if (Attrs.paramHasAttr(Idx, Attribute::InReg))
7231            // FIXME: should only count parameters that are lowered to integers.
7232            InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
7233
7234        if (InRegCount > 2) {
7235          llvm_report_error("Nest register in use - reduce number of inreg parameters!");
7236        }
7237      }
7238      break;
7239    }
7240    case CallingConv::X86_FastCall:
7241    case CallingConv::Fast:
7242      // Pass 'nest' parameter in EAX.
7243      // Must be kept in sync with X86CallingConv.td
7244      NestReg = X86::EAX;
7245      break;
7246    }
7247
7248    SDValue OutChains[4];
7249    SDValue Addr, Disp;
7250
7251    Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
7252                       DAG.getConstant(10, MVT::i32));
7253    Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
7254
7255    // This is storing the opcode for MOV32ri.
7256    const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
7257    const unsigned char N86Reg = RegInfo->getX86RegNum(NestReg);
7258    OutChains[0] = DAG.getStore(Root, dl,
7259                                DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
7260                                Trmp, TrmpAddr, 0, false, false, 0);
7261
7262    Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
7263                       DAG.getConstant(1, MVT::i32));
7264    OutChains[1] = DAG.getStore(Root, dl, Nest, Addr, TrmpAddr, 1,
7265                                false, false, 1);
7266
7267    const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
7268    Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
7269                       DAG.getConstant(5, MVT::i32));
7270    OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
7271                                TrmpAddr, 5, false, false, 1);
7272
7273    Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
7274                       DAG.getConstant(6, MVT::i32));
7275    OutChains[3] = DAG.getStore(Root, dl, Disp, Addr, TrmpAddr, 6,
7276                                false, false, 1);
7277
7278    SDValue Ops[] =
7279      { Trmp, DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 4) };
7280    return DAG.getMergeValues(Ops, 2, dl);
7281  }
7282}
7283
7284SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op, SelectionDAG &DAG) {
7285  /*
7286   The rounding mode is in bits 11:10 of FPSR, and has the following
7287   settings:
7288     00 Round to nearest
7289     01 Round to -inf
7290     10 Round to +inf
7291     11 Round to 0
7292
7293  FLT_ROUNDS, on the other hand, expects the following:
7294    -1 Undefined
7295     0 Round to 0
7296     1 Round to nearest
7297     2 Round to +inf
7298     3 Round to -inf
7299
7300  To perform the conversion, we do:
7301    (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
7302  */
7303
7304  MachineFunction &MF = DAG.getMachineFunction();
7305  const TargetMachine &TM = MF.getTarget();
7306  const TargetFrameInfo &TFI = *TM.getFrameInfo();
7307  unsigned StackAlignment = TFI.getStackAlignment();
7308  EVT VT = Op.getValueType();
7309  DebugLoc dl = Op.getDebugLoc();
7310
7311  // Save FP Control Word to stack slot
7312  int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
7313  SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7314
7315  SDValue Chain = DAG.getNode(X86ISD::FNSTCW16m, dl, MVT::Other,
7316                              DAG.getEntryNode(), StackSlot);
7317
7318  // Load FP Control Word from stack slot
7319  SDValue CWD = DAG.getLoad(MVT::i16, dl, Chain, StackSlot, NULL, 0,
7320                            false, false, 0);
7321
7322  // Transform as necessary
7323  SDValue CWD1 =
7324    DAG.getNode(ISD::SRL, dl, MVT::i16,
7325                DAG.getNode(ISD::AND, dl, MVT::i16,
7326                            CWD, DAG.getConstant(0x800, MVT::i16)),
7327                DAG.getConstant(11, MVT::i8));
7328  SDValue CWD2 =
7329    DAG.getNode(ISD::SRL, dl, MVT::i16,
7330                DAG.getNode(ISD::AND, dl, MVT::i16,
7331                            CWD, DAG.getConstant(0x400, MVT::i16)),
7332                DAG.getConstant(9, MVT::i8));
7333
7334  SDValue RetVal =
7335    DAG.getNode(ISD::AND, dl, MVT::i16,
7336                DAG.getNode(ISD::ADD, dl, MVT::i16,
7337                            DAG.getNode(ISD::OR, dl, MVT::i16, CWD1, CWD2),
7338                            DAG.getConstant(1, MVT::i16)),
7339                DAG.getConstant(3, MVT::i16));
7340
7341
7342  return DAG.getNode((VT.getSizeInBits() < 16 ?
7343                      ISD::TRUNCATE : ISD::ZERO_EXTEND), dl, VT, RetVal);
7344}
7345
7346SDValue X86TargetLowering::LowerCTLZ(SDValue Op, SelectionDAG &DAG) {
7347  EVT VT = Op.getValueType();
7348  EVT OpVT = VT;
7349  unsigned NumBits = VT.getSizeInBits();
7350  DebugLoc dl = Op.getDebugLoc();
7351
7352  Op = Op.getOperand(0);
7353  if (VT == MVT::i8) {
7354    // Zero extend to i32 since there is not an i8 bsr.
7355    OpVT = MVT::i32;
7356    Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
7357  }
7358
7359  // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
7360  SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
7361  Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
7362
7363  // If src is zero (i.e. bsr sets ZF), returns NumBits.
7364  SDValue Ops[] = {
7365    Op,
7366    DAG.getConstant(NumBits+NumBits-1, OpVT),
7367    DAG.getConstant(X86::COND_E, MVT::i8),
7368    Op.getValue(1)
7369  };
7370  Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
7371
7372  // Finally xor with NumBits-1.
7373  Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
7374
7375  if (VT == MVT::i8)
7376    Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
7377  return Op;
7378}
7379
7380SDValue X86TargetLowering::LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
7381  EVT VT = Op.getValueType();
7382  EVT OpVT = VT;
7383  unsigned NumBits = VT.getSizeInBits();
7384  DebugLoc dl = Op.getDebugLoc();
7385
7386  Op = Op.getOperand(0);
7387  if (VT == MVT::i8) {
7388    OpVT = MVT::i32;
7389    Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
7390  }
7391
7392  // Issue a bsf (scan bits forward) which also sets EFLAGS.
7393  SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
7394  Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
7395
7396  // If src is zero (i.e. bsf sets ZF), returns NumBits.
7397  SDValue Ops[] = {
7398    Op,
7399    DAG.getConstant(NumBits, OpVT),
7400    DAG.getConstant(X86::COND_E, MVT::i8),
7401    Op.getValue(1)
7402  };
7403  Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
7404
7405  if (VT == MVT::i8)
7406    Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
7407  return Op;
7408}
7409
7410SDValue X86TargetLowering::LowerMUL_V2I64(SDValue Op, SelectionDAG &DAG) {
7411  EVT VT = Op.getValueType();
7412  assert(VT == MVT::v2i64 && "Only know how to lower V2I64 multiply");
7413  DebugLoc dl = Op.getDebugLoc();
7414
7415  //  ulong2 Ahi = __builtin_ia32_psrlqi128( a, 32);
7416  //  ulong2 Bhi = __builtin_ia32_psrlqi128( b, 32);
7417  //  ulong2 AloBlo = __builtin_ia32_pmuludq128( a, b );
7418  //  ulong2 AloBhi = __builtin_ia32_pmuludq128( a, Bhi );
7419  //  ulong2 AhiBlo = __builtin_ia32_pmuludq128( Ahi, b );
7420  //
7421  //  AloBhi = __builtin_ia32_psllqi128( AloBhi, 32 );
7422  //  AhiBlo = __builtin_ia32_psllqi128( AhiBlo, 32 );
7423  //  return AloBlo + AloBhi + AhiBlo;
7424
7425  SDValue A = Op.getOperand(0);
7426  SDValue B = Op.getOperand(1);
7427
7428  SDValue Ahi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
7429                       DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
7430                       A, DAG.getConstant(32, MVT::i32));
7431  SDValue Bhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
7432                       DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
7433                       B, DAG.getConstant(32, MVT::i32));
7434  SDValue AloBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
7435                       DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
7436                       A, B);
7437  SDValue AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
7438                       DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
7439                       A, Bhi);
7440  SDValue AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
7441                       DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
7442                       Ahi, B);
7443  AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
7444                       DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
7445                       AloBhi, DAG.getConstant(32, MVT::i32));
7446  AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
7447                       DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
7448                       AhiBlo, DAG.getConstant(32, MVT::i32));
7449  SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
7450  Res = DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
7451  return Res;
7452}
7453
7454
7455SDValue X86TargetLowering::LowerXALUO(SDValue Op, SelectionDAG &DAG) {
7456  // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
7457  // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
7458  // looks for this combo and may remove the "setcc" instruction if the "setcc"
7459  // has only one use.
7460  SDNode *N = Op.getNode();
7461  SDValue LHS = N->getOperand(0);
7462  SDValue RHS = N->getOperand(1);
7463  unsigned BaseOp = 0;
7464  unsigned Cond = 0;
7465  DebugLoc dl = Op.getDebugLoc();
7466
7467  switch (Op.getOpcode()) {
7468  default: llvm_unreachable("Unknown ovf instruction!");
7469  case ISD::SADDO:
7470    // A subtract of one will be selected as a INC. Note that INC doesn't
7471    // set CF, so we can't do this for UADDO.
7472    if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op))
7473      if (C->getAPIntValue() == 1) {
7474        BaseOp = X86ISD::INC;
7475        Cond = X86::COND_O;
7476        break;
7477      }
7478    BaseOp = X86ISD::ADD;
7479    Cond = X86::COND_O;
7480    break;
7481  case ISD::UADDO:
7482    BaseOp = X86ISD::ADD;
7483    Cond = X86::COND_B;
7484    break;
7485  case ISD::SSUBO:
7486    // A subtract of one will be selected as a DEC. Note that DEC doesn't
7487    // set CF, so we can't do this for USUBO.
7488    if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op))
7489      if (C->getAPIntValue() == 1) {
7490        BaseOp = X86ISD::DEC;
7491        Cond = X86::COND_O;
7492        break;
7493      }
7494    BaseOp = X86ISD::SUB;
7495    Cond = X86::COND_O;
7496    break;
7497  case ISD::USUBO:
7498    BaseOp = X86ISD::SUB;
7499    Cond = X86::COND_B;
7500    break;
7501  case ISD::SMULO:
7502    BaseOp = X86ISD::SMUL;
7503    Cond = X86::COND_O;
7504    break;
7505  case ISD::UMULO:
7506    BaseOp = X86ISD::UMUL;
7507    Cond = X86::COND_B;
7508    break;
7509  }
7510
7511  // Also sets EFLAGS.
7512  SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
7513  SDValue Sum = DAG.getNode(BaseOp, dl, VTs, LHS, RHS);
7514
7515  SDValue SetCC =
7516    DAG.getNode(X86ISD::SETCC, dl, N->getValueType(1),
7517                DAG.getConstant(Cond, MVT::i32), SDValue(Sum.getNode(), 1));
7518
7519  DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), SetCC);
7520  return Sum;
7521}
7522
7523SDValue X86TargetLowering::LowerCMP_SWAP(SDValue Op, SelectionDAG &DAG) {
7524  EVT T = Op.getValueType();
7525  DebugLoc dl = Op.getDebugLoc();
7526  unsigned Reg = 0;
7527  unsigned size = 0;
7528  switch(T.getSimpleVT().SimpleTy) {
7529  default:
7530    assert(false && "Invalid value type!");
7531  case MVT::i8:  Reg = X86::AL;  size = 1; break;
7532  case MVT::i16: Reg = X86::AX;  size = 2; break;
7533  case MVT::i32: Reg = X86::EAX; size = 4; break;
7534  case MVT::i64:
7535    assert(Subtarget->is64Bit() && "Node not type legal!");
7536    Reg = X86::RAX; size = 8;
7537    break;
7538  }
7539  SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), dl, Reg,
7540                                    Op.getOperand(2), SDValue());
7541  SDValue Ops[] = { cpIn.getValue(0),
7542                    Op.getOperand(1),
7543                    Op.getOperand(3),
7544                    DAG.getTargetConstant(size, MVT::i8),
7545                    cpIn.getValue(1) };
7546  SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
7547  SDValue Result = DAG.getNode(X86ISD::LCMPXCHG_DAG, dl, Tys, Ops, 5);
7548  SDValue cpOut =
7549    DAG.getCopyFromReg(Result.getValue(0), dl, Reg, T, Result.getValue(1));
7550  return cpOut;
7551}
7552
7553SDValue X86TargetLowering::LowerREADCYCLECOUNTER(SDValue Op,
7554                                                 SelectionDAG &DAG) {
7555  assert(Subtarget->is64Bit() && "Result not type legalized?");
7556  SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
7557  SDValue TheChain = Op.getOperand(0);
7558  DebugLoc dl = Op.getDebugLoc();
7559  SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
7560  SDValue rax = DAG.getCopyFromReg(rd, dl, X86::RAX, MVT::i64, rd.getValue(1));
7561  SDValue rdx = DAG.getCopyFromReg(rax.getValue(1), dl, X86::RDX, MVT::i64,
7562                                   rax.getValue(2));
7563  SDValue Tmp = DAG.getNode(ISD::SHL, dl, MVT::i64, rdx,
7564                            DAG.getConstant(32, MVT::i8));
7565  SDValue Ops[] = {
7566    DAG.getNode(ISD::OR, dl, MVT::i64, rax, Tmp),
7567    rdx.getValue(1)
7568  };
7569  return DAG.getMergeValues(Ops, 2, dl);
7570}
7571
7572SDValue X86TargetLowering::LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) {
7573  SDNode *Node = Op.getNode();
7574  DebugLoc dl = Node->getDebugLoc();
7575  EVT T = Node->getValueType(0);
7576  SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
7577                              DAG.getConstant(0, T), Node->getOperand(2));
7578  return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
7579                       cast<AtomicSDNode>(Node)->getMemoryVT(),
7580                       Node->getOperand(0),
7581                       Node->getOperand(1), negOp,
7582                       cast<AtomicSDNode>(Node)->getSrcValue(),
7583                       cast<AtomicSDNode>(Node)->getAlignment());
7584}
7585
7586/// LowerOperation - Provide custom lowering hooks for some operations.
7587///
7588SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) {
7589  switch (Op.getOpcode()) {
7590  default: llvm_unreachable("Should not custom lower this!");
7591  case ISD::ATOMIC_CMP_SWAP:    return LowerCMP_SWAP(Op,DAG);
7592  case ISD::ATOMIC_LOAD_SUB:    return LowerLOAD_SUB(Op,DAG);
7593  case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
7594  case ISD::CONCAT_VECTORS:     return LowerCONCAT_VECTORS(Op, DAG);
7595  case ISD::VECTOR_SHUFFLE:     return LowerVECTOR_SHUFFLE(Op, DAG);
7596  case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
7597  case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
7598  case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
7599  case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
7600  case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
7601  case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
7602  case ISD::ExternalSymbol:     return LowerExternalSymbol(Op, DAG);
7603  case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
7604  case ISD::SHL_PARTS:
7605  case ISD::SRA_PARTS:
7606  case ISD::SRL_PARTS:          return LowerShift(Op, DAG);
7607  case ISD::SINT_TO_FP:         return LowerSINT_TO_FP(Op, DAG);
7608  case ISD::UINT_TO_FP:         return LowerUINT_TO_FP(Op, DAG);
7609  case ISD::FP_TO_SINT:         return LowerFP_TO_SINT(Op, DAG);
7610  case ISD::FP_TO_UINT:         return LowerFP_TO_UINT(Op, DAG);
7611  case ISD::FABS:               return LowerFABS(Op, DAG);
7612  case ISD::FNEG:               return LowerFNEG(Op, DAG);
7613  case ISD::FCOPYSIGN:          return LowerFCOPYSIGN(Op, DAG);
7614  case ISD::SETCC:              return LowerSETCC(Op, DAG);
7615  case ISD::VSETCC:             return LowerVSETCC(Op, DAG);
7616  case ISD::SELECT:             return LowerSELECT(Op, DAG);
7617  case ISD::BRCOND:             return LowerBRCOND(Op, DAG);
7618  case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
7619  case ISD::VASTART:            return LowerVASTART(Op, DAG);
7620  case ISD::VAARG:              return LowerVAARG(Op, DAG);
7621  case ISD::VACOPY:             return LowerVACOPY(Op, DAG);
7622  case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
7623  case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
7624  case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
7625  case ISD::FRAME_TO_ARGS_OFFSET:
7626                                return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
7627  case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
7628  case ISD::EH_RETURN:          return LowerEH_RETURN(Op, DAG);
7629  case ISD::TRAMPOLINE:         return LowerTRAMPOLINE(Op, DAG);
7630  case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
7631  case ISD::CTLZ:               return LowerCTLZ(Op, DAG);
7632  case ISD::CTTZ:               return LowerCTTZ(Op, DAG);
7633  case ISD::MUL:                return LowerMUL_V2I64(Op, DAG);
7634  case ISD::SADDO:
7635  case ISD::UADDO:
7636  case ISD::SSUBO:
7637  case ISD::USUBO:
7638  case ISD::SMULO:
7639  case ISD::UMULO:              return LowerXALUO(Op, DAG);
7640  case ISD::READCYCLECOUNTER:   return LowerREADCYCLECOUNTER(Op, DAG);
7641  }
7642}
7643
7644void X86TargetLowering::
7645ReplaceATOMIC_BINARY_64(SDNode *Node, SmallVectorImpl<SDValue>&Results,
7646                        SelectionDAG &DAG, unsigned NewOp) {
7647  EVT T = Node->getValueType(0);
7648  DebugLoc dl = Node->getDebugLoc();
7649  assert (T == MVT::i64 && "Only know how to expand i64 atomics");
7650
7651  SDValue Chain = Node->getOperand(0);
7652  SDValue In1 = Node->getOperand(1);
7653  SDValue In2L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
7654                             Node->getOperand(2), DAG.getIntPtrConstant(0));
7655  SDValue In2H = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
7656                             Node->getOperand(2), DAG.getIntPtrConstant(1));
7657  SDValue Ops[] = { Chain, In1, In2L, In2H };
7658  SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
7659  SDValue Result =
7660    DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops, 4, MVT::i64,
7661                            cast<MemSDNode>(Node)->getMemOperand());
7662  SDValue OpsF[] = { Result.getValue(0), Result.getValue(1)};
7663  Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
7664  Results.push_back(Result.getValue(2));
7665}
7666
7667/// ReplaceNodeResults - Replace a node with an illegal result type
7668/// with a new node built out of custom code.
7669void X86TargetLowering::ReplaceNodeResults(SDNode *N,
7670                                           SmallVectorImpl<SDValue>&Results,
7671                                           SelectionDAG &DAG) {
7672  DebugLoc dl = N->getDebugLoc();
7673  switch (N->getOpcode()) {
7674  default:
7675    assert(false && "Do not know how to custom type legalize this operation!");
7676    return;
7677  case ISD::FP_TO_SINT: {
7678    std::pair<SDValue,SDValue> Vals =
7679        FP_TO_INTHelper(SDValue(N, 0), DAG, true);
7680    SDValue FIST = Vals.first, StackSlot = Vals.second;
7681    if (FIST.getNode() != 0) {
7682      EVT VT = N->getValueType(0);
7683      // Return a load from the stack slot.
7684      Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot, NULL, 0,
7685                                    false, false, 0));
7686    }
7687    return;
7688  }
7689  case ISD::READCYCLECOUNTER: {
7690    SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
7691    SDValue TheChain = N->getOperand(0);
7692    SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
7693    SDValue eax = DAG.getCopyFromReg(rd, dl, X86::EAX, MVT::i32,
7694                                     rd.getValue(1));
7695    SDValue edx = DAG.getCopyFromReg(eax.getValue(1), dl, X86::EDX, MVT::i32,
7696                                     eax.getValue(2));
7697    // Use a buildpair to merge the two 32-bit values into a 64-bit one.
7698    SDValue Ops[] = { eax, edx };
7699    Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Ops, 2));
7700    Results.push_back(edx.getValue(1));
7701    return;
7702  }
7703  case ISD::ATOMIC_CMP_SWAP: {
7704    EVT T = N->getValueType(0);
7705    assert (T == MVT::i64 && "Only know how to expand i64 Cmp and Swap");
7706    SDValue cpInL, cpInH;
7707    cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(2),
7708                        DAG.getConstant(0, MVT::i32));
7709    cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(2),
7710                        DAG.getConstant(1, MVT::i32));
7711    cpInL = DAG.getCopyToReg(N->getOperand(0), dl, X86::EAX, cpInL, SDValue());
7712    cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl, X86::EDX, cpInH,
7713                             cpInL.getValue(1));
7714    SDValue swapInL, swapInH;
7715    swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(3),
7716                          DAG.getConstant(0, MVT::i32));
7717    swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(3),
7718                          DAG.getConstant(1, MVT::i32));
7719    swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl, X86::EBX, swapInL,
7720                               cpInH.getValue(1));
7721    swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl, X86::ECX, swapInH,
7722                               swapInL.getValue(1));
7723    SDValue Ops[] = { swapInH.getValue(0),
7724                      N->getOperand(1),
7725                      swapInH.getValue(1) };
7726    SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
7727    SDValue Result = DAG.getNode(X86ISD::LCMPXCHG8_DAG, dl, Tys, Ops, 3);
7728    SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl, X86::EAX,
7729                                        MVT::i32, Result.getValue(1));
7730    SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl, X86::EDX,
7731                                        MVT::i32, cpOutL.getValue(2));
7732    SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
7733    Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
7734    Results.push_back(cpOutH.getValue(1));
7735    return;
7736  }
7737  case ISD::ATOMIC_LOAD_ADD:
7738    ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMADD64_DAG);
7739    return;
7740  case ISD::ATOMIC_LOAD_AND:
7741    ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMAND64_DAG);
7742    return;
7743  case ISD::ATOMIC_LOAD_NAND:
7744    ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMNAND64_DAG);
7745    return;
7746  case ISD::ATOMIC_LOAD_OR:
7747    ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMOR64_DAG);
7748    return;
7749  case ISD::ATOMIC_LOAD_SUB:
7750    ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSUB64_DAG);
7751    return;
7752  case ISD::ATOMIC_LOAD_XOR:
7753    ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMXOR64_DAG);
7754    return;
7755  case ISD::ATOMIC_SWAP:
7756    ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSWAP64_DAG);
7757    return;
7758  }
7759}
7760
7761const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
7762  switch (Opcode) {
7763  default: return NULL;
7764  case X86ISD::BSF:                return "X86ISD::BSF";
7765  case X86ISD::BSR:                return "X86ISD::BSR";
7766  case X86ISD::SHLD:               return "X86ISD::SHLD";
7767  case X86ISD::SHRD:               return "X86ISD::SHRD";
7768  case X86ISD::FAND:               return "X86ISD::FAND";
7769  case X86ISD::FOR:                return "X86ISD::FOR";
7770  case X86ISD::FXOR:               return "X86ISD::FXOR";
7771  case X86ISD::FSRL:               return "X86ISD::FSRL";
7772  case X86ISD::FILD:               return "X86ISD::FILD";
7773  case X86ISD::FILD_FLAG:          return "X86ISD::FILD_FLAG";
7774  case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
7775  case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
7776  case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
7777  case X86ISD::FLD:                return "X86ISD::FLD";
7778  case X86ISD::FST:                return "X86ISD::FST";
7779  case X86ISD::CALL:               return "X86ISD::CALL";
7780  case X86ISD::RDTSC_DAG:          return "X86ISD::RDTSC_DAG";
7781  case X86ISD::BT:                 return "X86ISD::BT";
7782  case X86ISD::CMP:                return "X86ISD::CMP";
7783  case X86ISD::COMI:               return "X86ISD::COMI";
7784  case X86ISD::UCOMI:              return "X86ISD::UCOMI";
7785  case X86ISD::SETCC:              return "X86ISD::SETCC";
7786  case X86ISD::SETCC_CARRY:        return "X86ISD::SETCC_CARRY";
7787  case X86ISD::CMOV:               return "X86ISD::CMOV";
7788  case X86ISD::BRCOND:             return "X86ISD::BRCOND";
7789  case X86ISD::RET_FLAG:           return "X86ISD::RET_FLAG";
7790  case X86ISD::REP_STOS:           return "X86ISD::REP_STOS";
7791  case X86ISD::REP_MOVS:           return "X86ISD::REP_MOVS";
7792  case X86ISD::GlobalBaseReg:      return "X86ISD::GlobalBaseReg";
7793  case X86ISD::Wrapper:            return "X86ISD::Wrapper";
7794  case X86ISD::WrapperRIP:         return "X86ISD::WrapperRIP";
7795  case X86ISD::PEXTRB:             return "X86ISD::PEXTRB";
7796  case X86ISD::PEXTRW:             return "X86ISD::PEXTRW";
7797  case X86ISD::INSERTPS:           return "X86ISD::INSERTPS";
7798  case X86ISD::PINSRB:             return "X86ISD::PINSRB";
7799  case X86ISD::PINSRW:             return "X86ISD::PINSRW";
7800  case X86ISD::MMX_PINSRW:         return "X86ISD::MMX_PINSRW";
7801  case X86ISD::PSHUFB:             return "X86ISD::PSHUFB";
7802  case X86ISD::FMAX:               return "X86ISD::FMAX";
7803  case X86ISD::FMIN:               return "X86ISD::FMIN";
7804  case X86ISD::FRSQRT:             return "X86ISD::FRSQRT";
7805  case X86ISD::FRCP:               return "X86ISD::FRCP";
7806  case X86ISD::TLSADDR:            return "X86ISD::TLSADDR";
7807  case X86ISD::SegmentBaseAddress: return "X86ISD::SegmentBaseAddress";
7808  case X86ISD::EH_RETURN:          return "X86ISD::EH_RETURN";
7809  case X86ISD::TC_RETURN:          return "X86ISD::TC_RETURN";
7810  case X86ISD::FNSTCW16m:          return "X86ISD::FNSTCW16m";
7811  case X86ISD::LCMPXCHG_DAG:       return "X86ISD::LCMPXCHG_DAG";
7812  case X86ISD::LCMPXCHG8_DAG:      return "X86ISD::LCMPXCHG8_DAG";
7813  case X86ISD::ATOMADD64_DAG:      return "X86ISD::ATOMADD64_DAG";
7814  case X86ISD::ATOMSUB64_DAG:      return "X86ISD::ATOMSUB64_DAG";
7815  case X86ISD::ATOMOR64_DAG:       return "X86ISD::ATOMOR64_DAG";
7816  case X86ISD::ATOMXOR64_DAG:      return "X86ISD::ATOMXOR64_DAG";
7817  case X86ISD::ATOMAND64_DAG:      return "X86ISD::ATOMAND64_DAG";
7818  case X86ISD::ATOMNAND64_DAG:     return "X86ISD::ATOMNAND64_DAG";
7819  case X86ISD::VZEXT_MOVL:         return "X86ISD::VZEXT_MOVL";
7820  case X86ISD::VZEXT_LOAD:         return "X86ISD::VZEXT_LOAD";
7821  case X86ISD::VSHL:               return "X86ISD::VSHL";
7822  case X86ISD::VSRL:               return "X86ISD::VSRL";
7823  case X86ISD::CMPPD:              return "X86ISD::CMPPD";
7824  case X86ISD::CMPPS:              return "X86ISD::CMPPS";
7825  case X86ISD::PCMPEQB:            return "X86ISD::PCMPEQB";
7826  case X86ISD::PCMPEQW:            return "X86ISD::PCMPEQW";
7827  case X86ISD::PCMPEQD:            return "X86ISD::PCMPEQD";
7828  case X86ISD::PCMPEQQ:            return "X86ISD::PCMPEQQ";
7829  case X86ISD::PCMPGTB:            return "X86ISD::PCMPGTB";
7830  case X86ISD::PCMPGTW:            return "X86ISD::PCMPGTW";
7831  case X86ISD::PCMPGTD:            return "X86ISD::PCMPGTD";
7832  case X86ISD::PCMPGTQ:            return "X86ISD::PCMPGTQ";
7833  case X86ISD::ADD:                return "X86ISD::ADD";
7834  case X86ISD::SUB:                return "X86ISD::SUB";
7835  case X86ISD::SMUL:               return "X86ISD::SMUL";
7836  case X86ISD::UMUL:               return "X86ISD::UMUL";
7837  case X86ISD::INC:                return "X86ISD::INC";
7838  case X86ISD::DEC:                return "X86ISD::DEC";
7839  case X86ISD::OR:                 return "X86ISD::OR";
7840  case X86ISD::XOR:                return "X86ISD::XOR";
7841  case X86ISD::AND:                return "X86ISD::AND";
7842  case X86ISD::MUL_IMM:            return "X86ISD::MUL_IMM";
7843  case X86ISD::PTEST:              return "X86ISD::PTEST";
7844  case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
7845  case X86ISD::MINGW_ALLOCA:       return "X86ISD::MINGW_ALLOCA";
7846  }
7847}
7848
7849// isLegalAddressingMode - Return true if the addressing mode represented
7850// by AM is legal for this target, for a load/store of the specified type.
7851bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
7852                                              const Type *Ty) const {
7853  // X86 supports extremely general addressing modes.
7854  CodeModel::Model M = getTargetMachine().getCodeModel();
7855
7856  // X86 allows a sign-extended 32-bit immediate field as a displacement.
7857  if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != NULL))
7858    return false;
7859
7860  if (AM.BaseGV) {
7861    unsigned GVFlags =
7862      Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
7863
7864    // If a reference to this global requires an extra load, we can't fold it.
7865    if (isGlobalStubReference(GVFlags))
7866      return false;
7867
7868    // If BaseGV requires a register for the PIC base, we cannot also have a
7869    // BaseReg specified.
7870    if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
7871      return false;
7872
7873    // If lower 4G is not available, then we must use rip-relative addressing.
7874    if (Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
7875      return false;
7876  }
7877
7878  switch (AM.Scale) {
7879  case 0:
7880  case 1:
7881  case 2:
7882  case 4:
7883  case 8:
7884    // These scales always work.
7885    break;
7886  case 3:
7887  case 5:
7888  case 9:
7889    // These scales are formed with basereg+scalereg.  Only accept if there is
7890    // no basereg yet.
7891    if (AM.HasBaseReg)
7892      return false;
7893    break;
7894  default:  // Other stuff never works.
7895    return false;
7896  }
7897
7898  return true;
7899}
7900
7901
7902bool X86TargetLowering::isTruncateFree(const Type *Ty1, const Type *Ty2) const {
7903  if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
7904    return false;
7905  unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
7906  unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
7907  if (NumBits1 <= NumBits2)
7908    return false;
7909  return true;
7910}
7911
7912bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
7913  if (!VT1.isInteger() || !VT2.isInteger())
7914    return false;
7915  unsigned NumBits1 = VT1.getSizeInBits();
7916  unsigned NumBits2 = VT2.getSizeInBits();
7917  if (NumBits1 <= NumBits2)
7918    return false;
7919  return true;
7920}
7921
7922bool X86TargetLowering::isZExtFree(const Type *Ty1, const Type *Ty2) const {
7923  // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
7924  return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
7925}
7926
7927bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
7928  // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
7929  return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
7930}
7931
7932bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
7933  // i16 instructions are longer (0x66 prefix) and potentially slower.
7934  return !(VT1 == MVT::i32 && VT2 == MVT::i16);
7935}
7936
7937/// isShuffleMaskLegal - Targets can use this to indicate that they only
7938/// support *some* VECTOR_SHUFFLE operations, those with specific masks.
7939/// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
7940/// are assumed to be legal.
7941bool
7942X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
7943                                      EVT VT) const {
7944  // Only do shuffles on 128-bit vector types for now.
7945  if (VT.getSizeInBits() == 64)
7946    return false;
7947
7948  // FIXME: pshufb, blends, shifts.
7949  return (VT.getVectorNumElements() == 2 ||
7950          ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
7951          isMOVLMask(M, VT) ||
7952          isSHUFPMask(M, VT) ||
7953          isPSHUFDMask(M, VT) ||
7954          isPSHUFHWMask(M, VT) ||
7955          isPSHUFLWMask(M, VT) ||
7956          isPALIGNRMask(M, VT, Subtarget->hasSSSE3()) ||
7957          isUNPCKLMask(M, VT) ||
7958          isUNPCKHMask(M, VT) ||
7959          isUNPCKL_v_undef_Mask(M, VT) ||
7960          isUNPCKH_v_undef_Mask(M, VT));
7961}
7962
7963bool
7964X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
7965                                          EVT VT) const {
7966  unsigned NumElts = VT.getVectorNumElements();
7967  // FIXME: This collection of masks seems suspect.
7968  if (NumElts == 2)
7969    return true;
7970  if (NumElts == 4 && VT.getSizeInBits() == 128) {
7971    return (isMOVLMask(Mask, VT)  ||
7972            isCommutedMOVLMask(Mask, VT, true) ||
7973            isSHUFPMask(Mask, VT) ||
7974            isCommutedSHUFPMask(Mask, VT));
7975  }
7976  return false;
7977}
7978
7979//===----------------------------------------------------------------------===//
7980//                           X86 Scheduler Hooks
7981//===----------------------------------------------------------------------===//
7982
7983// private utility function
7984MachineBasicBlock *
7985X86TargetLowering::EmitAtomicBitwiseWithCustomInserter(MachineInstr *bInstr,
7986                                                       MachineBasicBlock *MBB,
7987                                                       unsigned regOpc,
7988                                                       unsigned immOpc,
7989                                                       unsigned LoadOpc,
7990                                                       unsigned CXchgOpc,
7991                                                       unsigned copyOpc,
7992                                                       unsigned notOpc,
7993                                                       unsigned EAXreg,
7994                                                       TargetRegisterClass *RC,
7995                                                       bool invSrc) const {
7996  // For the atomic bitwise operator, we generate
7997  //   thisMBB:
7998  //   newMBB:
7999  //     ld  t1 = [bitinstr.addr]
8000  //     op  t2 = t1, [bitinstr.val]
8001  //     mov EAX = t1
8002  //     lcs dest = [bitinstr.addr], t2  [EAX is implicit]
8003  //     bz  newMBB
8004  //     fallthrough -->nextMBB
8005  const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
8006  const BasicBlock *LLVM_BB = MBB->getBasicBlock();
8007  MachineFunction::iterator MBBIter = MBB;
8008  ++MBBIter;
8009
8010  /// First build the CFG
8011  MachineFunction *F = MBB->getParent();
8012  MachineBasicBlock *thisMBB = MBB;
8013  MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
8014  MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
8015  F->insert(MBBIter, newMBB);
8016  F->insert(MBBIter, nextMBB);
8017
8018  // Move all successors to thisMBB to nextMBB
8019  nextMBB->transferSuccessors(thisMBB);
8020
8021  // Update thisMBB to fall through to newMBB
8022  thisMBB->addSuccessor(newMBB);
8023
8024  // newMBB jumps to itself and fall through to nextMBB
8025  newMBB->addSuccessor(nextMBB);
8026  newMBB->addSuccessor(newMBB);
8027
8028  // Insert instructions into newMBB based on incoming instruction
8029  assert(bInstr->getNumOperands() < X86AddrNumOperands + 4 &&
8030         "unexpected number of operands");
8031  DebugLoc dl = bInstr->getDebugLoc();
8032  MachineOperand& destOper = bInstr->getOperand(0);
8033  MachineOperand* argOpers[2 + X86AddrNumOperands];
8034  int numArgs = bInstr->getNumOperands() - 1;
8035  for (int i=0; i < numArgs; ++i)
8036    argOpers[i] = &bInstr->getOperand(i+1);
8037
8038  // x86 address has 4 operands: base, index, scale, and displacement
8039  int lastAddrIndx = X86AddrNumOperands - 1; // [0,3]
8040  int valArgIndx = lastAddrIndx + 1;
8041
8042  unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
8043  MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(LoadOpc), t1);
8044  for (int i=0; i <= lastAddrIndx; ++i)
8045    (*MIB).addOperand(*argOpers[i]);
8046
8047  unsigned tt = F->getRegInfo().createVirtualRegister(RC);
8048  if (invSrc) {
8049    MIB = BuildMI(newMBB, dl, TII->get(notOpc), tt).addReg(t1);
8050  }
8051  else
8052    tt = t1;
8053
8054  unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
8055  assert((argOpers[valArgIndx]->isReg() ||
8056          argOpers[valArgIndx]->isImm()) &&
8057         "invalid operand");
8058  if (argOpers[valArgIndx]->isReg())
8059    MIB = BuildMI(newMBB, dl, TII->get(regOpc), t2);
8060  else
8061    MIB = BuildMI(newMBB, dl, TII->get(immOpc), t2);
8062  MIB.addReg(tt);
8063  (*MIB).addOperand(*argOpers[valArgIndx]);
8064
8065  MIB = BuildMI(newMBB, dl, TII->get(copyOpc), EAXreg);
8066  MIB.addReg(t1);
8067
8068  MIB = BuildMI(newMBB, dl, TII->get(CXchgOpc));
8069  for (int i=0; i <= lastAddrIndx; ++i)
8070    (*MIB).addOperand(*argOpers[i]);
8071  MIB.addReg(t2);
8072  assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
8073  (*MIB).setMemRefs(bInstr->memoperands_begin(),
8074                    bInstr->memoperands_end());
8075
8076  MIB = BuildMI(newMBB, dl, TII->get(copyOpc), destOper.getReg());
8077  MIB.addReg(EAXreg);
8078
8079  // insert branch
8080  BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
8081
8082  F->DeleteMachineInstr(bInstr);   // The pseudo instruction is gone now.
8083  return nextMBB;
8084}
8085
8086// private utility function:  64 bit atomics on 32 bit host.
8087MachineBasicBlock *
8088X86TargetLowering::EmitAtomicBit6432WithCustomInserter(MachineInstr *bInstr,
8089                                                       MachineBasicBlock *MBB,
8090                                                       unsigned regOpcL,
8091                                                       unsigned regOpcH,
8092                                                       unsigned immOpcL,
8093                                                       unsigned immOpcH,
8094                                                       bool invSrc) const {
8095  // For the atomic bitwise operator, we generate
8096  //   thisMBB (instructions are in pairs, except cmpxchg8b)
8097  //     ld t1,t2 = [bitinstr.addr]
8098  //   newMBB:
8099  //     out1, out2 = phi (thisMBB, t1/t2) (newMBB, t3/t4)
8100  //     op  t5, t6 <- out1, out2, [bitinstr.val]
8101  //      (for SWAP, substitute:  mov t5, t6 <- [bitinstr.val])
8102  //     mov ECX, EBX <- t5, t6
8103  //     mov EAX, EDX <- t1, t2
8104  //     cmpxchg8b [bitinstr.addr]  [EAX, EDX, EBX, ECX implicit]
8105  //     mov t3, t4 <- EAX, EDX
8106  //     bz  newMBB
8107  //     result in out1, out2
8108  //     fallthrough -->nextMBB
8109
8110  const TargetRegisterClass *RC = X86::GR32RegisterClass;
8111  const unsigned LoadOpc = X86::MOV32rm;
8112  const unsigned copyOpc = X86::MOV32rr;
8113  const unsigned NotOpc = X86::NOT32r;
8114  const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
8115  const BasicBlock *LLVM_BB = MBB->getBasicBlock();
8116  MachineFunction::iterator MBBIter = MBB;
8117  ++MBBIter;
8118
8119  /// First build the CFG
8120  MachineFunction *F = MBB->getParent();
8121  MachineBasicBlock *thisMBB = MBB;
8122  MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
8123  MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
8124  F->insert(MBBIter, newMBB);
8125  F->insert(MBBIter, nextMBB);
8126
8127  // Move all successors to thisMBB to nextMBB
8128  nextMBB->transferSuccessors(thisMBB);
8129
8130  // Update thisMBB to fall through to newMBB
8131  thisMBB->addSuccessor(newMBB);
8132
8133  // newMBB jumps to itself and fall through to nextMBB
8134  newMBB->addSuccessor(nextMBB);
8135  newMBB->addSuccessor(newMBB);
8136
8137  DebugLoc dl = bInstr->getDebugLoc();
8138  // Insert instructions into newMBB based on incoming instruction
8139  // There are 8 "real" operands plus 9 implicit def/uses, ignored here.
8140  assert(bInstr->getNumOperands() < X86AddrNumOperands + 14 &&
8141         "unexpected number of operands");
8142  MachineOperand& dest1Oper = bInstr->getOperand(0);
8143  MachineOperand& dest2Oper = bInstr->getOperand(1);
8144  MachineOperand* argOpers[2 + X86AddrNumOperands];
8145  for (int i=0; i < 2 + X86AddrNumOperands; ++i)
8146    argOpers[i] = &bInstr->getOperand(i+2);
8147
8148  // x86 address has 5 operands: base, index, scale, displacement, and segment.
8149  int lastAddrIndx = X86AddrNumOperands - 1; // [0,3]
8150
8151  unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
8152  MachineInstrBuilder MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t1);
8153  for (int i=0; i <= lastAddrIndx; ++i)
8154    (*MIB).addOperand(*argOpers[i]);
8155  unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
8156  MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t2);
8157  // add 4 to displacement.
8158  for (int i=0; i <= lastAddrIndx-2; ++i)
8159    (*MIB).addOperand(*argOpers[i]);
8160  MachineOperand newOp3 = *(argOpers[3]);
8161  if (newOp3.isImm())
8162    newOp3.setImm(newOp3.getImm()+4);
8163  else
8164    newOp3.setOffset(newOp3.getOffset()+4);
8165  (*MIB).addOperand(newOp3);
8166  (*MIB).addOperand(*argOpers[lastAddrIndx]);
8167
8168  // t3/4 are defined later, at the bottom of the loop
8169  unsigned t3 = F->getRegInfo().createVirtualRegister(RC);
8170  unsigned t4 = F->getRegInfo().createVirtualRegister(RC);
8171  BuildMI(newMBB, dl, TII->get(X86::PHI), dest1Oper.getReg())
8172    .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(newMBB);
8173  BuildMI(newMBB, dl, TII->get(X86::PHI), dest2Oper.getReg())
8174    .addReg(t2).addMBB(thisMBB).addReg(t4).addMBB(newMBB);
8175
8176  // The subsequent operations should be using the destination registers of
8177  //the PHI instructions.
8178  if (invSrc) {
8179    t1 = F->getRegInfo().createVirtualRegister(RC);
8180    t2 = F->getRegInfo().createVirtualRegister(RC);
8181    MIB = BuildMI(newMBB, dl, TII->get(NotOpc), t1).addReg(dest1Oper.getReg());
8182    MIB = BuildMI(newMBB, dl, TII->get(NotOpc), t2).addReg(dest2Oper.getReg());
8183  } else {
8184    t1 = dest1Oper.getReg();
8185    t2 = dest2Oper.getReg();
8186  }
8187
8188  int valArgIndx = lastAddrIndx + 1;
8189  assert((argOpers[valArgIndx]->isReg() ||
8190          argOpers[valArgIndx]->isImm()) &&
8191         "invalid operand");
8192  unsigned t5 = F->getRegInfo().createVirtualRegister(RC);
8193  unsigned t6 = F->getRegInfo().createVirtualRegister(RC);
8194  if (argOpers[valArgIndx]->isReg())
8195    MIB = BuildMI(newMBB, dl, TII->get(regOpcL), t5);
8196  else
8197    MIB = BuildMI(newMBB, dl, TII->get(immOpcL), t5);
8198  if (regOpcL != X86::MOV32rr)
8199    MIB.addReg(t1);
8200  (*MIB).addOperand(*argOpers[valArgIndx]);
8201  assert(argOpers[valArgIndx + 1]->isReg() ==
8202         argOpers[valArgIndx]->isReg());
8203  assert(argOpers[valArgIndx + 1]->isImm() ==
8204         argOpers[valArgIndx]->isImm());
8205  if (argOpers[valArgIndx + 1]->isReg())
8206    MIB = BuildMI(newMBB, dl, TII->get(regOpcH), t6);
8207  else
8208    MIB = BuildMI(newMBB, dl, TII->get(immOpcH), t6);
8209  if (regOpcH != X86::MOV32rr)
8210    MIB.addReg(t2);
8211  (*MIB).addOperand(*argOpers[valArgIndx + 1]);
8212
8213  MIB = BuildMI(newMBB, dl, TII->get(copyOpc), X86::EAX);
8214  MIB.addReg(t1);
8215  MIB = BuildMI(newMBB, dl, TII->get(copyOpc), X86::EDX);
8216  MIB.addReg(t2);
8217
8218  MIB = BuildMI(newMBB, dl, TII->get(copyOpc), X86::EBX);
8219  MIB.addReg(t5);
8220  MIB = BuildMI(newMBB, dl, TII->get(copyOpc), X86::ECX);
8221  MIB.addReg(t6);
8222
8223  MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG8B));
8224  for (int i=0; i <= lastAddrIndx; ++i)
8225    (*MIB).addOperand(*argOpers[i]);
8226
8227  assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
8228  (*MIB).setMemRefs(bInstr->memoperands_begin(),
8229                    bInstr->memoperands_end());
8230
8231  MIB = BuildMI(newMBB, dl, TII->get(copyOpc), t3);
8232  MIB.addReg(X86::EAX);
8233  MIB = BuildMI(newMBB, dl, TII->get(copyOpc), t4);
8234  MIB.addReg(X86::EDX);
8235
8236  // insert branch
8237  BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
8238
8239  F->DeleteMachineInstr(bInstr);   // The pseudo instruction is gone now.
8240  return nextMBB;
8241}
8242
8243// private utility function
8244MachineBasicBlock *
8245X86TargetLowering::EmitAtomicMinMaxWithCustomInserter(MachineInstr *mInstr,
8246                                                      MachineBasicBlock *MBB,
8247                                                      unsigned cmovOpc) const {
8248  // For the atomic min/max operator, we generate
8249  //   thisMBB:
8250  //   newMBB:
8251  //     ld t1 = [min/max.addr]
8252  //     mov t2 = [min/max.val]
8253  //     cmp  t1, t2
8254  //     cmov[cond] t2 = t1
8255  //     mov EAX = t1
8256  //     lcs dest = [bitinstr.addr], t2  [EAX is implicit]
8257  //     bz   newMBB
8258  //     fallthrough -->nextMBB
8259  //
8260  const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
8261  const BasicBlock *LLVM_BB = MBB->getBasicBlock();
8262  MachineFunction::iterator MBBIter = MBB;
8263  ++MBBIter;
8264
8265  /// First build the CFG
8266  MachineFunction *F = MBB->getParent();
8267  MachineBasicBlock *thisMBB = MBB;
8268  MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
8269  MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
8270  F->insert(MBBIter, newMBB);
8271  F->insert(MBBIter, nextMBB);
8272
8273  // Move all successors of thisMBB to nextMBB
8274  nextMBB->transferSuccessors(thisMBB);
8275
8276  // Update thisMBB to fall through to newMBB
8277  thisMBB->addSuccessor(newMBB);
8278
8279  // newMBB jumps to newMBB and fall through to nextMBB
8280  newMBB->addSuccessor(nextMBB);
8281  newMBB->addSuccessor(newMBB);
8282
8283  DebugLoc dl = mInstr->getDebugLoc();
8284  // Insert instructions into newMBB based on incoming instruction
8285  assert(mInstr->getNumOperands() < X86AddrNumOperands + 4 &&
8286         "unexpected number of operands");
8287  MachineOperand& destOper = mInstr->getOperand(0);
8288  MachineOperand* argOpers[2 + X86AddrNumOperands];
8289  int numArgs = mInstr->getNumOperands() - 1;
8290  for (int i=0; i < numArgs; ++i)
8291    argOpers[i] = &mInstr->getOperand(i+1);
8292
8293  // x86 address has 4 operands: base, index, scale, and displacement
8294  int lastAddrIndx = X86AddrNumOperands - 1; // [0,3]
8295  int valArgIndx = lastAddrIndx + 1;
8296
8297  unsigned t1 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
8298  MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rm), t1);
8299  for (int i=0; i <= lastAddrIndx; ++i)
8300    (*MIB).addOperand(*argOpers[i]);
8301
8302  // We only support register and immediate values
8303  assert((argOpers[valArgIndx]->isReg() ||
8304          argOpers[valArgIndx]->isImm()) &&
8305         "invalid operand");
8306
8307  unsigned t2 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
8308  if (argOpers[valArgIndx]->isReg())
8309    MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rr), t2);
8310  else
8311    MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rr), t2);
8312  (*MIB).addOperand(*argOpers[valArgIndx]);
8313
8314  MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rr), X86::EAX);
8315  MIB.addReg(t1);
8316
8317  MIB = BuildMI(newMBB, dl, TII->get(X86::CMP32rr));
8318  MIB.addReg(t1);
8319  MIB.addReg(t2);
8320
8321  // Generate movc
8322  unsigned t3 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
8323  MIB = BuildMI(newMBB, dl, TII->get(cmovOpc),t3);
8324  MIB.addReg(t2);
8325  MIB.addReg(t1);
8326
8327  // Cmp and exchange if none has modified the memory location
8328  MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG32));
8329  for (int i=0; i <= lastAddrIndx; ++i)
8330    (*MIB).addOperand(*argOpers[i]);
8331  MIB.addReg(t3);
8332  assert(mInstr->hasOneMemOperand() && "Unexpected number of memoperand");
8333  (*MIB).setMemRefs(mInstr->memoperands_begin(),
8334                    mInstr->memoperands_end());
8335
8336  MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rr), destOper.getReg());
8337  MIB.addReg(X86::EAX);
8338
8339  // insert branch
8340  BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
8341
8342  F->DeleteMachineInstr(mInstr);   // The pseudo instruction is gone now.
8343  return nextMBB;
8344}
8345
8346// FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
8347// all of this code can be replaced with that in the .td file.
8348MachineBasicBlock *
8349X86TargetLowering::EmitPCMP(MachineInstr *MI, MachineBasicBlock *BB,
8350                            unsigned numArgs, bool memArg) const {
8351
8352  MachineFunction *F = BB->getParent();
8353  DebugLoc dl = MI->getDebugLoc();
8354  const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
8355
8356  unsigned Opc;
8357  if (memArg)
8358    Opc = numArgs == 3 ? X86::PCMPISTRM128rm : X86::PCMPESTRM128rm;
8359  else
8360    Opc = numArgs == 3 ? X86::PCMPISTRM128rr : X86::PCMPESTRM128rr;
8361
8362  MachineInstrBuilder MIB = BuildMI(BB, dl, TII->get(Opc));
8363
8364  for (unsigned i = 0; i < numArgs; ++i) {
8365    MachineOperand &Op = MI->getOperand(i+1);
8366
8367    if (!(Op.isReg() && Op.isImplicit()))
8368      MIB.addOperand(Op);
8369  }
8370
8371  BuildMI(BB, dl, TII->get(X86::MOVAPSrr), MI->getOperand(0).getReg())
8372    .addReg(X86::XMM0);
8373
8374  F->DeleteMachineInstr(MI);
8375
8376  return BB;
8377}
8378
8379MachineBasicBlock *
8380X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
8381                                                 MachineInstr *MI,
8382                                                 MachineBasicBlock *MBB) const {
8383  // Emit code to save XMM registers to the stack. The ABI says that the
8384  // number of registers to save is given in %al, so it's theoretically
8385  // possible to do an indirect jump trick to avoid saving all of them,
8386  // however this code takes a simpler approach and just executes all
8387  // of the stores if %al is non-zero. It's less code, and it's probably
8388  // easier on the hardware branch predictor, and stores aren't all that
8389  // expensive anyway.
8390
8391  // Create the new basic blocks. One block contains all the XMM stores,
8392  // and one block is the final destination regardless of whether any
8393  // stores were performed.
8394  const BasicBlock *LLVM_BB = MBB->getBasicBlock();
8395  MachineFunction *F = MBB->getParent();
8396  MachineFunction::iterator MBBIter = MBB;
8397  ++MBBIter;
8398  MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
8399  MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
8400  F->insert(MBBIter, XMMSaveMBB);
8401  F->insert(MBBIter, EndMBB);
8402
8403  // Set up the CFG.
8404  // Move any original successors of MBB to the end block.
8405  EndMBB->transferSuccessors(MBB);
8406  // The original block will now fall through to the XMM save block.
8407  MBB->addSuccessor(XMMSaveMBB);
8408  // The XMMSaveMBB will fall through to the end block.
8409  XMMSaveMBB->addSuccessor(EndMBB);
8410
8411  // Now add the instructions.
8412  const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
8413  DebugLoc DL = MI->getDebugLoc();
8414
8415  unsigned CountReg = MI->getOperand(0).getReg();
8416  int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
8417  int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
8418
8419  if (!Subtarget->isTargetWin64()) {
8420    // If %al is 0, branch around the XMM save block.
8421    BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
8422    BuildMI(MBB, DL, TII->get(X86::JE_4)).addMBB(EndMBB);
8423    MBB->addSuccessor(EndMBB);
8424  }
8425
8426  // In the XMM save block, save all the XMM argument registers.
8427  for (int i = 3, e = MI->getNumOperands(); i != e; ++i) {
8428    int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
8429    MachineMemOperand *MMO =
8430      F->getMachineMemOperand(
8431        PseudoSourceValue::getFixedStack(RegSaveFrameIndex),
8432        MachineMemOperand::MOStore, Offset,
8433        /*Size=*/16, /*Align=*/16);
8434    BuildMI(XMMSaveMBB, DL, TII->get(X86::MOVAPSmr))
8435      .addFrameIndex(RegSaveFrameIndex)
8436      .addImm(/*Scale=*/1)
8437      .addReg(/*IndexReg=*/0)
8438      .addImm(/*Disp=*/Offset)
8439      .addReg(/*Segment=*/0)
8440      .addReg(MI->getOperand(i).getReg())
8441      .addMemOperand(MMO);
8442  }
8443
8444  F->DeleteMachineInstr(MI);   // The pseudo instruction is gone now.
8445
8446  return EndMBB;
8447}
8448
8449MachineBasicBlock *
8450X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
8451                                     MachineBasicBlock *BB,
8452                   DenseMap<MachineBasicBlock*, MachineBasicBlock*> *EM) const {
8453  const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
8454  DebugLoc DL = MI->getDebugLoc();
8455
8456  // To "insert" a SELECT_CC instruction, we actually have to insert the
8457  // diamond control-flow pattern.  The incoming instruction knows the
8458  // destination vreg to set, the condition code register to branch on, the
8459  // true/false values to select between, and a branch opcode to use.
8460  const BasicBlock *LLVM_BB = BB->getBasicBlock();
8461  MachineFunction::iterator It = BB;
8462  ++It;
8463
8464  //  thisMBB:
8465  //  ...
8466  //   TrueVal = ...
8467  //   cmpTY ccX, r1, r2
8468  //   bCC copy1MBB
8469  //   fallthrough --> copy0MBB
8470  MachineBasicBlock *thisMBB = BB;
8471  MachineFunction *F = BB->getParent();
8472  MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
8473  MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
8474  unsigned Opc =
8475    X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
8476  BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
8477  F->insert(It, copy0MBB);
8478  F->insert(It, sinkMBB);
8479  // Update machine-CFG edges by first adding all successors of the current
8480  // block to the new block which will contain the Phi node for the select.
8481  // Also inform sdisel of the edge changes.
8482  for (MachineBasicBlock::succ_iterator I = BB->succ_begin(),
8483         E = BB->succ_end(); I != E; ++I) {
8484    EM->insert(std::make_pair(*I, sinkMBB));
8485    sinkMBB->addSuccessor(*I);
8486  }
8487  // Next, remove all successors of the current block, and add the true
8488  // and fallthrough blocks as its successors.
8489  while (!BB->succ_empty())
8490    BB->removeSuccessor(BB->succ_begin());
8491  // Add the true and fallthrough blocks as its successors.
8492  BB->addSuccessor(copy0MBB);
8493  BB->addSuccessor(sinkMBB);
8494
8495  //  copy0MBB:
8496  //   %FalseValue = ...
8497  //   # fallthrough to sinkMBB
8498  BB = copy0MBB;
8499
8500  // Update machine-CFG edges
8501  BB->addSuccessor(sinkMBB);
8502
8503  //  sinkMBB:
8504  //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
8505  //  ...
8506  BB = sinkMBB;
8507  BuildMI(BB, DL, TII->get(X86::PHI), MI->getOperand(0).getReg())
8508    .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
8509    .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
8510
8511  F->DeleteMachineInstr(MI);   // The pseudo instruction is gone now.
8512  return BB;
8513}
8514
8515MachineBasicBlock *
8516X86TargetLowering::EmitLoweredMingwAlloca(MachineInstr *MI,
8517                                          MachineBasicBlock *BB,
8518                   DenseMap<MachineBasicBlock*, MachineBasicBlock*> *EM) const {
8519  const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
8520  DebugLoc DL = MI->getDebugLoc();
8521  MachineFunction *F = BB->getParent();
8522
8523  // The lowering is pretty easy: we're just emitting the call to _alloca.  The
8524  // non-trivial part is impdef of ESP.
8525  // FIXME: The code should be tweaked as soon as we'll try to do codegen for
8526  // mingw-w64.
8527
8528  BuildMI(BB, DL, TII->get(X86::CALLpcrel32))
8529    .addExternalSymbol("_alloca")
8530    .addReg(X86::EAX, RegState::Implicit)
8531    .addReg(X86::ESP, RegState::Implicit)
8532    .addReg(X86::EAX, RegState::Define | RegState::Implicit)
8533    .addReg(X86::ESP, RegState::Define | RegState::Implicit);
8534
8535  F->DeleteMachineInstr(MI);   // The pseudo instruction is gone now.
8536  return BB;
8537}
8538
8539MachineBasicBlock *
8540X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
8541                                               MachineBasicBlock *BB,
8542                   DenseMap<MachineBasicBlock*, MachineBasicBlock*> *EM) const {
8543  switch (MI->getOpcode()) {
8544  default: assert(false && "Unexpected instr type to insert");
8545  case X86::MINGW_ALLOCA:
8546    return EmitLoweredMingwAlloca(MI, BB, EM);
8547  case X86::CMOV_GR8:
8548  case X86::CMOV_V1I64:
8549  case X86::CMOV_FR32:
8550  case X86::CMOV_FR64:
8551  case X86::CMOV_V4F32:
8552  case X86::CMOV_V2F64:
8553  case X86::CMOV_V2I64:
8554  case X86::CMOV_GR16:
8555  case X86::CMOV_GR32:
8556  case X86::CMOV_RFP32:
8557  case X86::CMOV_RFP64:
8558  case X86::CMOV_RFP80:
8559    return EmitLoweredSelect(MI, BB, EM);
8560
8561  case X86::FP32_TO_INT16_IN_MEM:
8562  case X86::FP32_TO_INT32_IN_MEM:
8563  case X86::FP32_TO_INT64_IN_MEM:
8564  case X86::FP64_TO_INT16_IN_MEM:
8565  case X86::FP64_TO_INT32_IN_MEM:
8566  case X86::FP64_TO_INT64_IN_MEM:
8567  case X86::FP80_TO_INT16_IN_MEM:
8568  case X86::FP80_TO_INT32_IN_MEM:
8569  case X86::FP80_TO_INT64_IN_MEM: {
8570    const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
8571    DebugLoc DL = MI->getDebugLoc();
8572
8573    // Change the floating point control register to use "round towards zero"
8574    // mode when truncating to an integer value.
8575    MachineFunction *F = BB->getParent();
8576    int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
8577    addFrameReference(BuildMI(BB, DL, TII->get(X86::FNSTCW16m)), CWFrameIdx);
8578
8579    // Load the old value of the high byte of the control word...
8580    unsigned OldCW =
8581      F->getRegInfo().createVirtualRegister(X86::GR16RegisterClass);
8582    addFrameReference(BuildMI(BB, DL, TII->get(X86::MOV16rm), OldCW),
8583                      CWFrameIdx);
8584
8585    // Set the high part to be round to zero...
8586    addFrameReference(BuildMI(BB, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
8587      .addImm(0xC7F);
8588
8589    // Reload the modified control word now...
8590    addFrameReference(BuildMI(BB, DL, TII->get(X86::FLDCW16m)), CWFrameIdx);
8591
8592    // Restore the memory image of control word to original value
8593    addFrameReference(BuildMI(BB, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
8594      .addReg(OldCW);
8595
8596    // Get the X86 opcode to use.
8597    unsigned Opc;
8598    switch (MI->getOpcode()) {
8599    default: llvm_unreachable("illegal opcode!");
8600    case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
8601    case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
8602    case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
8603    case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
8604    case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
8605    case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
8606    case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
8607    case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
8608    case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
8609    }
8610
8611    X86AddressMode AM;
8612    MachineOperand &Op = MI->getOperand(0);
8613    if (Op.isReg()) {
8614      AM.BaseType = X86AddressMode::RegBase;
8615      AM.Base.Reg = Op.getReg();
8616    } else {
8617      AM.BaseType = X86AddressMode::FrameIndexBase;
8618      AM.Base.FrameIndex = Op.getIndex();
8619    }
8620    Op = MI->getOperand(1);
8621    if (Op.isImm())
8622      AM.Scale = Op.getImm();
8623    Op = MI->getOperand(2);
8624    if (Op.isImm())
8625      AM.IndexReg = Op.getImm();
8626    Op = MI->getOperand(3);
8627    if (Op.isGlobal()) {
8628      AM.GV = Op.getGlobal();
8629    } else {
8630      AM.Disp = Op.getImm();
8631    }
8632    addFullAddress(BuildMI(BB, DL, TII->get(Opc)), AM)
8633                      .addReg(MI->getOperand(X86AddrNumOperands).getReg());
8634
8635    // Reload the original control word now.
8636    addFrameReference(BuildMI(BB, DL, TII->get(X86::FLDCW16m)), CWFrameIdx);
8637
8638    F->DeleteMachineInstr(MI);   // The pseudo instruction is gone now.
8639    return BB;
8640  }
8641    // DBG_VALUE.  Only the frame index case is done here.
8642  case X86::DBG_VALUE: {
8643    const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
8644    DebugLoc DL = MI->getDebugLoc();
8645    X86AddressMode AM;
8646    MachineFunction *F = BB->getParent();
8647    AM.BaseType = X86AddressMode::FrameIndexBase;
8648    AM.Base.FrameIndex = MI->getOperand(0).getImm();
8649    addFullAddress(BuildMI(BB, DL, TII->get(X86::DBG_VALUE)), AM).
8650      addImm(MI->getOperand(1).getImm()).
8651      addMetadata(MI->getOperand(2).getMetadata());
8652    F->DeleteMachineInstr(MI);      // Remove pseudo.
8653    return BB;
8654  }
8655
8656    // String/text processing lowering.
8657  case X86::PCMPISTRM128REG:
8658    return EmitPCMP(MI, BB, 3, false /* in-mem */);
8659  case X86::PCMPISTRM128MEM:
8660    return EmitPCMP(MI, BB, 3, true /* in-mem */);
8661  case X86::PCMPESTRM128REG:
8662    return EmitPCMP(MI, BB, 5, false /* in mem */);
8663  case X86::PCMPESTRM128MEM:
8664    return EmitPCMP(MI, BB, 5, true /* in mem */);
8665
8666    // Atomic Lowering.
8667  case X86::ATOMAND32:
8668    return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
8669                                               X86::AND32ri, X86::MOV32rm,
8670                                               X86::LCMPXCHG32, X86::MOV32rr,
8671                                               X86::NOT32r, X86::EAX,
8672                                               X86::GR32RegisterClass);
8673  case X86::ATOMOR32:
8674    return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR32rr,
8675                                               X86::OR32ri, X86::MOV32rm,
8676                                               X86::LCMPXCHG32, X86::MOV32rr,
8677                                               X86::NOT32r, X86::EAX,
8678                                               X86::GR32RegisterClass);
8679  case X86::ATOMXOR32:
8680    return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR32rr,
8681                                               X86::XOR32ri, X86::MOV32rm,
8682                                               X86::LCMPXCHG32, X86::MOV32rr,
8683                                               X86::NOT32r, X86::EAX,
8684                                               X86::GR32RegisterClass);
8685  case X86::ATOMNAND32:
8686    return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
8687                                               X86::AND32ri, X86::MOV32rm,
8688                                               X86::LCMPXCHG32, X86::MOV32rr,
8689                                               X86::NOT32r, X86::EAX,
8690                                               X86::GR32RegisterClass, true);
8691  case X86::ATOMMIN32:
8692    return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL32rr);
8693  case X86::ATOMMAX32:
8694    return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG32rr);
8695  case X86::ATOMUMIN32:
8696    return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB32rr);
8697  case X86::ATOMUMAX32:
8698    return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA32rr);
8699
8700  case X86::ATOMAND16:
8701    return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
8702                                               X86::AND16ri, X86::MOV16rm,
8703                                               X86::LCMPXCHG16, X86::MOV16rr,
8704                                               X86::NOT16r, X86::AX,
8705                                               X86::GR16RegisterClass);
8706  case X86::ATOMOR16:
8707    return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR16rr,
8708                                               X86::OR16ri, X86::MOV16rm,
8709                                               X86::LCMPXCHG16, X86::MOV16rr,
8710                                               X86::NOT16r, X86::AX,
8711                                               X86::GR16RegisterClass);
8712  case X86::ATOMXOR16:
8713    return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR16rr,
8714                                               X86::XOR16ri, X86::MOV16rm,
8715                                               X86::LCMPXCHG16, X86::MOV16rr,
8716                                               X86::NOT16r, X86::AX,
8717                                               X86::GR16RegisterClass);
8718  case X86::ATOMNAND16:
8719    return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
8720                                               X86::AND16ri, X86::MOV16rm,
8721                                               X86::LCMPXCHG16, X86::MOV16rr,
8722                                               X86::NOT16r, X86::AX,
8723                                               X86::GR16RegisterClass, true);
8724  case X86::ATOMMIN16:
8725    return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL16rr);
8726  case X86::ATOMMAX16:
8727    return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG16rr);
8728  case X86::ATOMUMIN16:
8729    return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB16rr);
8730  case X86::ATOMUMAX16:
8731    return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA16rr);
8732
8733  case X86::ATOMAND8:
8734    return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
8735                                               X86::AND8ri, X86::MOV8rm,
8736                                               X86::LCMPXCHG8, X86::MOV8rr,
8737                                               X86::NOT8r, X86::AL,
8738                                               X86::GR8RegisterClass);
8739  case X86::ATOMOR8:
8740    return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR8rr,
8741                                               X86::OR8ri, X86::MOV8rm,
8742                                               X86::LCMPXCHG8, X86::MOV8rr,
8743                                               X86::NOT8r, X86::AL,
8744                                               X86::GR8RegisterClass);
8745  case X86::ATOMXOR8:
8746    return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR8rr,
8747                                               X86::XOR8ri, X86::MOV8rm,
8748                                               X86::LCMPXCHG8, X86::MOV8rr,
8749                                               X86::NOT8r, X86::AL,
8750                                               X86::GR8RegisterClass);
8751  case X86::ATOMNAND8:
8752    return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
8753                                               X86::AND8ri, X86::MOV8rm,
8754                                               X86::LCMPXCHG8, X86::MOV8rr,
8755                                               X86::NOT8r, X86::AL,
8756                                               X86::GR8RegisterClass, true);
8757  // FIXME: There are no CMOV8 instructions; MIN/MAX need some other way.
8758  // This group is for 64-bit host.
8759  case X86::ATOMAND64:
8760    return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
8761                                               X86::AND64ri32, X86::MOV64rm,
8762                                               X86::LCMPXCHG64, X86::MOV64rr,
8763                                               X86::NOT64r, X86::RAX,
8764                                               X86::GR64RegisterClass);
8765  case X86::ATOMOR64:
8766    return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR64rr,
8767                                               X86::OR64ri32, X86::MOV64rm,
8768                                               X86::LCMPXCHG64, X86::MOV64rr,
8769                                               X86::NOT64r, X86::RAX,
8770                                               X86::GR64RegisterClass);
8771  case X86::ATOMXOR64:
8772    return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR64rr,
8773                                               X86::XOR64ri32, X86::MOV64rm,
8774                                               X86::LCMPXCHG64, X86::MOV64rr,
8775                                               X86::NOT64r, X86::RAX,
8776                                               X86::GR64RegisterClass);
8777  case X86::ATOMNAND64:
8778    return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
8779                                               X86::AND64ri32, X86::MOV64rm,
8780                                               X86::LCMPXCHG64, X86::MOV64rr,
8781                                               X86::NOT64r, X86::RAX,
8782                                               X86::GR64RegisterClass, true);
8783  case X86::ATOMMIN64:
8784    return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL64rr);
8785  case X86::ATOMMAX64:
8786    return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG64rr);
8787  case X86::ATOMUMIN64:
8788    return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB64rr);
8789  case X86::ATOMUMAX64:
8790    return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA64rr);
8791
8792  // This group does 64-bit operations on a 32-bit host.
8793  case X86::ATOMAND6432:
8794    return EmitAtomicBit6432WithCustomInserter(MI, BB,
8795                                               X86::AND32rr, X86::AND32rr,
8796                                               X86::AND32ri, X86::AND32ri,
8797                                               false);
8798  case X86::ATOMOR6432:
8799    return EmitAtomicBit6432WithCustomInserter(MI, BB,
8800                                               X86::OR32rr, X86::OR32rr,
8801                                               X86::OR32ri, X86::OR32ri,
8802                                               false);
8803  case X86::ATOMXOR6432:
8804    return EmitAtomicBit6432WithCustomInserter(MI, BB,
8805                                               X86::XOR32rr, X86::XOR32rr,
8806                                               X86::XOR32ri, X86::XOR32ri,
8807                                               false);
8808  case X86::ATOMNAND6432:
8809    return EmitAtomicBit6432WithCustomInserter(MI, BB,
8810                                               X86::AND32rr, X86::AND32rr,
8811                                               X86::AND32ri, X86::AND32ri,
8812                                               true);
8813  case X86::ATOMADD6432:
8814    return EmitAtomicBit6432WithCustomInserter(MI, BB,
8815                                               X86::ADD32rr, X86::ADC32rr,
8816                                               X86::ADD32ri, X86::ADC32ri,
8817                                               false);
8818  case X86::ATOMSUB6432:
8819    return EmitAtomicBit6432WithCustomInserter(MI, BB,
8820                                               X86::SUB32rr, X86::SBB32rr,
8821                                               X86::SUB32ri, X86::SBB32ri,
8822                                               false);
8823  case X86::ATOMSWAP6432:
8824    return EmitAtomicBit6432WithCustomInserter(MI, BB,
8825                                               X86::MOV32rr, X86::MOV32rr,
8826                                               X86::MOV32ri, X86::MOV32ri,
8827                                               false);
8828  case X86::VASTART_SAVE_XMM_REGS:
8829    return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
8830  }
8831}
8832
8833//===----------------------------------------------------------------------===//
8834//                           X86 Optimization Hooks
8835//===----------------------------------------------------------------------===//
8836
8837void X86TargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
8838                                                       const APInt &Mask,
8839                                                       APInt &KnownZero,
8840                                                       APInt &KnownOne,
8841                                                       const SelectionDAG &DAG,
8842                                                       unsigned Depth) const {
8843  unsigned Opc = Op.getOpcode();
8844  assert((Opc >= ISD::BUILTIN_OP_END ||
8845          Opc == ISD::INTRINSIC_WO_CHAIN ||
8846          Opc == ISD::INTRINSIC_W_CHAIN ||
8847          Opc == ISD::INTRINSIC_VOID) &&
8848         "Should use MaskedValueIsZero if you don't know whether Op"
8849         " is a target node!");
8850
8851  KnownZero = KnownOne = APInt(Mask.getBitWidth(), 0);   // Don't know anything.
8852  switch (Opc) {
8853  default: break;
8854  case X86ISD::ADD:
8855  case X86ISD::SUB:
8856  case X86ISD::SMUL:
8857  case X86ISD::UMUL:
8858  case X86ISD::INC:
8859  case X86ISD::DEC:
8860  case X86ISD::OR:
8861  case X86ISD::XOR:
8862  case X86ISD::AND:
8863    // These nodes' second result is a boolean.
8864    if (Op.getResNo() == 0)
8865      break;
8866    // Fallthrough
8867  case X86ISD::SETCC:
8868    KnownZero |= APInt::getHighBitsSet(Mask.getBitWidth(),
8869                                       Mask.getBitWidth() - 1);
8870    break;
8871  }
8872}
8873
8874/// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
8875/// node is a GlobalAddress + offset.
8876bool X86TargetLowering::isGAPlusOffset(SDNode *N,
8877                                       GlobalValue* &GA, int64_t &Offset) const{
8878  if (N->getOpcode() == X86ISD::Wrapper) {
8879    if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
8880      GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
8881      Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
8882      return true;
8883    }
8884  }
8885  return TargetLowering::isGAPlusOffset(N, GA, Offset);
8886}
8887
8888/// PerformShuffleCombine - Combine a vector_shuffle that is equal to
8889/// build_vector load1, load2, load3, load4, <0, 1, 2, 3> into a 128-bit load
8890/// if the load addresses are consecutive, non-overlapping, and in the right
8891/// order.
8892static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
8893                                     const TargetLowering &TLI) {
8894  DebugLoc dl = N->getDebugLoc();
8895  EVT VT = N->getValueType(0);
8896  ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
8897
8898  if (VT.getSizeInBits() != 128)
8899    return SDValue();
8900
8901  SmallVector<SDValue, 16> Elts;
8902  for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
8903    Elts.push_back(DAG.getShuffleScalarElt(SVN, i));
8904
8905  return EltsFromConsecutiveLoads(VT, Elts, dl, DAG);
8906}
8907
8908/// PerformShuffleCombine - Detect vector gather/scatter index generation
8909/// and convert it from being a bunch of shuffles and extracts to a simple
8910/// store and scalar loads to extract the elements.
8911static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
8912                                                const TargetLowering &TLI) {
8913  SDValue InputVector = N->getOperand(0);
8914
8915  // Only operate on vectors of 4 elements, where the alternative shuffling
8916  // gets to be more expensive.
8917  if (InputVector.getValueType() != MVT::v4i32)
8918    return SDValue();
8919
8920  // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
8921  // single use which is a sign-extend or zero-extend, and all elements are
8922  // used.
8923  SmallVector<SDNode *, 4> Uses;
8924  unsigned ExtractedElements = 0;
8925  for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
8926       UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
8927    if (UI.getUse().getResNo() != InputVector.getResNo())
8928      return SDValue();
8929
8930    SDNode *Extract = *UI;
8931    if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
8932      return SDValue();
8933
8934    if (Extract->getValueType(0) != MVT::i32)
8935      return SDValue();
8936    if (!Extract->hasOneUse())
8937      return SDValue();
8938    if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
8939        Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
8940      return SDValue();
8941    if (!isa<ConstantSDNode>(Extract->getOperand(1)))
8942      return SDValue();
8943
8944    // Record which element was extracted.
8945    ExtractedElements |=
8946      1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
8947
8948    Uses.push_back(Extract);
8949  }
8950
8951  // If not all the elements were used, this may not be worthwhile.
8952  if (ExtractedElements != 15)
8953    return SDValue();
8954
8955  // Ok, we've now decided to do the transformation.
8956  DebugLoc dl = InputVector.getDebugLoc();
8957
8958  // Store the value to a temporary stack slot.
8959  SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
8960  SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr, NULL, 0,
8961                            false, false, 0);
8962
8963  // Replace each use (extract) with a load of the appropriate element.
8964  for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
8965       UE = Uses.end(); UI != UE; ++UI) {
8966    SDNode *Extract = *UI;
8967
8968    // Compute the element's address.
8969    SDValue Idx = Extract->getOperand(1);
8970    unsigned EltSize =
8971        InputVector.getValueType().getVectorElementType().getSizeInBits()/8;
8972    uint64_t Offset = EltSize * cast<ConstantSDNode>(Idx)->getZExtValue();
8973    SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy());
8974
8975    SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, Idx.getValueType(), OffsetVal, StackPtr);
8976
8977    // Load the scalar.
8978    SDValue LoadScalar = DAG.getLoad(Extract->getValueType(0), dl, Ch, ScalarAddr,
8979                          NULL, 0, false, false, 0);
8980
8981    // Replace the exact with the load.
8982    DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), LoadScalar);
8983  }
8984
8985  // The replacement was made in place; don't return anything.
8986  return SDValue();
8987}
8988
8989/// PerformSELECTCombine - Do target-specific dag combines on SELECT nodes.
8990static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
8991                                    const X86Subtarget *Subtarget) {
8992  DebugLoc DL = N->getDebugLoc();
8993  SDValue Cond = N->getOperand(0);
8994  // Get the LHS/RHS of the select.
8995  SDValue LHS = N->getOperand(1);
8996  SDValue RHS = N->getOperand(2);
8997
8998  // If we have SSE[12] support, try to form min/max nodes. SSE min/max
8999  // instructions match the semantics of the common C idiom x<y?x:y but not
9000  // x<=y?x:y, because of how they handle negative zero (which can be
9001  // ignored in unsafe-math mode).
9002  if (Subtarget->hasSSE2() &&
9003      (LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64) &&
9004      Cond.getOpcode() == ISD::SETCC) {
9005    ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
9006
9007    unsigned Opcode = 0;
9008    // Check for x CC y ? x : y.
9009    if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
9010        DAG.isEqualTo(RHS, Cond.getOperand(1))) {
9011      switch (CC) {
9012      default: break;
9013      case ISD::SETULT:
9014        // Converting this to a min would handle NaNs incorrectly, and swapping
9015        // the operands would cause it to handle comparisons between positive
9016        // and negative zero incorrectly.
9017        if (!FiniteOnlyFPMath() &&
9018            (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))) {
9019          if (!UnsafeFPMath &&
9020              !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
9021            break;
9022          std::swap(LHS, RHS);
9023        }
9024        Opcode = X86ISD::FMIN;
9025        break;
9026      case ISD::SETOLE:
9027        // Converting this to a min would handle comparisons between positive
9028        // and negative zero incorrectly.
9029        if (!UnsafeFPMath &&
9030            !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
9031          break;
9032        Opcode = X86ISD::FMIN;
9033        break;
9034      case ISD::SETULE:
9035        // Converting this to a min would handle both negative zeros and NaNs
9036        // incorrectly, but we can swap the operands to fix both.
9037        std::swap(LHS, RHS);
9038      case ISD::SETOLT:
9039      case ISD::SETLT:
9040      case ISD::SETLE:
9041        Opcode = X86ISD::FMIN;
9042        break;
9043
9044      case ISD::SETOGE:
9045        // Converting this to a max would handle comparisons between positive
9046        // and negative zero incorrectly.
9047        if (!UnsafeFPMath &&
9048            !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(LHS))
9049          break;
9050        Opcode = X86ISD::FMAX;
9051        break;
9052      case ISD::SETUGT:
9053        // Converting this to a max would handle NaNs incorrectly, and swapping
9054        // the operands would cause it to handle comparisons between positive
9055        // and negative zero incorrectly.
9056        if (!FiniteOnlyFPMath() &&
9057            (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))) {
9058          if (!UnsafeFPMath &&
9059              !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
9060            break;
9061          std::swap(LHS, RHS);
9062        }
9063        Opcode = X86ISD::FMAX;
9064        break;
9065      case ISD::SETUGE:
9066        // Converting this to a max would handle both negative zeros and NaNs
9067        // incorrectly, but we can swap the operands to fix both.
9068        std::swap(LHS, RHS);
9069      case ISD::SETOGT:
9070      case ISD::SETGT:
9071      case ISD::SETGE:
9072        Opcode = X86ISD::FMAX;
9073        break;
9074      }
9075    // Check for x CC y ? y : x -- a min/max with reversed arms.
9076    } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
9077               DAG.isEqualTo(RHS, Cond.getOperand(0))) {
9078      switch (CC) {
9079      default: break;
9080      case ISD::SETOGE:
9081        // Converting this to a min would handle comparisons between positive
9082        // and negative zero incorrectly, and swapping the operands would
9083        // cause it to handle NaNs incorrectly.
9084        if (!UnsafeFPMath &&
9085            !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
9086          if (!FiniteOnlyFPMath() &&
9087              (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
9088            break;
9089          std::swap(LHS, RHS);
9090        }
9091        Opcode = X86ISD::FMIN;
9092        break;
9093      case ISD::SETUGT:
9094        // Converting this to a min would handle NaNs incorrectly.
9095        if (!UnsafeFPMath &&
9096            (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
9097          break;
9098        Opcode = X86ISD::FMIN;
9099        break;
9100      case ISD::SETUGE:
9101        // Converting this to a min would handle both negative zeros and NaNs
9102        // incorrectly, but we can swap the operands to fix both.
9103        std::swap(LHS, RHS);
9104      case ISD::SETOGT:
9105      case ISD::SETGT:
9106      case ISD::SETGE:
9107        Opcode = X86ISD::FMIN;
9108        break;
9109
9110      case ISD::SETULT:
9111        // Converting this to a max would handle NaNs incorrectly.
9112        if (!FiniteOnlyFPMath() &&
9113            (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
9114          break;
9115        Opcode = X86ISD::FMAX;
9116        break;
9117      case ISD::SETOLE:
9118        // Converting this to a max would handle comparisons between positive
9119        // and negative zero incorrectly, and swapping the operands would
9120        // cause it to handle NaNs incorrectly.
9121        if (!UnsafeFPMath &&
9122            !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
9123          if (!FiniteOnlyFPMath() &&
9124              (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
9125            break;
9126          std::swap(LHS, RHS);
9127        }
9128        Opcode = X86ISD::FMAX;
9129        break;
9130      case ISD::SETULE:
9131        // Converting this to a max would handle both negative zeros and NaNs
9132        // incorrectly, but we can swap the operands to fix both.
9133        std::swap(LHS, RHS);
9134      case ISD::SETOLT:
9135      case ISD::SETLT:
9136      case ISD::SETLE:
9137        Opcode = X86ISD::FMAX;
9138        break;
9139      }
9140    }
9141
9142    if (Opcode)
9143      return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
9144  }
9145
9146  // If this is a select between two integer constants, try to do some
9147  // optimizations.
9148  if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
9149    if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
9150      // Don't do this for crazy integer types.
9151      if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
9152        // If this is efficiently invertible, canonicalize the LHSC/RHSC values
9153        // so that TrueC (the true value) is larger than FalseC.
9154        bool NeedsCondInvert = false;
9155
9156        if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
9157            // Efficiently invertible.
9158            (Cond.getOpcode() == ISD::SETCC ||  // setcc -> invertible.
9159             (Cond.getOpcode() == ISD::XOR &&   // xor(X, C) -> invertible.
9160              isa<ConstantSDNode>(Cond.getOperand(1))))) {
9161          NeedsCondInvert = true;
9162          std::swap(TrueC, FalseC);
9163        }
9164
9165        // Optimize C ? 8 : 0 -> zext(C) << 3.  Likewise for any pow2/0.
9166        if (FalseC->getAPIntValue() == 0 &&
9167            TrueC->getAPIntValue().isPowerOf2()) {
9168          if (NeedsCondInvert) // Invert the condition if needed.
9169            Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
9170                               DAG.getConstant(1, Cond.getValueType()));
9171
9172          // Zero extend the condition if needed.
9173          Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
9174
9175          unsigned ShAmt = TrueC->getAPIntValue().logBase2();
9176          return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
9177                             DAG.getConstant(ShAmt, MVT::i8));
9178        }
9179
9180        // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
9181        if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
9182          if (NeedsCondInvert) // Invert the condition if needed.
9183            Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
9184                               DAG.getConstant(1, Cond.getValueType()));
9185
9186          // Zero extend the condition if needed.
9187          Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
9188                             FalseC->getValueType(0), Cond);
9189          return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
9190                             SDValue(FalseC, 0));
9191        }
9192
9193        // Optimize cases that will turn into an LEA instruction.  This requires
9194        // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
9195        if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
9196          uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
9197          if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
9198
9199          bool isFastMultiplier = false;
9200          if (Diff < 10) {
9201            switch ((unsigned char)Diff) {
9202              default: break;
9203              case 1:  // result = add base, cond
9204              case 2:  // result = lea base(    , cond*2)
9205              case 3:  // result = lea base(cond, cond*2)
9206              case 4:  // result = lea base(    , cond*4)
9207              case 5:  // result = lea base(cond, cond*4)
9208              case 8:  // result = lea base(    , cond*8)
9209              case 9:  // result = lea base(cond, cond*8)
9210                isFastMultiplier = true;
9211                break;
9212            }
9213          }
9214
9215          if (isFastMultiplier) {
9216            APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
9217            if (NeedsCondInvert) // Invert the condition if needed.
9218              Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
9219                                 DAG.getConstant(1, Cond.getValueType()));
9220
9221            // Zero extend the condition if needed.
9222            Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
9223                               Cond);
9224            // Scale the condition by the difference.
9225            if (Diff != 1)
9226              Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
9227                                 DAG.getConstant(Diff, Cond.getValueType()));
9228
9229            // Add the base if non-zero.
9230            if (FalseC->getAPIntValue() != 0)
9231              Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
9232                                 SDValue(FalseC, 0));
9233            return Cond;
9234          }
9235        }
9236      }
9237  }
9238
9239  return SDValue();
9240}
9241
9242/// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
9243static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
9244                                  TargetLowering::DAGCombinerInfo &DCI) {
9245  DebugLoc DL = N->getDebugLoc();
9246
9247  // If the flag operand isn't dead, don't touch this CMOV.
9248  if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
9249    return SDValue();
9250
9251  // If this is a select between two integer constants, try to do some
9252  // optimizations.  Note that the operands are ordered the opposite of SELECT
9253  // operands.
9254  if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(N->getOperand(1))) {
9255    if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
9256      // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
9257      // larger than FalseC (the false value).
9258      X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
9259
9260      if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
9261        CC = X86::GetOppositeBranchCondition(CC);
9262        std::swap(TrueC, FalseC);
9263      }
9264
9265      // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3.  Likewise for any pow2/0.
9266      // This is efficient for any integer data type (including i8/i16) and
9267      // shift amount.
9268      if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
9269        SDValue Cond = N->getOperand(3);
9270        Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
9271                           DAG.getConstant(CC, MVT::i8), Cond);
9272
9273        // Zero extend the condition if needed.
9274        Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
9275
9276        unsigned ShAmt = TrueC->getAPIntValue().logBase2();
9277        Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
9278                           DAG.getConstant(ShAmt, MVT::i8));
9279        if (N->getNumValues() == 2)  // Dead flag value?
9280          return DCI.CombineTo(N, Cond, SDValue());
9281        return Cond;
9282      }
9283
9284      // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.  This is efficient
9285      // for any integer data type, including i8/i16.
9286      if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
9287        SDValue Cond = N->getOperand(3);
9288        Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
9289                           DAG.getConstant(CC, MVT::i8), Cond);
9290
9291        // Zero extend the condition if needed.
9292        Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
9293                           FalseC->getValueType(0), Cond);
9294        Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
9295                           SDValue(FalseC, 0));
9296
9297        if (N->getNumValues() == 2)  // Dead flag value?
9298          return DCI.CombineTo(N, Cond, SDValue());
9299        return Cond;
9300      }
9301
9302      // Optimize cases that will turn into an LEA instruction.  This requires
9303      // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
9304      if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
9305        uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
9306        if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
9307
9308        bool isFastMultiplier = false;
9309        if (Diff < 10) {
9310          switch ((unsigned char)Diff) {
9311          default: break;
9312          case 1:  // result = add base, cond
9313          case 2:  // result = lea base(    , cond*2)
9314          case 3:  // result = lea base(cond, cond*2)
9315          case 4:  // result = lea base(    , cond*4)
9316          case 5:  // result = lea base(cond, cond*4)
9317          case 8:  // result = lea base(    , cond*8)
9318          case 9:  // result = lea base(cond, cond*8)
9319            isFastMultiplier = true;
9320            break;
9321          }
9322        }
9323
9324        if (isFastMultiplier) {
9325          APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
9326          SDValue Cond = N->getOperand(3);
9327          Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
9328                             DAG.getConstant(CC, MVT::i8), Cond);
9329          // Zero extend the condition if needed.
9330          Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
9331                             Cond);
9332          // Scale the condition by the difference.
9333          if (Diff != 1)
9334            Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
9335                               DAG.getConstant(Diff, Cond.getValueType()));
9336
9337          // Add the base if non-zero.
9338          if (FalseC->getAPIntValue() != 0)
9339            Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
9340                               SDValue(FalseC, 0));
9341          if (N->getNumValues() == 2)  // Dead flag value?
9342            return DCI.CombineTo(N, Cond, SDValue());
9343          return Cond;
9344        }
9345      }
9346    }
9347  }
9348  return SDValue();
9349}
9350
9351
9352/// PerformMulCombine - Optimize a single multiply with constant into two
9353/// in order to implement it with two cheaper instructions, e.g.
9354/// LEA + SHL, LEA + LEA.
9355static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
9356                                 TargetLowering::DAGCombinerInfo &DCI) {
9357  if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
9358    return SDValue();
9359
9360  EVT VT = N->getValueType(0);
9361  if (VT != MVT::i64)
9362    return SDValue();
9363
9364  ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
9365  if (!C)
9366    return SDValue();
9367  uint64_t MulAmt = C->getZExtValue();
9368  if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
9369    return SDValue();
9370
9371  uint64_t MulAmt1 = 0;
9372  uint64_t MulAmt2 = 0;
9373  if ((MulAmt % 9) == 0) {
9374    MulAmt1 = 9;
9375    MulAmt2 = MulAmt / 9;
9376  } else if ((MulAmt % 5) == 0) {
9377    MulAmt1 = 5;
9378    MulAmt2 = MulAmt / 5;
9379  } else if ((MulAmt % 3) == 0) {
9380    MulAmt1 = 3;
9381    MulAmt2 = MulAmt / 3;
9382  }
9383  if (MulAmt2 &&
9384      (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
9385    DebugLoc DL = N->getDebugLoc();
9386
9387    if (isPowerOf2_64(MulAmt2) &&
9388        !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
9389      // If second multiplifer is pow2, issue it first. We want the multiply by
9390      // 3, 5, or 9 to be folded into the addressing mode unless the lone use
9391      // is an add.
9392      std::swap(MulAmt1, MulAmt2);
9393
9394    SDValue NewMul;
9395    if (isPowerOf2_64(MulAmt1))
9396      NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
9397                           DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
9398    else
9399      NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
9400                           DAG.getConstant(MulAmt1, VT));
9401
9402    if (isPowerOf2_64(MulAmt2))
9403      NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
9404                           DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
9405    else
9406      NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
9407                           DAG.getConstant(MulAmt2, VT));
9408
9409    // Do not add new nodes to DAG combiner worklist.
9410    DCI.CombineTo(N, NewMul, false);
9411  }
9412  return SDValue();
9413}
9414
9415static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
9416  SDValue N0 = N->getOperand(0);
9417  SDValue N1 = N->getOperand(1);
9418  ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
9419  EVT VT = N0.getValueType();
9420
9421  // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
9422  // since the result of setcc_c is all zero's or all ones.
9423  if (N1C && N0.getOpcode() == ISD::AND &&
9424      N0.getOperand(1).getOpcode() == ISD::Constant) {
9425    SDValue N00 = N0.getOperand(0);
9426    if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
9427        ((N00.getOpcode() == ISD::ANY_EXTEND ||
9428          N00.getOpcode() == ISD::ZERO_EXTEND) &&
9429         N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
9430      APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
9431      APInt ShAmt = N1C->getAPIntValue();
9432      Mask = Mask.shl(ShAmt);
9433      if (Mask != 0)
9434        return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
9435                           N00, DAG.getConstant(Mask, VT));
9436    }
9437  }
9438
9439  return SDValue();
9440}
9441
9442/// PerformShiftCombine - Transforms vector shift nodes to use vector shifts
9443///                       when possible.
9444static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
9445                                   const X86Subtarget *Subtarget) {
9446  EVT VT = N->getValueType(0);
9447  if (!VT.isVector() && VT.isInteger() &&
9448      N->getOpcode() == ISD::SHL)
9449    return PerformSHLCombine(N, DAG);
9450
9451  // On X86 with SSE2 support, we can transform this to a vector shift if
9452  // all elements are shifted by the same amount.  We can't do this in legalize
9453  // because the a constant vector is typically transformed to a constant pool
9454  // so we have no knowledge of the shift amount.
9455  if (!Subtarget->hasSSE2())
9456    return SDValue();
9457
9458  if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16)
9459    return SDValue();
9460
9461  SDValue ShAmtOp = N->getOperand(1);
9462  EVT EltVT = VT.getVectorElementType();
9463  DebugLoc DL = N->getDebugLoc();
9464  SDValue BaseShAmt = SDValue();
9465  if (ShAmtOp.getOpcode() == ISD::BUILD_VECTOR) {
9466    unsigned NumElts = VT.getVectorNumElements();
9467    unsigned i = 0;
9468    for (; i != NumElts; ++i) {
9469      SDValue Arg = ShAmtOp.getOperand(i);
9470      if (Arg.getOpcode() == ISD::UNDEF) continue;
9471      BaseShAmt = Arg;
9472      break;
9473    }
9474    for (; i != NumElts; ++i) {
9475      SDValue Arg = ShAmtOp.getOperand(i);
9476      if (Arg.getOpcode() == ISD::UNDEF) continue;
9477      if (Arg != BaseShAmt) {
9478        return SDValue();
9479      }
9480    }
9481  } else if (ShAmtOp.getOpcode() == ISD::VECTOR_SHUFFLE &&
9482             cast<ShuffleVectorSDNode>(ShAmtOp)->isSplat()) {
9483    SDValue InVec = ShAmtOp.getOperand(0);
9484    if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
9485      unsigned NumElts = InVec.getValueType().getVectorNumElements();
9486      unsigned i = 0;
9487      for (; i != NumElts; ++i) {
9488        SDValue Arg = InVec.getOperand(i);
9489        if (Arg.getOpcode() == ISD::UNDEF) continue;
9490        BaseShAmt = Arg;
9491        break;
9492      }
9493    } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
9494       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
9495         unsigned SplatIdx= cast<ShuffleVectorSDNode>(ShAmtOp)->getSplatIndex();
9496         if (C->getZExtValue() == SplatIdx)
9497           BaseShAmt = InVec.getOperand(1);
9498       }
9499    }
9500    if (BaseShAmt.getNode() == 0)
9501      BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, ShAmtOp,
9502                              DAG.getIntPtrConstant(0));
9503  } else
9504    return SDValue();
9505
9506  // The shift amount is an i32.
9507  if (EltVT.bitsGT(MVT::i32))
9508    BaseShAmt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, BaseShAmt);
9509  else if (EltVT.bitsLT(MVT::i32))
9510    BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, BaseShAmt);
9511
9512  // The shift amount is identical so we can do a vector shift.
9513  SDValue  ValOp = N->getOperand(0);
9514  switch (N->getOpcode()) {
9515  default:
9516    llvm_unreachable("Unknown shift opcode!");
9517    break;
9518  case ISD::SHL:
9519    if (VT == MVT::v2i64)
9520      return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
9521                         DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
9522                         ValOp, BaseShAmt);
9523    if (VT == MVT::v4i32)
9524      return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
9525                         DAG.getConstant(Intrinsic::x86_sse2_pslli_d, MVT::i32),
9526                         ValOp, BaseShAmt);
9527    if (VT == MVT::v8i16)
9528      return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
9529                         DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32),
9530                         ValOp, BaseShAmt);
9531    break;
9532  case ISD::SRA:
9533    if (VT == MVT::v4i32)
9534      return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
9535                         DAG.getConstant(Intrinsic::x86_sse2_psrai_d, MVT::i32),
9536                         ValOp, BaseShAmt);
9537    if (VT == MVT::v8i16)
9538      return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
9539                         DAG.getConstant(Intrinsic::x86_sse2_psrai_w, MVT::i32),
9540                         ValOp, BaseShAmt);
9541    break;
9542  case ISD::SRL:
9543    if (VT == MVT::v2i64)
9544      return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
9545                         DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
9546                         ValOp, BaseShAmt);
9547    if (VT == MVT::v4i32)
9548      return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
9549                         DAG.getConstant(Intrinsic::x86_sse2_psrli_d, MVT::i32),
9550                         ValOp, BaseShAmt);
9551    if (VT ==  MVT::v8i16)
9552      return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
9553                         DAG.getConstant(Intrinsic::x86_sse2_psrli_w, MVT::i32),
9554                         ValOp, BaseShAmt);
9555    break;
9556  }
9557  return SDValue();
9558}
9559
9560static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
9561                                const X86Subtarget *Subtarget) {
9562  EVT VT = N->getValueType(0);
9563  if (VT != MVT::i64 || !Subtarget->is64Bit())
9564    return SDValue();
9565
9566  // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
9567  SDValue N0 = N->getOperand(0);
9568  SDValue N1 = N->getOperand(1);
9569  if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
9570    std::swap(N0, N1);
9571  if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
9572    return SDValue();
9573
9574  SDValue ShAmt0 = N0.getOperand(1);
9575  if (ShAmt0.getValueType() != MVT::i8)
9576    return SDValue();
9577  SDValue ShAmt1 = N1.getOperand(1);
9578  if (ShAmt1.getValueType() != MVT::i8)
9579    return SDValue();
9580  if (ShAmt0.getOpcode() == ISD::TRUNCATE)
9581    ShAmt0 = ShAmt0.getOperand(0);
9582  if (ShAmt1.getOpcode() == ISD::TRUNCATE)
9583    ShAmt1 = ShAmt1.getOperand(0);
9584
9585  DebugLoc DL = N->getDebugLoc();
9586  unsigned Opc = X86ISD::SHLD;
9587  SDValue Op0 = N0.getOperand(0);
9588  SDValue Op1 = N1.getOperand(0);
9589  if (ShAmt0.getOpcode() == ISD::SUB) {
9590    Opc = X86ISD::SHRD;
9591    std::swap(Op0, Op1);
9592    std::swap(ShAmt0, ShAmt1);
9593  }
9594
9595  if (ShAmt1.getOpcode() == ISD::SUB) {
9596    SDValue Sum = ShAmt1.getOperand(0);
9597    if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
9598      if (SumC->getSExtValue() == 64 &&
9599          ShAmt1.getOperand(1) == ShAmt0)
9600        return DAG.getNode(Opc, DL, VT,
9601                           Op0, Op1,
9602                           DAG.getNode(ISD::TRUNCATE, DL,
9603                                       MVT::i8, ShAmt0));
9604    }
9605  } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
9606    ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
9607    if (ShAmt0C &&
9608        ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == 64)
9609      return DAG.getNode(Opc, DL, VT,
9610                         N0.getOperand(0), N1.getOperand(0),
9611                         DAG.getNode(ISD::TRUNCATE, DL,
9612                                       MVT::i8, ShAmt0));
9613  }
9614
9615  return SDValue();
9616}
9617
9618/// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
9619static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
9620                                   const X86Subtarget *Subtarget) {
9621  // Turn load->store of MMX types into GPR load/stores.  This avoids clobbering
9622  // the FP state in cases where an emms may be missing.
9623  // A preferable solution to the general problem is to figure out the right
9624  // places to insert EMMS.  This qualifies as a quick hack.
9625
9626  // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
9627  StoreSDNode *St = cast<StoreSDNode>(N);
9628  EVT VT = St->getValue().getValueType();
9629  if (VT.getSizeInBits() != 64)
9630    return SDValue();
9631
9632  const Function *F = DAG.getMachineFunction().getFunction();
9633  bool NoImplicitFloatOps = F->hasFnAttr(Attribute::NoImplicitFloat);
9634  bool F64IsLegal = !UseSoftFloat && !NoImplicitFloatOps
9635    && Subtarget->hasSSE2();
9636  if ((VT.isVector() ||
9637       (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
9638      isa<LoadSDNode>(St->getValue()) &&
9639      !cast<LoadSDNode>(St->getValue())->isVolatile() &&
9640      St->getChain().hasOneUse() && !St->isVolatile()) {
9641    SDNode* LdVal = St->getValue().getNode();
9642    LoadSDNode *Ld = 0;
9643    int TokenFactorIndex = -1;
9644    SmallVector<SDValue, 8> Ops;
9645    SDNode* ChainVal = St->getChain().getNode();
9646    // Must be a store of a load.  We currently handle two cases:  the load
9647    // is a direct child, and it's under an intervening TokenFactor.  It is
9648    // possible to dig deeper under nested TokenFactors.
9649    if (ChainVal == LdVal)
9650      Ld = cast<LoadSDNode>(St->getChain());
9651    else if (St->getValue().hasOneUse() &&
9652             ChainVal->getOpcode() == ISD::TokenFactor) {
9653      for (unsigned i=0, e = ChainVal->getNumOperands(); i != e; ++i) {
9654        if (ChainVal->getOperand(i).getNode() == LdVal) {
9655          TokenFactorIndex = i;
9656          Ld = cast<LoadSDNode>(St->getValue());
9657        } else
9658          Ops.push_back(ChainVal->getOperand(i));
9659      }
9660    }
9661
9662    if (!Ld || !ISD::isNormalLoad(Ld))
9663      return SDValue();
9664
9665    // If this is not the MMX case, i.e. we are just turning i64 load/store
9666    // into f64 load/store, avoid the transformation if there are multiple
9667    // uses of the loaded value.
9668    if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
9669      return SDValue();
9670
9671    DebugLoc LdDL = Ld->getDebugLoc();
9672    DebugLoc StDL = N->getDebugLoc();
9673    // If we are a 64-bit capable x86, lower to a single movq load/store pair.
9674    // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
9675    // pair instead.
9676    if (Subtarget->is64Bit() || F64IsLegal) {
9677      EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
9678      SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(),
9679                                  Ld->getBasePtr(), Ld->getSrcValue(),
9680                                  Ld->getSrcValueOffset(), Ld->isVolatile(),
9681                                  Ld->isNonTemporal(), Ld->getAlignment());
9682      SDValue NewChain = NewLd.getValue(1);
9683      if (TokenFactorIndex != -1) {
9684        Ops.push_back(NewChain);
9685        NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
9686                               Ops.size());
9687      }
9688      return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
9689                          St->getSrcValue(), St->getSrcValueOffset(),
9690                          St->isVolatile(), St->isNonTemporal(),
9691                          St->getAlignment());
9692    }
9693
9694    // Otherwise, lower to two pairs of 32-bit loads / stores.
9695    SDValue LoAddr = Ld->getBasePtr();
9696    SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
9697                                 DAG.getConstant(4, MVT::i32));
9698
9699    SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
9700                               Ld->getSrcValue(), Ld->getSrcValueOffset(),
9701                               Ld->isVolatile(), Ld->isNonTemporal(),
9702                               Ld->getAlignment());
9703    SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
9704                               Ld->getSrcValue(), Ld->getSrcValueOffset()+4,
9705                               Ld->isVolatile(), Ld->isNonTemporal(),
9706                               MinAlign(Ld->getAlignment(), 4));
9707
9708    SDValue NewChain = LoLd.getValue(1);
9709    if (TokenFactorIndex != -1) {
9710      Ops.push_back(LoLd);
9711      Ops.push_back(HiLd);
9712      NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
9713                             Ops.size());
9714    }
9715
9716    LoAddr = St->getBasePtr();
9717    HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
9718                         DAG.getConstant(4, MVT::i32));
9719
9720    SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
9721                                St->getSrcValue(), St->getSrcValueOffset(),
9722                                St->isVolatile(), St->isNonTemporal(),
9723                                St->getAlignment());
9724    SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
9725                                St->getSrcValue(),
9726                                St->getSrcValueOffset() + 4,
9727                                St->isVolatile(),
9728                                St->isNonTemporal(),
9729                                MinAlign(St->getAlignment(), 4));
9730    return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
9731  }
9732  return SDValue();
9733}
9734
9735/// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
9736/// X86ISD::FXOR nodes.
9737static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
9738  assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
9739  // F[X]OR(0.0, x) -> x
9740  // F[X]OR(x, 0.0) -> x
9741  if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
9742    if (C->getValueAPF().isPosZero())
9743      return N->getOperand(1);
9744  if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
9745    if (C->getValueAPF().isPosZero())
9746      return N->getOperand(0);
9747  return SDValue();
9748}
9749
9750/// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
9751static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
9752  // FAND(0.0, x) -> 0.0
9753  // FAND(x, 0.0) -> 0.0
9754  if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
9755    if (C->getValueAPF().isPosZero())
9756      return N->getOperand(0);
9757  if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
9758    if (C->getValueAPF().isPosZero())
9759      return N->getOperand(1);
9760  return SDValue();
9761}
9762
9763static SDValue PerformBTCombine(SDNode *N,
9764                                SelectionDAG &DAG,
9765                                TargetLowering::DAGCombinerInfo &DCI) {
9766  // BT ignores high bits in the bit index operand.
9767  SDValue Op1 = N->getOperand(1);
9768  if (Op1.hasOneUse()) {
9769    unsigned BitWidth = Op1.getValueSizeInBits();
9770    APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
9771    APInt KnownZero, KnownOne;
9772    TargetLowering::TargetLoweringOpt TLO(DAG);
9773    TargetLowering &TLI = DAG.getTargetLoweringInfo();
9774    if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
9775        TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
9776      DCI.CommitTargetLoweringOpt(TLO);
9777  }
9778  return SDValue();
9779}
9780
9781static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
9782  SDValue Op = N->getOperand(0);
9783  if (Op.getOpcode() == ISD::BIT_CONVERT)
9784    Op = Op.getOperand(0);
9785  EVT VT = N->getValueType(0), OpVT = Op.getValueType();
9786  if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
9787      VT.getVectorElementType().getSizeInBits() ==
9788      OpVT.getVectorElementType().getSizeInBits()) {
9789    return DAG.getNode(ISD::BIT_CONVERT, N->getDebugLoc(), VT, Op);
9790  }
9791  return SDValue();
9792}
9793
9794// On X86 and X86-64, atomic operations are lowered to locked instructions.
9795// Locked instructions, in turn, have implicit fence semantics (all memory
9796// operations are flushed before issuing the locked instruction, and the
9797// are not buffered), so we can fold away the common pattern of
9798// fence-atomic-fence.
9799static SDValue PerformMEMBARRIERCombine(SDNode* N, SelectionDAG &DAG) {
9800  SDValue atomic = N->getOperand(0);
9801  switch (atomic.getOpcode()) {
9802    case ISD::ATOMIC_CMP_SWAP:
9803    case ISD::ATOMIC_SWAP:
9804    case ISD::ATOMIC_LOAD_ADD:
9805    case ISD::ATOMIC_LOAD_SUB:
9806    case ISD::ATOMIC_LOAD_AND:
9807    case ISD::ATOMIC_LOAD_OR:
9808    case ISD::ATOMIC_LOAD_XOR:
9809    case ISD::ATOMIC_LOAD_NAND:
9810    case ISD::ATOMIC_LOAD_MIN:
9811    case ISD::ATOMIC_LOAD_MAX:
9812    case ISD::ATOMIC_LOAD_UMIN:
9813    case ISD::ATOMIC_LOAD_UMAX:
9814      break;
9815    default:
9816      return SDValue();
9817  }
9818
9819  SDValue fence = atomic.getOperand(0);
9820  if (fence.getOpcode() != ISD::MEMBARRIER)
9821    return SDValue();
9822
9823  switch (atomic.getOpcode()) {
9824    case ISD::ATOMIC_CMP_SWAP:
9825      return DAG.UpdateNodeOperands(atomic, fence.getOperand(0),
9826                                    atomic.getOperand(1), atomic.getOperand(2),
9827                                    atomic.getOperand(3));
9828    case ISD::ATOMIC_SWAP:
9829    case ISD::ATOMIC_LOAD_ADD:
9830    case ISD::ATOMIC_LOAD_SUB:
9831    case ISD::ATOMIC_LOAD_AND:
9832    case ISD::ATOMIC_LOAD_OR:
9833    case ISD::ATOMIC_LOAD_XOR:
9834    case ISD::ATOMIC_LOAD_NAND:
9835    case ISD::ATOMIC_LOAD_MIN:
9836    case ISD::ATOMIC_LOAD_MAX:
9837    case ISD::ATOMIC_LOAD_UMIN:
9838    case ISD::ATOMIC_LOAD_UMAX:
9839      return DAG.UpdateNodeOperands(atomic, fence.getOperand(0),
9840                                    atomic.getOperand(1), atomic.getOperand(2));
9841    default:
9842      return SDValue();
9843  }
9844}
9845
9846static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG) {
9847  // (i32 zext (and (i8  x86isd::setcc_carry), 1)) ->
9848  //           (and (i32 x86isd::setcc_carry), 1)
9849  // This eliminates the zext. This transformation is necessary because
9850  // ISD::SETCC is always legalized to i8.
9851  DebugLoc dl = N->getDebugLoc();
9852  SDValue N0 = N->getOperand(0);
9853  EVT VT = N->getValueType(0);
9854  if (N0.getOpcode() == ISD::AND &&
9855      N0.hasOneUse() &&
9856      N0.getOperand(0).hasOneUse()) {
9857    SDValue N00 = N0.getOperand(0);
9858    if (N00.getOpcode() != X86ISD::SETCC_CARRY)
9859      return SDValue();
9860    ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
9861    if (!C || C->getZExtValue() != 1)
9862      return SDValue();
9863    return DAG.getNode(ISD::AND, dl, VT,
9864                       DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
9865                                   N00.getOperand(0), N00.getOperand(1)),
9866                       DAG.getConstant(1, VT));
9867  }
9868
9869  return SDValue();
9870}
9871
9872SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
9873                                             DAGCombinerInfo &DCI) const {
9874  SelectionDAG &DAG = DCI.DAG;
9875  switch (N->getOpcode()) {
9876  default: break;
9877  case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, *this);
9878  case ISD::EXTRACT_VECTOR_ELT:
9879                        return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, *this);
9880  case ISD::SELECT:         return PerformSELECTCombine(N, DAG, Subtarget);
9881  case X86ISD::CMOV:        return PerformCMOVCombine(N, DAG, DCI);
9882  case ISD::MUL:            return PerformMulCombine(N, DAG, DCI);
9883  case ISD::SHL:
9884  case ISD::SRA:
9885  case ISD::SRL:            return PerformShiftCombine(N, DAG, Subtarget);
9886  case ISD::OR:             return PerformOrCombine(N, DAG, Subtarget);
9887  case ISD::STORE:          return PerformSTORECombine(N, DAG, Subtarget);
9888  case X86ISD::FXOR:
9889  case X86ISD::FOR:         return PerformFORCombine(N, DAG);
9890  case X86ISD::FAND:        return PerformFANDCombine(N, DAG);
9891  case X86ISD::BT:          return PerformBTCombine(N, DAG, DCI);
9892  case X86ISD::VZEXT_MOVL:  return PerformVZEXT_MOVLCombine(N, DAG);
9893  case ISD::MEMBARRIER:     return PerformMEMBARRIERCombine(N, DAG);
9894  case ISD::ZERO_EXTEND:    return PerformZExtCombine(N, DAG);
9895  }
9896
9897  return SDValue();
9898}
9899
9900//===----------------------------------------------------------------------===//
9901//                           X86 Inline Assembly Support
9902//===----------------------------------------------------------------------===//
9903
9904static bool LowerToBSwap(CallInst *CI) {
9905  // FIXME: this should verify that we are targetting a 486 or better.  If not,
9906  // we will turn this bswap into something that will be lowered to logical ops
9907  // instead of emitting the bswap asm.  For now, we don't support 486 or lower
9908  // so don't worry about this.
9909
9910  // Verify this is a simple bswap.
9911  if (CI->getNumOperands() != 2 ||
9912      CI->getType() != CI->getOperand(1)->getType() ||
9913      !CI->getType()->isIntegerTy())
9914    return false;
9915
9916  const IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
9917  if (!Ty || Ty->getBitWidth() % 16 != 0)
9918    return false;
9919
9920  // Okay, we can do this xform, do so now.
9921  const Type *Tys[] = { Ty };
9922  Module *M = CI->getParent()->getParent()->getParent();
9923  Constant *Int = Intrinsic::getDeclaration(M, Intrinsic::bswap, Tys, 1);
9924
9925  Value *Op = CI->getOperand(1);
9926  Op = CallInst::Create(Int, Op, CI->getName(), CI);
9927
9928  CI->replaceAllUsesWith(Op);
9929  CI->eraseFromParent();
9930  return true;
9931}
9932
9933bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
9934  InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
9935  std::vector<InlineAsm::ConstraintInfo> Constraints = IA->ParseConstraints();
9936
9937  std::string AsmStr = IA->getAsmString();
9938
9939  // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
9940  SmallVector<StringRef, 4> AsmPieces;
9941  SplitString(AsmStr, AsmPieces, "\n");  // ; as separator?
9942
9943  switch (AsmPieces.size()) {
9944  default: return false;
9945  case 1:
9946    AsmStr = AsmPieces[0];
9947    AsmPieces.clear();
9948    SplitString(AsmStr, AsmPieces, " \t");  // Split with whitespace.
9949
9950    // bswap $0
9951    if (AsmPieces.size() == 2 &&
9952        (AsmPieces[0] == "bswap" ||
9953         AsmPieces[0] == "bswapq" ||
9954         AsmPieces[0] == "bswapl") &&
9955        (AsmPieces[1] == "$0" ||
9956         AsmPieces[1] == "${0:q}")) {
9957      // No need to check constraints, nothing other than the equivalent of
9958      // "=r,0" would be valid here.
9959      return LowerToBSwap(CI);
9960    }
9961    // rorw $$8, ${0:w}  -->  llvm.bswap.i16
9962    if (CI->getType()->isIntegerTy(16) &&
9963        AsmPieces.size() == 3 &&
9964        (AsmPieces[0] == "rorw" || AsmPieces[0] == "rolw") &&
9965        AsmPieces[1] == "$$8," &&
9966        AsmPieces[2] == "${0:w}" &&
9967        IA->getConstraintString().compare(0, 5, "=r,0,") == 0) {
9968      AsmPieces.clear();
9969      const std::string &Constraints = IA->getConstraintString();
9970      SplitString(StringRef(Constraints).substr(5), AsmPieces, ",");
9971      std::sort(AsmPieces.begin(), AsmPieces.end());
9972      if (AsmPieces.size() == 4 &&
9973          AsmPieces[0] == "~{cc}" &&
9974          AsmPieces[1] == "~{dirflag}" &&
9975          AsmPieces[2] == "~{flags}" &&
9976          AsmPieces[3] == "~{fpsr}") {
9977        return LowerToBSwap(CI);
9978      }
9979    }
9980    break;
9981  case 3:
9982    if (CI->getType()->isIntegerTy(64) &&
9983        Constraints.size() >= 2 &&
9984        Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
9985        Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
9986      // bswap %eax / bswap %edx / xchgl %eax, %edx  -> llvm.bswap.i64
9987      SmallVector<StringRef, 4> Words;
9988      SplitString(AsmPieces[0], Words, " \t");
9989      if (Words.size() == 2 && Words[0] == "bswap" && Words[1] == "%eax") {
9990        Words.clear();
9991        SplitString(AsmPieces[1], Words, " \t");
9992        if (Words.size() == 2 && Words[0] == "bswap" && Words[1] == "%edx") {
9993          Words.clear();
9994          SplitString(AsmPieces[2], Words, " \t,");
9995          if (Words.size() == 3 && Words[0] == "xchgl" && Words[1] == "%eax" &&
9996              Words[2] == "%edx") {
9997            return LowerToBSwap(CI);
9998          }
9999        }
10000      }
10001    }
10002    break;
10003  }
10004  return false;
10005}
10006
10007
10008
10009/// getConstraintType - Given a constraint letter, return the type of
10010/// constraint it is for this target.
10011X86TargetLowering::ConstraintType
10012X86TargetLowering::getConstraintType(const std::string &Constraint) const {
10013  if (Constraint.size() == 1) {
10014    switch (Constraint[0]) {
10015    case 'A':
10016      return C_Register;
10017    case 'f':
10018    case 'r':
10019    case 'R':
10020    case 'l':
10021    case 'q':
10022    case 'Q':
10023    case 'x':
10024    case 'y':
10025    case 'Y':
10026      return C_RegisterClass;
10027    case 'e':
10028    case 'Z':
10029      return C_Other;
10030    default:
10031      break;
10032    }
10033  }
10034  return TargetLowering::getConstraintType(Constraint);
10035}
10036
10037/// LowerXConstraint - try to replace an X constraint, which matches anything,
10038/// with another that has more specific requirements based on the type of the
10039/// corresponding operand.
10040const char *X86TargetLowering::
10041LowerXConstraint(EVT ConstraintVT) const {
10042  // FP X constraints get lowered to SSE1/2 registers if available, otherwise
10043  // 'f' like normal targets.
10044  if (ConstraintVT.isFloatingPoint()) {
10045    if (Subtarget->hasSSE2())
10046      return "Y";
10047    if (Subtarget->hasSSE1())
10048      return "x";
10049  }
10050
10051  return TargetLowering::LowerXConstraint(ConstraintVT);
10052}
10053
10054/// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
10055/// vector.  If it is invalid, don't add anything to Ops.
10056void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
10057                                                     char Constraint,
10058                                                     bool hasMemory,
10059                                                     std::vector<SDValue>&Ops,
10060                                                     SelectionDAG &DAG) const {
10061  SDValue Result(0, 0);
10062
10063  switch (Constraint) {
10064  default: break;
10065  case 'I':
10066    if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
10067      if (C->getZExtValue() <= 31) {
10068        Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
10069        break;
10070      }
10071    }
10072    return;
10073  case 'J':
10074    if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
10075      if (C->getZExtValue() <= 63) {
10076        Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
10077        break;
10078      }
10079    }
10080    return;
10081  case 'K':
10082    if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
10083      if ((int8_t)C->getSExtValue() == C->getSExtValue()) {
10084        Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
10085        break;
10086      }
10087    }
10088    return;
10089  case 'N':
10090    if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
10091      if (C->getZExtValue() <= 255) {
10092        Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
10093        break;
10094      }
10095    }
10096    return;
10097  case 'e': {
10098    // 32-bit signed value
10099    if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
10100      const ConstantInt *CI = C->getConstantIntValue();
10101      if (CI->isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
10102                                  C->getSExtValue())) {
10103        // Widen to 64 bits here to get it sign extended.
10104        Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
10105        break;
10106      }
10107    // FIXME gcc accepts some relocatable values here too, but only in certain
10108    // memory models; it's complicated.
10109    }
10110    return;
10111  }
10112  case 'Z': {
10113    // 32-bit unsigned value
10114    if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
10115      const ConstantInt *CI = C->getConstantIntValue();
10116      if (CI->isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
10117                                  C->getZExtValue())) {
10118        Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
10119        break;
10120      }
10121    }
10122    // FIXME gcc accepts some relocatable values here too, but only in certain
10123    // memory models; it's complicated.
10124    return;
10125  }
10126  case 'i': {
10127    // Literal immediates are always ok.
10128    if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
10129      // Widen to 64 bits here to get it sign extended.
10130      Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
10131      break;
10132    }
10133
10134    // If we are in non-pic codegen mode, we allow the address of a global (with
10135    // an optional displacement) to be used with 'i'.
10136    GlobalAddressSDNode *GA = 0;
10137    int64_t Offset = 0;
10138
10139    // Match either (GA), (GA+C), (GA+C1+C2), etc.
10140    while (1) {
10141      if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
10142        Offset += GA->getOffset();
10143        break;
10144      } else if (Op.getOpcode() == ISD::ADD) {
10145        if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
10146          Offset += C->getZExtValue();
10147          Op = Op.getOperand(0);
10148          continue;
10149        }
10150      } else if (Op.getOpcode() == ISD::SUB) {
10151        if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
10152          Offset += -C->getZExtValue();
10153          Op = Op.getOperand(0);
10154          continue;
10155        }
10156      }
10157
10158      // Otherwise, this isn't something we can handle, reject it.
10159      return;
10160    }
10161
10162    GlobalValue *GV = GA->getGlobal();
10163    // If we require an extra load to get this address, as in PIC mode, we
10164    // can't accept it.
10165    if (isGlobalStubReference(Subtarget->ClassifyGlobalReference(GV,
10166                                                        getTargetMachine())))
10167      return;
10168
10169    if (hasMemory)
10170      Op = LowerGlobalAddress(GV, Op.getDebugLoc(), Offset, DAG);
10171    else
10172      Op = DAG.getTargetGlobalAddress(GV, GA->getValueType(0), Offset);
10173    Result = Op;
10174    break;
10175  }
10176  }
10177
10178  if (Result.getNode()) {
10179    Ops.push_back(Result);
10180    return;
10181  }
10182  return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, hasMemory,
10183                                                      Ops, DAG);
10184}
10185
10186std::vector<unsigned> X86TargetLowering::
10187getRegClassForInlineAsmConstraint(const std::string &Constraint,
10188                                  EVT VT) const {
10189  if (Constraint.size() == 1) {
10190    // FIXME: not handling fp-stack yet!
10191    switch (Constraint[0]) {      // GCC X86 Constraint Letters
10192    default: break;  // Unknown constraint letter
10193    case 'q':   // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
10194      if (Subtarget->is64Bit()) {
10195        if (VT == MVT::i32)
10196          return make_vector<unsigned>(X86::EAX, X86::EDX, X86::ECX, X86::EBX,
10197                                       X86::ESI, X86::EDI, X86::R8D, X86::R9D,
10198                                       X86::R10D,X86::R11D,X86::R12D,
10199                                       X86::R13D,X86::R14D,X86::R15D,
10200                                       X86::EBP, X86::ESP, 0);
10201        else if (VT == MVT::i16)
10202          return make_vector<unsigned>(X86::AX,  X86::DX,  X86::CX, X86::BX,
10203                                       X86::SI,  X86::DI,  X86::R8W,X86::R9W,
10204                                       X86::R10W,X86::R11W,X86::R12W,
10205                                       X86::R13W,X86::R14W,X86::R15W,
10206                                       X86::BP,  X86::SP, 0);
10207        else if (VT == MVT::i8)
10208          return make_vector<unsigned>(X86::AL,  X86::DL,  X86::CL, X86::BL,
10209                                       X86::SIL, X86::DIL, X86::R8B,X86::R9B,
10210                                       X86::R10B,X86::R11B,X86::R12B,
10211                                       X86::R13B,X86::R14B,X86::R15B,
10212                                       X86::BPL, X86::SPL, 0);
10213
10214        else if (VT == MVT::i64)
10215          return make_vector<unsigned>(X86::RAX, X86::RDX, X86::RCX, X86::RBX,
10216                                       X86::RSI, X86::RDI, X86::R8,  X86::R9,
10217                                       X86::R10, X86::R11, X86::R12,
10218                                       X86::R13, X86::R14, X86::R15,
10219                                       X86::RBP, X86::RSP, 0);
10220
10221        break;
10222      }
10223      // 32-bit fallthrough
10224    case 'Q':   // Q_REGS
10225      if (VT == MVT::i32)
10226        return make_vector<unsigned>(X86::EAX, X86::EDX, X86::ECX, X86::EBX, 0);
10227      else if (VT == MVT::i16)
10228        return make_vector<unsigned>(X86::AX, X86::DX, X86::CX, X86::BX, 0);
10229      else if (VT == MVT::i8)
10230        return make_vector<unsigned>(X86::AL, X86::DL, X86::CL, X86::BL, 0);
10231      else if (VT == MVT::i64)
10232        return make_vector<unsigned>(X86::RAX, X86::RDX, X86::RCX, X86::RBX, 0);
10233      break;
10234    }
10235  }
10236
10237  return std::vector<unsigned>();
10238}
10239
10240std::pair<unsigned, const TargetRegisterClass*>
10241X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
10242                                                EVT VT) const {
10243  // First, see if this is a constraint that directly corresponds to an LLVM
10244  // register class.
10245  if (Constraint.size() == 1) {
10246    // GCC Constraint Letters
10247    switch (Constraint[0]) {
10248    default: break;
10249    case 'r':   // GENERAL_REGS
10250    case 'l':   // INDEX_REGS
10251      if (VT == MVT::i8)
10252        return std::make_pair(0U, X86::GR8RegisterClass);
10253      if (VT == MVT::i16)
10254        return std::make_pair(0U, X86::GR16RegisterClass);
10255      if (VT == MVT::i32 || !Subtarget->is64Bit())
10256        return std::make_pair(0U, X86::GR32RegisterClass);
10257      return std::make_pair(0U, X86::GR64RegisterClass);
10258    case 'R':   // LEGACY_REGS
10259      if (VT == MVT::i8)
10260        return std::make_pair(0U, X86::GR8_NOREXRegisterClass);
10261      if (VT == MVT::i16)
10262        return std::make_pair(0U, X86::GR16_NOREXRegisterClass);
10263      if (VT == MVT::i32 || !Subtarget->is64Bit())
10264        return std::make_pair(0U, X86::GR32_NOREXRegisterClass);
10265      return std::make_pair(0U, X86::GR64_NOREXRegisterClass);
10266    case 'f':  // FP Stack registers.
10267      // If SSE is enabled for this VT, use f80 to ensure the isel moves the
10268      // value to the correct fpstack register class.
10269      if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
10270        return std::make_pair(0U, X86::RFP32RegisterClass);
10271      if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
10272        return std::make_pair(0U, X86::RFP64RegisterClass);
10273      return std::make_pair(0U, X86::RFP80RegisterClass);
10274    case 'y':   // MMX_REGS if MMX allowed.
10275      if (!Subtarget->hasMMX()) break;
10276      return std::make_pair(0U, X86::VR64RegisterClass);
10277    case 'Y':   // SSE_REGS if SSE2 allowed
10278      if (!Subtarget->hasSSE2()) break;
10279      // FALL THROUGH.
10280    case 'x':   // SSE_REGS if SSE1 allowed
10281      if (!Subtarget->hasSSE1()) break;
10282
10283      switch (VT.getSimpleVT().SimpleTy) {
10284      default: break;
10285      // Scalar SSE types.
10286      case MVT::f32:
10287      case MVT::i32:
10288        return std::make_pair(0U, X86::FR32RegisterClass);
10289      case MVT::f64:
10290      case MVT::i64:
10291        return std::make_pair(0U, X86::FR64RegisterClass);
10292      // Vector types.
10293      case MVT::v16i8:
10294      case MVT::v8i16:
10295      case MVT::v4i32:
10296      case MVT::v2i64:
10297      case MVT::v4f32:
10298      case MVT::v2f64:
10299        return std::make_pair(0U, X86::VR128RegisterClass);
10300      }
10301      break;
10302    }
10303  }
10304
10305  // Use the default implementation in TargetLowering to convert the register
10306  // constraint into a member of a register class.
10307  std::pair<unsigned, const TargetRegisterClass*> Res;
10308  Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
10309
10310  // Not found as a standard register?
10311  if (Res.second == 0) {
10312    // Map st(0) -> st(7) -> ST0
10313    if (Constraint.size() == 7 && Constraint[0] == '{' &&
10314        tolower(Constraint[1]) == 's' &&
10315        tolower(Constraint[2]) == 't' &&
10316        Constraint[3] == '(' &&
10317        (Constraint[4] >= '0' && Constraint[4] <= '7') &&
10318        Constraint[5] == ')' &&
10319        Constraint[6] == '}') {
10320
10321      Res.first = X86::ST0+Constraint[4]-'0';
10322      Res.second = X86::RFP80RegisterClass;
10323      return Res;
10324    }
10325
10326    // GCC allows "st(0)" to be called just plain "st".
10327    if (StringRef("{st}").equals_lower(Constraint)) {
10328      Res.first = X86::ST0;
10329      Res.second = X86::RFP80RegisterClass;
10330      return Res;
10331    }
10332
10333    // flags -> EFLAGS
10334    if (StringRef("{flags}").equals_lower(Constraint)) {
10335      Res.first = X86::EFLAGS;
10336      Res.second = X86::CCRRegisterClass;
10337      return Res;
10338    }
10339
10340    // 'A' means EAX + EDX.
10341    if (Constraint == "A") {
10342      Res.first = X86::EAX;
10343      Res.second = X86::GR32_ADRegisterClass;
10344      return Res;
10345    }
10346    return Res;
10347  }
10348
10349  // Otherwise, check to see if this is a register class of the wrong value
10350  // type.  For example, we want to map "{ax},i32" -> {eax}, we don't want it to
10351  // turn into {ax},{dx}.
10352  if (Res.second->hasType(VT))
10353    return Res;   // Correct type already, nothing to do.
10354
10355  // All of the single-register GCC register classes map their values onto
10356  // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp".  If we
10357  // really want an 8-bit or 32-bit register, map to the appropriate register
10358  // class and return the appropriate register.
10359  if (Res.second == X86::GR16RegisterClass) {
10360    if (VT == MVT::i8) {
10361      unsigned DestReg = 0;
10362      switch (Res.first) {
10363      default: break;
10364      case X86::AX: DestReg = X86::AL; break;
10365      case X86::DX: DestReg = X86::DL; break;
10366      case X86::CX: DestReg = X86::CL; break;
10367      case X86::BX: DestReg = X86::BL; break;
10368      }
10369      if (DestReg) {
10370        Res.first = DestReg;
10371        Res.second = X86::GR8RegisterClass;
10372      }
10373    } else if (VT == MVT::i32) {
10374      unsigned DestReg = 0;
10375      switch (Res.first) {
10376      default: break;
10377      case X86::AX: DestReg = X86::EAX; break;
10378      case X86::DX: DestReg = X86::EDX; break;
10379      case X86::CX: DestReg = X86::ECX; break;
10380      case X86::BX: DestReg = X86::EBX; break;
10381      case X86::SI: DestReg = X86::ESI; break;
10382      case X86::DI: DestReg = X86::EDI; break;
10383      case X86::BP: DestReg = X86::EBP; break;
10384      case X86::SP: DestReg = X86::ESP; break;
10385      }
10386      if (DestReg) {
10387        Res.first = DestReg;
10388        Res.second = X86::GR32RegisterClass;
10389      }
10390    } else if (VT == MVT::i64) {
10391      unsigned DestReg = 0;
10392      switch (Res.first) {
10393      default: break;
10394      case X86::AX: DestReg = X86::RAX; break;
10395      case X86::DX: DestReg = X86::RDX; break;
10396      case X86::CX: DestReg = X86::RCX; break;
10397      case X86::BX: DestReg = X86::RBX; break;
10398      case X86::SI: DestReg = X86::RSI; break;
10399      case X86::DI: DestReg = X86::RDI; break;
10400      case X86::BP: DestReg = X86::RBP; break;
10401      case X86::SP: DestReg = X86::RSP; break;
10402      }
10403      if (DestReg) {
10404        Res.first = DestReg;
10405        Res.second = X86::GR64RegisterClass;
10406      }
10407    }
10408  } else if (Res.second == X86::FR32RegisterClass ||
10409             Res.second == X86::FR64RegisterClass ||
10410             Res.second == X86::VR128RegisterClass) {
10411    // Handle references to XMM physical registers that got mapped into the
10412    // wrong class.  This can happen with constraints like {xmm0} where the
10413    // target independent register mapper will just pick the first match it can
10414    // find, ignoring the required type.
10415    if (VT == MVT::f32)
10416      Res.second = X86::FR32RegisterClass;
10417    else if (VT == MVT::f64)
10418      Res.second = X86::FR64RegisterClass;
10419    else if (X86::VR128RegisterClass->hasType(VT))
10420      Res.second = X86::VR128RegisterClass;
10421  }
10422
10423  return Res;
10424}
10425